com.fasterxml.jackson.databind.JsonMappingException Java Examples
The following examples show how to use
com.fasterxml.jackson.databind.JsonMappingException.
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: KibanaImporter.java From arctic-sea with Apache License 2.0 | 6 votes |
public void importJson(String jsonString) throws JsonParseException, JsonMappingException, IOException { Objects.requireNonNull(jsonString); // delete .kibana index try { client.delete(new DeleteRequest(kibanaIndexName), RequestOptions.DEFAULT); } catch (ElasticsearchException ex) { LOG.debug("Tried to delete kibana index " + kibanaIndexName + " but it is not exists", ex); } ObjectMapper mapper = new ObjectMapper(); KibanaConfigHolderDto holder = mapper.readValue(jsonString, KibanaConfigHolderDto.class); for (KibanaConfigEntryDto dto : holder.getEntries()) { processDto(dto); LOG.debug("Importing {}", dto); CreateIndexResponse response = client.indices().create(new CreateIndexRequest(kibanaIndexName), RequestOptions.DEFAULT); // client.prepareIndex(kibanaIndexName, dto.getType(), dto.getId()) // .setSource(dto.getSource()).get(); } }
Example #2
Source File: ReadCompJsonFile.java From singleton with Eclipse Public License 2.0 | 6 votes |
public static DBI18nDocument Json2DBDoc(TransCompDocFile compDoc) throws JsonParseException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); logger.info(compDoc.getDocFile().getAbsolutePath()); StringBuilder strBuilder = file2String(compDoc.getDocFile(), StandardCharsets.UTF_8); logger.debug(strBuilder.toString()); DBI18nDocument doc = mapper.readValue(strBuilder.toString(), DBI18nDocument.class); logger.debug("bundle doc component:" + doc.getComponent()); logger.debug("bundle doc locale:" + doc.getComponent()); doc.setProduct(compDoc.getProduct()); doc.setVersion(compDoc.getVersion()); doc.setComponent(compDoc.getComponent()); doc.setLocale(compDoc.getLocale()); return doc; }
Example #3
Source File: SendGridHttpTest.java From ogham with Apache License 2.0 | 6 votes |
@Test public void authenticationFailed() throws MessagingException, JsonParseException, JsonMappingException, IOException { // @formatter:off server.stubFor(post("/api/mail.send.json") .willReturn(aResponse() .withStatus(400) .withBody(loadJson("/stubs/responses/authenticationFailed.json")))); // @formatter:on // @formatter:off Email email = new Email() .subject(SUBJECT) .content(CONTENT_TEXT) .from(FROM_ADDRESS) .to(TO_ADDRESS_1); // @formatter:on MessagingException e = assertThrows(MessagingException.class, () -> { messagingService.send(email); }, "throws message exception"); assertThat("sendgrid exception", e.getCause(), allOf(notNullValue(), instanceOf(SendGridException.class))); assertThat("root cause", e.getCause().getCause(), allOf(notNullValue(), instanceOf(IOException.class))); assertThat("sendgrid message", e.getCause().getCause().getMessage(), Matchers.equalTo("Sending to SendGrid failed: (400) {\n" + " \"errors\": [\"The provided authorization grant is invalid, expired, or revoked\"],\n" + " \"message\": \"error\"\n" + "}")); }
Example #4
Source File: JsonDBRawMetrics.java From syndesis with Apache License 2.0 | 6 votes |
/** * If Integrations get deleted we should also delete their metrics */ @Override public void curate(Set<String> activeIntegrationIds) throws IOException, JsonMappingException { //1. Loop over all RawMetrics String json = jsonDB.getAsString(path(), new GetOptions().depth(1)); if (json != null) { Map<String,Boolean> metricsMap = JsonUtils.reader().forType(TYPE_REFERENCE).readValue(json); Set<String> rawIntegrationIds = metricsMap.keySet(); for (String rawIntId : rawIntegrationIds) { if (! activeIntegrationIds.contains(rawIntId)) { jsonDB.delete(path(rawIntId)); } } } }
Example #5
Source File: JsonToGuavaMultimap.java From levelup-java-examples with Apache License 2.0 | 6 votes |
@Test public void convert() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new GuavaModule()); Multimap<String, NavItem> navs = objectMapper.readValue( objectMapper.treeAsTokens(objectMapper.readTree(jsonString)), objectMapper.getTypeFactory().constructMapLikeType( Multimap.class, String.class, NavItem.class)); logger.info(navs); assertThat(navs.keys(), hasItems("123455", "999999")); }
Example #6
Source File: JsonMapperProviderTest.java From conductor with Apache License 2.0 | 6 votes |
@Test public void testSimpleMapping() throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper m = new JsonMapperProvider().get(); assertTrue(m.canSerialize(Any.class)); Struct struct1 = Struct.newBuilder().putFields( "some-key", Value.newBuilder().setStringValue("some-value").build() ).build(); Any source = Any.pack(struct1); StringWriter buf = new StringWriter(); m.writer().writeValue(buf, source); Any dest = m.reader().forType(Any.class).readValue(buf.toString()); assertEquals(source.getTypeUrl(), dest.getTypeUrl()); Struct struct2 = dest.unpack(Struct.class); assertTrue(struct2.containsFields("some-key")); assertEquals( struct1.getFieldsOrThrow("some-key").getStringValue(), struct2.getFieldsOrThrow("some-key").getStringValue() ); }
Example #7
Source File: UmAuthenticationChecker.java From wecube-platform with Apache License 2.0 | 6 votes |
private UmUserAuthResultDto performUserAuthentication(UmAuthContext authCtx, UmSubSystemAuthResultDto subSystemAuthResult, UsernamePasswordAuthenticationToken userToken) throws JsonParseException, JsonMappingException, IOException { String host = authCtx.getHost(); int port = authCtx.getPort(); String userId = userToken.getName(); String pwd = (String) userToken.getCredentials(); String appid = subSystemAuthResult.getId(); String tmp = generatePwd(userId, pwd); String timeStamp = String.valueOf(System.currentTimeMillis() / 1000); String sign = md5(userId + tmp + timeStamp); String token = subSystemAuthResult.getTok(); String auth = subSystemAuthResult.getAuth(); String url = String.format( "http://%s:%s/um_service?style=6&appid=%s&id=%s&sign=%s&timeStamp=%s&token=%s&auth=%s", host, port, appid, userId, sign, timeStamp, token, auth); HttpHeaders headers = new HttpHeaders(); ResponseEntity<String> resp = sendGetRequestWithUrlParamMap(restTemplate, url, headers, String.class); UmUserAuthResultDto authResult = objectMapper.readValue(resp.getBody(), UmUserAuthResultDto.class); return authResult; }
Example #8
Source File: PoliciesDataTest.java From pulsar with Apache License 2.0 | 6 votes |
@Test public void bundlesData() throws JsonParseException, JsonMappingException, IOException { ObjectMapper jsonMapper = ObjectMapperFactory.create(); String newJsonPolicy = "{\"auth_policies\":{\"namespace_auth\":{},\"destination_auth\":{}},\"replication_clusters\":[],\"bundles\":{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]},\"backlog_quota_map\":{},\"persistence\":null,\"latency_stats_sample_rate\":{}}"; List<String> bundleSet = Lists.newArrayList(); bundleSet.add("0x00000000"); bundleSet.add("0xffffffff"); String newBundlesDataString = "{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]}"; BundlesData data = jsonMapper.readValue(newBundlesDataString.getBytes(), BundlesData.class); assertEquals(data.getBoundaries(), bundleSet); Policies policies = jsonMapper.readValue(newJsonPolicy.getBytes(), Policies.class); Policies expected = new Policies(); expected.bundles = data; assertEquals(policies, expected); }
Example #9
Source File: AbstractJackson2HttpMessageConverter.java From spring-analysis-note with MIT License | 6 votes |
/** * Determine whether to log the given exception coming from a * {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check. * @param type the class that Jackson tested for (de-)serializability * @param cause the Jackson-thrown exception to evaluate * (typically a {@link JsonMappingException}) * @since 4.3 */ protected void logWarningIfNecessary(Type type, @Nullable Throwable cause) { if (cause == null) { return; } // Do not log warning for serializer not found (note: different message wording on Jackson 2.9) boolean debugLevel = (cause instanceof JsonMappingException && cause.getMessage().startsWith("Cannot find")); if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) { String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") + "serialization for type [" + type + "]"; if (debugLevel) { logger.debug(msg, cause); } else if (logger.isDebugEnabled()) { logger.warn(msg, cause); } else { logger.warn(msg + ": " + cause); } } }
Example #10
Source File: WfdescAgent.java From incubator-taverna-language with Apache License 2.0 | 6 votes |
public void annotateT2flows() throws JsonParseException, JsonMappingException, IOException { String query = "PREFIX ro: <http://purl.org/wf4ever/ro#> " + "" + " SELECT ?ro ?p ?s ?name WHERE { " + "?ro a ?x ;" + " ?p ?s ." + "?s ro:name ?name ." + " FILTER REGEX(?name, \"t2flow$\") } "; for (JsonNode binding : sparql(query)) { System.out.print( binding.path("ro").path("value").asText()); System.out.print( binding.path("p").path("value").asText()); System.out.print( binding.path("s").path("value").asText()); System.out.println( binding.path("name").path("value").asText()); } }
Example #11
Source File: BeanValidation.java From open-Autoscaler with Apache License 2.0 | 6 votes |
public static JsonNode parseScalingHistory(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{ List<String> violation_message = new ArrayList<String>(); ObjectNode result = new_mapper.createObjectNode(); result.put("valid", false); JavaType javaType = getCollectionType(ArrayList.class, ArrayList.class, HistoryData.class); new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType); ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Locale locale = LocaleUtil.getLocale(httpServletRequest); MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale); Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator(); Set<ConstraintViolation<List<HistoryData>>> set = validator.validate(scalinghistory); if (set.size() > 0 ){ for (ConstraintViolation<List<HistoryData>> constraintViolation : set) { violation_message.add(constraintViolation.getMessage()); } result.set("violation_message", new_mapper.valueToTree(violation_message)); return result; } //additional data manipulation String new_json = transformHistory(scalinghistory); result.put("valid", true); result.put("new_json", new_json); return result; }
Example #12
Source File: DiffTest.java From milkman with MIT License | 6 votes |
@Test public void shouldMergeCorrectlyAddCollection() throws JsonParseException, JsonMappingException, IOException { String colId = UUID.randomUUID().toString(); String colId2 = UUID.randomUUID().toString(); List<Collection> base = new LinkedList<Collection>(); base.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList())); List<Collection> working = new LinkedList<Collection>(); working.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList())); working.add(new Collection(colId2, "collection2", false, new LinkedList<>(), Collections.emptyList())); CollectionDiffer collectionDiffer = new CollectionDiffer(); DiffNode diffNode = collectionDiffer.compare(working, base); collectionDiffer.mergeDiffs(working, base, diffNode); assertThat(base.size()).isEqualTo(2); assertThat(base.get(0).getId()).isEqualTo(colId); assertThat(base.get(0).getName()).isEqualTo("collection1"); assertThat(base.get(1).getId()).isEqualTo(colId2); assertThat(base.get(1).getName()).isEqualTo("collection2"); }
Example #13
Source File: KogitoSpringObjectMapper.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, property.getType().containedType(0)); DataStreamDeserializer deserializer = new DataStreamDeserializer(); deserializer.collectionType = collectionType; return deserializer; }
Example #14
Source File: RefStdDeserializer.java From gwt-jackson with Apache License 2.0 | 5 votes |
@Override public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException { if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null ) { throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." ); } return new RefStdDeserializer( ctxt.getContextualType().containedType( 0 ) ); }
Example #15
Source File: ConfiguredBean.java From logsniffer with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void resolve(final DeserializationContext ctxt) throws JsonMappingException { if (defaultDeserializer instanceof ResolvableDeserializer) { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } }
Example #16
Source File: ConfigTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testIsAuthentication() throws JsonGenerationException, JsonMappingException, IOException { // given System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString()); String ssl = "true"; // when Map<String, String> configValues = ImmutableMap.of("smtp.authentication", ssl); File tempConfig = createTempConfig(configValues); Config config = new Config(); // then assertThat(config.isSmtpAuthentication(), equalTo(Boolean.valueOf(ssl))); assertThat(tempConfig.delete(), equalTo(true)); }
Example #17
Source File: AWSServiceSerdeTest.java From cloudformation-cli-java-plugin with Apache License 2.0 | 5 votes |
@Test public void notObjectStart() { JsonMappingException exception = Assertions.assertThrows(JsonMappingException.class, () -> serializer.deserialize("[]", new TypeReference<AllPrimitives>() { })); assertThat(exception.getMessage()).contains("Expected to be in START_OBJECT got"); }
Example #18
Source File: ConfigTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testGetCorsUrlPatternDefaultValue() throws JsonGenerationException, JsonMappingException, IOException { // given System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString()); // when Map<String, String> configValues = new HashMap<>(); File tempConfig = createTempConfig(configValues); Config config = new Config(); // then assertThat(config.getCorsUrlPattern().toString(), equalTo(Pattern.compile(Default.CORS_URLPATTERN.toString()).toString())); assertThat(tempConfig.delete(), equalTo(true)); }
Example #19
Source File: CliqueConfigurationTest.java From SciGraph with Apache License 2.0 | 5 votes |
@Before public void setup() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { URL url = this.getClass().getResource("/cliqueConfiguration.yaml"); File configFile = new File(url.getFile()); assertThat(configFile.exists(), is(true)); OwlLoadConfigurationLoader owlLoadConfigurationLoader = new OwlLoadConfigurationLoader(configFile); loaderConfig = owlLoadConfigurationLoader.loadConfig(); cliqueConfiguration = loaderConfig.getCliqueConfiguration().get(); }
Example #20
Source File: RefactoringPopulator.java From RefactoringMiner with MIT License | 5 votes |
private static void prepareFSERefactorings(TestBuilder test, BigInteger flag) throws JsonParseException, JsonMappingException, IOException { List<Root> roots = getFSERefactorings(flag); for (Root root : roots) { test.project(root.repository, "master").atCommit(root.sha1) .containsOnly(extractRefactorings(root.refactorings)); } }
Example #21
Source File: ConfigTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testGetSmptHostDefaultValue() throws JsonGenerationException, JsonMappingException, IOException { // given System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString()); // when Map<String, String> configValues = new HashMap<>(); File tempConfig = createTempConfig(configValues); Config config = new Config(); // then assertThat(config.getSmtpHost(), equalTo(Default.SMTP_HOST.toString())); assertThat(tempConfig.delete(), equalTo(true)); }
Example #22
Source File: UnknownPropertiesUnitTest.java From tutorials with MIT License | 5 votes |
@Test(expected = UnrecognizedPropertyException.class) public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException { final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}"; final ObjectMapper mapper = new ObjectMapper(); final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); assertNotNull(readValue); assertThat(readValue.getStringValue(), equalTo("a")); assertThat(readValue.isBooleanValue(), equalTo(true)); assertThat(readValue.getIntValue(), equalTo(1)); }
Example #23
Source File: PolicyEnbale.java From open-Autoscaler with Apache License 2.0 | 5 votes |
public String transformInput() throws JsonParseException, JsonMappingException, IOException{ Map<String, String> result = new HashMap<String, String>(); if (this.enable == true) { result.put("state", "enabled"); } else { result.put("state", "disabled"); } return BeanValidation.new_mapper.writeValueAsString(result); }
Example #24
Source File: ConfigTest.java From mangooio with Apache License 2.0 | 5 votes |
@Test public void testGetAuthenticationCookieExpiresDefaultValue() throws JsonGenerationException, JsonMappingException, IOException { // given System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString()); // when Map<String, String> configValues = new HashMap<>(); File tempConfig = createTempConfig(configValues); Config config = new Config(); // then assertThat(config.isAuthenticationCookieExpires(), equalTo(Default.AUTHENTICATION_COOKIE_EXPIRES.toBoolean())); assertThat(tempConfig.delete(), equalTo(true)); }
Example #25
Source File: KogitoQuarkusObjectMapper.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, property.getType().containedType(0)); DataStreamDeserializer deserializer = new DataStreamDeserializer(); deserializer.collectionType = collectionType; return deserializer; }
Example #26
Source File: Metrics.java From open-Autoscaler with Apache License 2.0 | 5 votes |
public String transformOutput() throws JsonParseException, JsonMappingException, IOException{ String current_json = BeanValidation.new_mapper.writeValueAsString(this.data); JsonNode top = BeanValidation.new_mapper.readTree(current_json); JsonObjectComparator comparator = new JsonObjectComparator("timestamp", "long"); Iterator<JsonNode> elements = top.elements(); List<JsonNode> elements_sorted = new ArrayList<JsonNode>(); while(elements.hasNext()){ elements_sorted.add(elements.next()); } Collections.sort(elements_sorted, comparator); ObjectNode jNode = BeanValidation.new_mapper.createObjectNode(); List<JsonNode> sub_list; long last_timestamp; int max_len = Integer.parseInt(ConfigManager.get("maxMetricRecord")); BeanValidation.logger.info("Current maxMetricRecord returned is " + max_len + " and current number of metric record is " + elements_sorted.size()); if(elements_sorted.size() > max_len){ sub_list = elements_sorted.subList(0, max_len); JsonNode last_metric = elements_sorted.get(max_len-1); last_timestamp = last_metric.get("timestamp").asLong(); } else { sub_list = elements_sorted; last_timestamp = 0; } JsonNodeFactory factory = JsonNodeFactory.instance; ArrayNode aaData = new ArrayNode(factory); aaData.addAll(sub_list); jNode.set("data", aaData); jNode.put("timestamp", last_timestamp); return jNode.toString(); }
Example #27
Source File: YearMonthSerializer.java From jackson-modules-java8 with Apache License 2.0 | 5 votes |
@Override protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException { SerializerProvider provider = visitor.getProvider(); boolean useTimestamp = (provider != null) && useTimestamp(provider); if (useTimestamp) { super._acceptTimestampVisitor(visitor, typeHint); } else { JsonStringFormatVisitor v2 = visitor.expectStringFormat(typeHint); if (v2 != null) { v2.format(JsonValueFormat.DATE_TIME); } } }
Example #28
Source File: OptionDeserializer.java From cyclops with Apache License 2.0 | 5 votes |
@Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { if (valueType.isContainerType()) { deser = ctxt.findRootValueDeserializer(valueType.getContentType()); }else{ deser = ctxt.findRootValueDeserializer(valueType.containedTypeOrUnknown(0)); } }
Example #29
Source File: SubscriptionManagerTest.java From joynr with Apache License 2.0 | 5 votes |
@Test public void registerBroadcastSubscription() throws JoynrSendBufferFullException, JoynrMessageNotSentException, JsonGenerationException, JsonMappingException, IOException { String broadcastName = "broadcastName"; BroadcastSubscriptionListener broadcastSubscriptionListener = mock(LocationUpdateBroadcastListener.class); BroadcastSubscribeInvocation subscriptionRequest = new BroadcastSubscribeInvocation(broadcastName, broadcastSubscriptionListener, onChangeQos, future); subscriptionManager.registerBroadcastSubscription(fromParticipantId, new HashSet<DiscoveryEntryWithMetaInfo>(Arrays.asList(toDiscoveryEntry)), subscriptionRequest); subscriptionId = subscriptionRequest.getSubscriptionId(); verify(broadcastSubscriptionDirectory).put(Mockito.anyString(), Mockito.eq(broadcastSubscriptionListener)); verify(subscriptionStates).put(Mockito.anyString(), Mockito.any(PubSubState.class)); verify(cleanupScheduler).schedule(Mockito.any(Runnable.class), Mockito.eq(onChangeQos.getExpiryDateMs()), Mockito.eq(TimeUnit.MILLISECONDS)); verify(subscriptionEndFutures, Mockito.times(1)).put(Mockito.eq(subscriptionId), Mockito.any(ScheduledFuture.class)); verify(dispatcher).sendSubscriptionRequest(eq(fromParticipantId), eq(new HashSet<DiscoveryEntryWithMetaInfo>(Arrays.asList(toDiscoveryEntry))), any(SubscriptionRequest.class), any(MessagingQos.class)); }
Example #30
Source File: Serializer.java From kylin with Apache License 2.0 | 5 votes |
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException { if (null == value) { return null; } return JsonUtil.readValue(value, type); }