Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#findAndRegisterModules()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#findAndRegisterModules() . 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: TwitchHelixBuilder.java    From twitch4j with MIT License 8 votes vote down vote up
/**
 * Twitch API Client (Helix)
 *
 * @return TwitchHelix
 */
public TwitchHelix build() {
    log.debug("Helix: Initializing Module ...");

    // Hystrix
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds", timeout);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.command.default.requestCache.enabled", false);
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.maxQueueSize", getRequestQueueSize());
    ConfigurationManager.getConfigInstance().setProperty("hystrix.threadpool.default.queueSizeRejectionThreshold", getRequestQueueSize());

    // Jackson ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    // - Modules
    mapper.findAndRegisterModules();

    // Feign
    TwitchHelix client = HystrixFeign.builder()
        .client(new OkHttpClient())
        .encoder(new JacksonEncoder(mapper))
        .decoder(new JacksonDecoder(mapper))
        .logger(new Logger.ErrorLogger())
        .errorDecoder(new TwitchHelixErrorDecoder(new JacksonDecoder()))
        .requestInterceptor(new TwitchHelixClientIdInterceptor(this))
        .options(new Request.Options(timeout / 3, TimeUnit.MILLISECONDS, timeout, TimeUnit.MILLISECONDS, true))
        .retryer(new Retryer.Default(500, timeout, 2))
        .target(TwitchHelix.class, baseUrl);

    return client;
}
 
Example 2
Source File: PanacheFunctionalityTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * _PanacheEntityBase_ has the method _isPersistent_. This method is used by Jackson to serialize the attribute *peristent*
 * in the JSON which is not intended. This test ensures that the attribute *persistent* is not generated when using Jackson.
 * 
 * This test does not interact with the Quarkus application itself. It is just using the Jackson ObjectMapper with a
 * PanacheEntity. Thus this test is disabled in native mode. The test code runs the JVM and not native.
 */
@DisabledOnNativeImage
@Test
public void jacksonDeserializationIgnoresPersistentAttribute() throws JsonProcessingException {
    // set Up
    Person person = new Person();
    person.name = "max";
    // do
    ObjectMapper objectMapper = new ObjectMapper();
    // make sure the Jaxb module is loaded
    objectMapper.findAndRegisterModules();
    String personAsString = objectMapper.writeValueAsString(person);
    // check 
    // hence no 'persistence'-attribute
    assertEquals(
            "{\"id\":null,\"name\":\"max\",\"uniqueName\":null,\"address\":null,\"status\":null,\"dogs\":[],\"serialisationTrick\":1}",
            personAsString);
}
 
Example 3
Source File: TeamsPagedMembersResult.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Converts a PagedMembersResult to a TeamsPagedMembersResult.
 * 
 * @param pagedMembersResult The PagedMembersResult value.
 */
public TeamsPagedMembersResult(PagedMembersResult pagedMembersResult) {
    continuationToken = pagedMembersResult.getContinuationToken();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();

    members = pagedMembersResult.getMembers().stream().map(channelAccount -> {
        try {
            // convert fro ChannelAccount to TeamsChannelAccount by going to JSON then back
            // to TeamsChannelAccount.
            // Is this really the most efficient way to handle this?
            JsonNode node = objectMapper.valueToTree(channelAccount);
            return objectMapper.treeToValue(node, TeamsChannelAccount.class);
        } catch (JsonProcessingException jpe) {
            // this would be a conversion error. for now, return null and filter the results
            // below. there is probably a more elegant way to handle this.
            return null;
        }
    }).collect(Collectors.toCollection(ArrayList::new));

    members.removeIf(Objects::isNull);
}
 
