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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#addMixIn() . 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: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a json string using the swagger object.
 *
 * @param swaggerObj swagger object
 * @return json string using the swagger object
 * @throws APIManagementException error while creating swagger json
 */
public static String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    //this is to ignore "originalRef" in schema objects
    mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);

    //this is to ignore "responseSchema" in response schema objects
    mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
    try {
        return new String(mapper.writeValueAsBytes(swaggerObj));
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while generating Swagger json from model", e);
    }
}
 
Example 2
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a json string using the swagger object.
 *
 * @param swaggerObj swagger object
 * @return json string using the swagger object
 * @throws APIManagementException error while creating swagger json
 */
private String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    //this is to ignore "originalRef" in schema objects
    mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
    mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);

    //this is to ignore "responseSchema" in response schema objects
    mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
    try {
        return new String(mapper.writeValueAsBytes(swaggerObj));
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while generating Swagger json from model", e);
    }
}
 
Example 3
Source File: ExportMain.java    From opsgenie-configuration-backup with Apache License 2.0 6 votes vote down vote up
private static void configureDefaultApiClient(String apiKey, String opsGenieHost, boolean debug) {
    final ApiClient defaultApiClient = Configuration.getDefaultApiClient();
    defaultApiClient.setApiKeyPrefix("GenieKey");
    defaultApiClient.setApiKey(apiKey);
    defaultApiClient.setBasePath(opsGenieHost);
    defaultApiClient.setDebugging(debug);

    ObjectMapper mapper = defaultApiClient.getJSON().getContext(Object.class);
    mapper.addMixIn(Recipient.class, IgnoredIdAndType.class);
    mapper.addMixIn(Filter.class, IgnoredType.class);
    mapper.addMixIn(TimeRestrictionInterval.class, IgnoredType.class);
    mapper.addMixIn(DeprecatedAlertPolicy.class, IgnoredType.class);
    mapper.addMixIn(Integration.class, IgnoredType.class);
    mapper.addMixIn(BaseIntegrationAction.class, IgnoredIdAndType.class);
    mapper.addMixIn(Responder.class, IgnoredType.class);
    mapper.addMixIn(Policy.class, IgnoredType.class);
}
 
Example 4
Source File: OffsetTimeDeserializerIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
    OffsetTime offsetTime = OffsetTime.of(10, 15, 30, 0, ZoneOffset.ofHours(1));

    ObjectMapper mapper = createMapper();
    mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
    TemporalAccessor value = mapper.readValue("[\"" + OffsetTime.class.getName() + "\",\"10:15:30+01:00\"]", TemporalAccessor.class);

    assertNotNull(value);
    assertTrue(value instanceof OffsetTime, "The value should be a OffsetTime.");
    assertEquals(offsetTime, value);
}
 
Example 5
Source File: JacksonJsonLayout.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
protected ObjectWriter createConfiguredWriter(List<JacksonMixIn> mixins) {

            ObjectMapper objectMapper = createDefaultObjectMapper();
            objectMapper.registerModule(new ExtendedLog4j2JsonModule());

            if (useAfterburner) {
                // com.fasterxml.jackson.module:jackson-module-afterburner required here
                new JacksonAfterburnerModuleConfigurer().configure(objectMapper);
            }

            for (JacksonMixIn mixin : mixins) {
                objectMapper.addMixIn(mixin.getTargetClass(), mixin.getMixInClass());
            }

            ValueResolver valueResolver = createValueResolver();

            for (VirtualProperty property : virtualProperties) {
                if (!property.isDynamic()) {
                    property.setValue(valueResolver.resolve(property.getValue()));
                }
            }

            SerializationConfig customConfig = objectMapper.getSerializationConfig()
                    .with(new JacksonHandlerInstantiator(
                            virtualProperties,
                            valueResolver,
                            virtualPropertyFilters
                    ));

            objectMapper.setConfig(customConfig);

            return objectMapper.writer(new MinimalPrettyPrinter());

        }
 
Example 6
Source File: BufferedBulkOperations.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * @return {@code com.fasterxml.jackson.databind.ObjectWriter} to serialize {@link BufferedIndex} instances
 */
protected ObjectWriter configuredWriter() {

    ObjectMapper objectMapper = new ExtendedObjectMapper(new JsonFactory())
            .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .configure(SerializationFeature.CLOSE_CLOSEABLE, false)
            .addMixIn(BufferedIndex.class, BulkableActionMixIn.class);

    for (JacksonMixIn mixIn: mixIns) {
        objectMapper.addMixIn(mixIn.getTargetClass(), mixIn.getMixInClass());
    }

    return objectMapper.writerFor(BufferedIndex.class);
}
 
Example 7
Source File: IronTestUtils.java    From irontest with Apache License 2.0 5 votes vote down vote up
public static void addMixInsForWireMock(ObjectMapper objectMapper) {
    objectMapper.addMixIn(StubMapping.class, StubMappingMixIn.class);
    objectMapper.addMixIn(RequestPattern.class, RequestPatternMixIn.class);
    objectMapper.addMixIn(StringValuePattern.class, StringValuePatternMixIn.class);
    objectMapper.addMixIn(ResponseDefinition.class, ResponseDefinitionMixIn.class);
    objectMapper.addMixIn(ContentPattern.class, ContentPatternMixIn.class);
    objectMapper.addMixIn(LoggedResponse.class, LoggedResponseMixIn.class);
    objectMapper.addMixIn(ServeEvent.class, ServeEventMixIn.class);
    objectMapper.addMixIn(LoggedRequest.class, LoggedRequestMixIn.class);
}
 
Example 8
Source File: JsonHelper.java    From spark-dependencies with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper configure(ObjectMapper objectMapper) {
  objectMapper.addMixIn(Span.class, SpanMixin.class);
  objectMapper.addMixIn(KeyValue.class, KeyValueMixin.class);
  objectMapper.addMixIn(Reference.class, ReferenceMixin.class);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return objectMapper;
}
 
Example 9
Source File: HodRequestMapper.java    From find with MIT License 5 votes vote down vote up
@Override
protected void addCustomMixins(final ObjectMapper objectMapper, final QueryRestrictionsBuilder<?, ?, ?> queryRestrictionsBuilder, final QueryRequestBuilder<?, ?, ?> queryRequestBuilder) {
    objectMapper.addMixIn(HodQueryRequest.class, HodQueryRequestMixin.class);
    objectMapper.addMixIn(queryRequestBuilder.getClass(), HodQueryRequestBuilderMixins.class);
    objectMapper.addMixIn(HodQueryRestrictions.class, HodQueryRestrictionsMixin.class);
    objectMapper.addMixIn(queryRestrictionsBuilder.getClass(), HodQueryRestrictionsBuilderMixins.class);
}
 
Example 10
Source File: ZonedDateTimeDeserializerIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
    ZonedDateTime zonedDateTime = ZonedDateTime.of(2017, 9, 2, 10, 15, 30, 0, ZoneOffset.ofHours(1));

    ObjectMapper mapper = createMapper();
    mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
    TemporalAccessor value = mapper.readValue("[\"" + ZonedDateTime.class.getName() + "\",\"2017-09-02T10:15:30+01:00\"]", TemporalAccessor.class);

    assertNotNull(value);
    assertTrue(value instanceof ZonedDateTime, "The value should be a ZonedDateTime.");
    assertEquals(zonedDateTime, value);
}
 
Example 11
Source File: JWTOrFormAuthenticationFilterTest.java    From shiro-jwt with MIT License 5 votes vote down vote up
@Before
public void setUp() throws MalformedURLException {
    Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
    target = client.target(URI.create(new URL(base, "resources/test").toExternalForm()));

    objectMapper = new ObjectMapper();
    objectMapper.addMixIn(TokenResponse.class, MixInExample.class);
}
 
Example 12
Source File: DefaultFeatureSupport.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Bootstrap<?> bootstrap) {
    ObjectMapper om = bootstrap.getObjectMapper();

    // for Config
    om.addMixIn(SessionStore.class, sessionStoreMixin());
    om.addMixIn(Authorizer.class, authorizerMixin());
    om.addMixIn(HttpActionAdapter.class, httpActionAdapterMixin());
    om.addMixIn(Matcher.class, matcherMixin());
    om.addMixIn(SecurityLogic.class, securityLogicMixin());
    om.addMixIn(CallbackLogic.class, callbackLogicMixin());
    om.addMixIn(LogoutLogic.class, logoutLogicMixin());

    // for Clients
    om.addMixIn(Client.class, clientMixin());
    om.addMixIn(BaseClient.class, baseClientMixin());

    // for Clients and Client subsclasses
    om.addMixIn(AjaxRequestResolver.class, ajaxRequestResolverMixin());
    om.addMixIn(UrlResolver.class, urlResolverMixin());
    om.addMixIn(CallbackUrlResolver.class, callbackUrlResolverMixin());
    om.addMixIn(AuthorizationGenerator.class,
            authorizationGeneratorMixin());

    // for Client/BaseClient
    om.addMixIn(Authenticator.class, authenticatorMixin());
    om.addMixIn(CredentialsExtractor.class, credentialExtractorMixin());
    om.addMixIn(ProfileCreator.class, profileCreatorMixin());

    // for IndirectClient
    om.addMixIn(RedirectActionBuilder.class, redirectActionBuilderMixin());
    om.addMixIn(LogoutActionBuilder.class, logoutActionBuilderMixin());
    
    // for some of the Authenticators
    om.addMixIn(PasswordEncoder.class, passwordEncoderMixin());
}
 