Example 4
Source File: ActivityTest.java    From botbuilder-java with MIT License 6 votes vote down vote up
@Test
public void GetInformationForMicrosoftTeams() throws JsonProcessingException, IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    Activity activity = objectMapper.readValue(ActivityTest.serializedActivityFromTeams, Activity.class);
    Assert.assertEquals("19:[email protected]", activity.teamsGetChannelId());
    Assert.assertEquals("19:[email protected]", activity.teamsGetTeamId());
    Assert.assertEquals(true, activity.isTeamsActivity());

    activity = objectMapper.readValue(ActivityTest.serializedActivityFromTeamsWithoutTeamsChannelIdorTeamId,
            Activity.class);

    Assert.assertEquals("channel_id", activity.teamsGetChannelId());
    Assert.assertEquals("team_id", activity.teamsGetTeamId());

    TeamsChannelData teamsChannelData = activity.getChannelData(TeamsChannelData.class);
    Assert.assertEquals("channel_id", teamsChannelData.getChannel().getId());
    Assert.assertEquals("channel_name", teamsChannelData.getChannel().getName());
    Assert.assertEquals("team_id", teamsChannelData.getTeam().getId());
    Assert.assertEquals("team_name", teamsChannelData.getTeam().getName());
    Assert.assertEquals("aad_groupid", teamsChannelData.getTeam().getAadGroupId());
    Assert.assertEquals(true, teamsChannelData.getNotification().getAlert());
    Assert.assertEquals("teamMemberAdded", teamsChannelData.getEventType());
    Assert.assertEquals("tenant_id", teamsChannelData.getTenant().getId());
}
 
Example 5
Source File: CacheConfig.java    From todolist with MIT License 6 votes vote down vote up
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
	RedisTemplate<Object, Object> template = new RedisTemplate<>();
	template.setConnectionFactory(factory);

	Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
	ObjectMapper mapper = new ObjectMapper();
	mapper.findAndRegisterModules();
	mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
	mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
	jackson2JsonRedisSerializer.setObjectMapper(mapper);

	template.setValueSerializer(jackson2JsonRedisSerializer);
	template.setKeySerializer(new StringRedisSerializer());

	template.afterPropertiesSet();

	return template;
}
 
Example 6
Source File: TeamsActivityHandler.java    From botbuilder-java with MIT License 6 votes vote down vote up
protected CompletableFuture<Void> onTeamsMembersRemovedDispatch(
    List<ChannelAccount> membersRemoved,
    TeamInfo teamInfo,
    TurnContext turnContext
) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();

    List<TeamsChannelAccount> teamsMembersRemoved = new ArrayList<>();
    for (ChannelAccount memberRemoved : membersRemoved) {
        try {
            JsonNode node = mapper.valueToTree(memberRemoved);
            teamsMembersRemoved.add(mapper.treeToValue(node, TeamsChannelAccount.class));
        } catch (JsonProcessingException jpe) {
            return withException(jpe);
        }
    }

    return onTeamsMembersRemoved(teamsMembersRemoved, teamInfo, turnContext);
}
 
Example 7
Source File: RedisTemplateConfiguration.java    From mica with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * value 值 序列化
 *
 * @return RedisSerializer
 */
@Bean
@ConditionalOnMissingBean(RedisSerializer.class)
public RedisSerializer<Object> redisSerializer(MicaRedisProperties properties,
											   ObjectProvider<ObjectMapper> objectProvider) {
	MicaRedisProperties.SerializerType serializerType = properties.getSerializerType();
	if (MicaRedisProperties.SerializerType.JDK == serializerType) {
		return new JdkSerializationRedisSerializer();
	}
	// jackson findAndRegisterModules,use copy
	ObjectMapper objectMapper = objectProvider.getIfAvailable(ObjectMapper::new).copy();
	// findAndRegisterModules
	objectMapper.findAndRegisterModules();
	// class type info to json
	GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null);
	objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(), DefaultTyping.NON_FINAL, As.PROPERTY);
	return new GenericJackson2JsonRedisSerializer(objectMapper);
}
 
Example 8
Source File: Jackson.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
	mapper.findAndRegisterModules();
	SimpleModule module = new SimpleModule();
	mapper.registerModule(module);
	mapper.enable(SerializationFeature.INDENT_OUTPUT);
	mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
	mapper.setSerializationInclusion(Include.NON_NULL);
	return mapper;
}
 
Example 9
Source File: InventoryItemDomain.java    From cqrs-eventsourcing-kafka with Apache License 2.0 5 votes vote down vote up
private static void configureObjectMapper(Environment environment) {
    ObjectMapper mapper = environment.getObjectMapper();
    mapper.findAndRegisterModules();

    SimpleModule module = new SimpleModule();
    module.addSerializer(ID.class, new IDSerializer());
    mapper.registerModule(module);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example 10
Source File: InventoryItemApi.java    From cqrs-eventsourcing-kafka with Apache License 2.0 5 votes vote down vote up
private static void configureObjectMapper(Environment environment) {
    ObjectMapper mapper = environment.getObjectMapper();
    mapper.findAndRegisterModules();

    SimpleModule module = new SimpleModule();
    module.addSerializer(ID.class, new IDSerializer());
    mapper.registerModule(module);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
 
Example 11
Source File: CustomDeserializationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
    String converted = objectMapper.writeValueAsString(now);
    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("restored: " + restored);
    assertThat(now, is(restored));
}
 
Example 12
Source File: CustomDeserializationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
    String converted = objectMapper.writeValueAsString(now);
    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("restored: " + restored);
    assertThat(now, is(not(restored)));
}
 
Example 13
Source File: OpenLRW.java    From OpenLRW with Educational Community License v2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.setDateFormat(new ISO8601DateFormat());
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}
 
Example 14
Source File: ApprovalTestApplication.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private void initObjectMapper(CrnkFeature feature) {
    ObjectMapper objectMapper = feature.getObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.findAndRegisterModules();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
 
Example 15
Source File: ApplicationConfiguration.java    From cerberus with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper getObjectMapper() {
  ObjectMapper om = new ObjectMapper();
  om.findAndRegisterModules();
  om.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
  om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  om.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
  om.enable(SerializationFeature.INDENT_OUTPUT);
  return om;
}
 
Example 16
Source File: JacksonDateUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect()
  throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));
    String converted = objectMapper.writeValueAsString(now);
 
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    System.out.println("serialized: " + now);
    System.out.println("restored: " + restored);
    assertThat(now, is(restored));
}
 
Example 17
Source File: TranscriptBaseTests.java    From botbuilder-java with MIT License 4 votes vote down vote up
protected TranscriptBaseTests() {
    mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
}
 
Example 18
Source File: TestConversionConfig.java    From elastic-crud with Apache License 2.0 4 votes vote down vote up
@Bean
ObjectMapper objectMapper() {
  final ObjectMapper mapper = new ObjectMapper();
  mapper.findAndRegisterModules();
  return mapper;
}
 
Example 19
Source File: ConnectWatsonIoTQRadar.java    From qradar-monitor-device-events with Apache License 2.0 4 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	try {
		response.setContentType("application/json");
		setAccessControlHeaders(response);
		StringBuilder sb = new StringBuilder();
		String s;
		while ((s = request.getReader().readLine()) != null) {
			sb.append(s);
		}
		Logger.getLogger(getServletName()).log(Level.INFO,"Connecting Watson IoT to QRadar with - " + sb.toString());
		JSONObject req = new JSONObject(sb.toString());
		//{"deviceId":"","deviceType":""}
		String deviceId = req.getString("deviceId");
		String deviceType = req.getString("deviceType");
		
		ObjectMapper mapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER));
		mapper.findAndRegisterModules();
		String fileUrl = URLDecoder.decode(getClass().getResource("/appconfig.yaml").getFile(), StandardCharsets.UTF_8.toString());
		Config config = mapper.readValue(new File(fileUrl), Config.class);
		config.getAuth().setKey(IoTConfig.apikey);
		config.getAuth().setToken(IoTConfig.token);
		
		mapper.writeValue(new File(fileUrl), config);

		ApplicationClient client = new ApplicationClient(fileUrl);
		client.connect();
		AppEventCallbackJson evtCallback = new AppEventCallbackJson();
		AppStatusCallback statusCallback = new AppStatusCallback();
		client.registerCodec(new JsonCodec());
		client.registerEventCallback(evtCallback);
		client.setStatusCallback(statusCallback);
		
		client.subscribeToDeviceEvents(deviceType, deviceId, "security", "json", 1);
		client.subscribeToDeviceStatus(deviceType, deviceId);

		Logger.getLogger(getServletName()).log(Level.INFO,"Subscribing to device events! " + sb.toString());
		JSONObject res = new JSONObject();
        res.put("response", "Successfully connected Watson IoT to QRadar!" + sb.toString());
		response.getWriter().append(res.toString());
		
	} catch (Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 20
Source File: RedisConfiguration.java    From WTFDYUM with Apache License 2.0 4 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    final ObjectMapper result = new ObjectMapper();
    result.findAndRegisterModules();
    return result;
}