Example 13
Source File: QueryTest.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    mapper = new ObjectMapper();
    mapper.addMixIn(Aggregation.class, TypeNameMixin.class);
    mapper.registerModule(new Jdk8Module());
    mapper.registerSubtypes(new NamedType(Group.class, Group.NAME));
    mapper.registerSubtypes(new NamedType(Empty.class, Empty.NAME));
}
 
Example 14
Source File: ObjectMapperMixInTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@Test
void scaUserDataMixIn() throws JsonProcessingException, JSONException {
    // Given
    String expected = "{\"id\":\"id\",\"login\":\"login\",\"email\":\"email\",\"pin\":\"pin\",\"scaUserData\":[{\"id\":\"id\",\"scaMethod\":\"EMAIL\",\"methodValue\":\"methodValue\",\"user\":null,\"usesStaticTan\":true,\"staticTan\":\"STATIC TAN\", \"decoupled\":false, \"valid\":false}],\"accountAccesses\":[],\"userRoles\":[],\"branch\":\"branch\",\"blocked\":false,\"systemBlocked\":false}";
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixIn(ScaUserDataTO.class, ScaUserDataMixedIn.class);

    UserTO user = getUser();

    // When
    String result = objectMapper.writeValueAsString(user);

    // Then
    JSONAssert.assertEquals(result, expected, true);
}
 
Example 15
Source File: ImportMain.java    From opsgenie-configuration-backup with Apache License 2.0 5 votes vote down vote up
private static void configureClientObjectMapper(ApiClient defaultApiClient) {
    ObjectMapper mapper = defaultApiClient.getJSON().getContext(Object.class);
    mapper.addMixIn(Filter.class, IgnoredType.class);
    mapper.addMixIn(TimeRestrictionInterval.class, IgnoredType.class);
    mapper.addMixIn(Recipient.class, IgnoredType.class);
    mapper.addMixIn(DeprecatedAlertPolicy.class, IgnoredType.class);
    mapper.addMixIn(Integration.class, IgnoredType.class);
    mapper.addMixIn(BaseIntegrationAction.class, IgnoredIntegration.class);
    mapper.addMixIn(Policy.class, IgnoredType.class);
    mapper.addMixIn(Responder.class, IgnoredType.class);
}
 
Example 16
Source File: JacksonAnnotationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializingUsingMixInAnnotation_thenCorrect() throws JsonProcessingException {
    final com.baeldung.jackson.annotation.dtos.Item item = new com.baeldung.jackson.annotation.dtos.Item(1, "book", null);

    String result = new ObjectMapper().writeValueAsString(item);
    assertThat(result, containsString("owner"));

    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(com.baeldung.jackson.annotation.dtos.User.class, MyMixInForIgnoreType.class);

    result = mapper.writeValueAsString(item);
    assertThat(result, not(containsString("owner")));
}
 
Example 17
Source File: JacksonSerializationIgnoreUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
    final MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
    dtoObject.setBooleanValue(true);

    final String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
    System.out.println(dtoAsString);
}
 
Example 18
Source File: OffsetDateTimeDeserializerIT.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
    OffsetDateTime offsetDateTime = OffsetDateTime.of(2017, 9, 2, 10, 15, 30, 0, ZoneOffset.ofHours(1));

    ObjectMapper mapper = createMapper();
    mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
    TemporalAccessor value = mapper.readValue("[\"" + OffsetDateTime.class.getName() + "\",\"2017-09-02T10:15:30+01:00\"]", TemporalAccessor.class);

    assertNotNull(value, "The value should not be null.");
    assertTrue(value instanceof OffsetDateTime, "The value should be a OffsetDateTime.");
    assertEquals(offsetDateTime, value, "The value is not correct.");
}
 
Example 19
Source File: JacksonJsonProvider.java    From paseto with MIT License 4 votes vote down vote up
public static void registerMixins(ObjectMapper mapper) {
	mapper.addMixIn(Token.class, TokenMixIn.class);
	mapper.addMixIn(KeyId.class, KeyIdMixIn.class);
}
 
Example 20
Source File: RegisteredServiceJsonSerializer.java    From springboot-shiro-cas-mybatis with MIT License 3 votes vote down vote up
/**
 * Mixins are added to the object mapper in order to
 * ignore certain method signatures from serialization
 * that are otherwise treated as getters. Each mixin
 * implements the appropriate interface as a private
 * dummy class and is annotated with JsonIgnore elements
 * throughout. This helps us catch errors at compile-time
 * when the interface changes.
 * @return the prepped object mapper.
 */
@Override
protected ObjectMapper initializeObjectMapper() {
    final ObjectMapper mapper = super.initializeObjectMapper();
    mapper.addMixIn(RegisteredServiceProxyPolicy.class, RegisteredServiceProxyPolicyMixin.class);
    mapper.addMixIn(RegisteredServiceAccessStrategy.class, RegisteredServiceAuthorizationStrategyMixin.class);
    mapper.addMixIn(Duration.class, DurationMixin.class);
    return mapper;
}