Example usage for com.fasterxml.jackson.databind ObjectMapper getSerializationConfig

List of usage examples for com.fasterxml.jackson.databind ObjectMapper getSerializationConfig

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper getSerializationConfig.

Prototype

public SerializationConfig getSerializationConfig() 

Source Link

Document

Method that returns the shared default SerializationConfig object that defines configuration settings for serialization.

Usage

From source file:org.hawkular.bus.common.BasicMessageObjectMapperTest.java

@Override
protected ObjectMapper buildObjectMapperForSerialization() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
            .withGetterVisibility((SUPPORT_GETTER_SETTER) ? JsonAutoDetect.Visibility.PUBLIC_ONLY
                    : JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility((SUPPORT_GETTER_SETTER) ? JsonAutoDetect.Visibility.PUBLIC_ONLY
                    : JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
}

From source file:capital.scalable.restdocs.payload.JacksonResponseFieldSnippetTest.java

@Test
public void noResponseBody() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "noItem");

    this.snippet.expectResponseFields().withContents(equalTo("No response body."));

    new JacksonResponseFieldSnippet()
            .document(operationBuilder.attribute(HandlerMethod.class.getName(), handlerMethod)
                    .attribute(ObjectMapper.class.getName(), mapper).request("http://localhost").build());
}

From source file:org.usrz.libs.webtools.validation.ValidationInterceptor.java

@Inject
private ValidationInterceptor(ObjectMapper objectMapper) {
    validator = Validation.buildDefaultValidatorFactory().getValidator();
    log.info("Validation interceptor using validator %s", validator);
    naming = objectMapper.getSerializationConfig().getPropertyNamingStrategy();
    withName = nameFor("constraintViolations");
}

From source file:capital.scalable.restdocs.payload.JacksonResponseFieldSnippetTest.java

@Test
public void listResponse() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "getItems");
    JavadocReader javadocReader = mock(JavadocReader.class);
    when(javadocReader.resolveFieldComment(Item.class, "field1")).thenReturn("A string");
    when(javadocReader.resolveFieldComment(Item.class, "field2")).thenReturn("A decimal");

    this.snippet.expectResponseFields()
            .withContents(tableWithPrefix("\n",
                    tableWithHeader("Path", "Type", "Optional", "Description")
                            .row("[].field1", "String", "true", "A string.")
                            .row("[].field2", "Decimal", "true", "A decimal.")));

    new JacksonResponseFieldSnippet()
            .document(operationBuilder.attribute(HandlerMethod.class.getName(), handlerMethod)
                    .attribute(ObjectMapper.class.getName(), mapper)
                    .attribute(JavadocReader.class.getName(), javadocReader)
                    .attribute(ConstraintReader.class.getName(), mock(ConstraintReader.class))
                    .request("http://localhost").build());
}

From source file:capital.scalable.restdocs.payload.JacksonResponseFieldSnippetTest.java

@Test
public void simpleResponse() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "getItem");
    JavadocReader javadocReader = mock(JavadocReader.class);
    when(javadocReader.resolveFieldComment(Item.class, "field1")).thenReturn("A string");
    when(javadocReader.resolveFieldComment(Item.class, "field2")).thenReturn("A decimal");

    ConstraintReader constraintReader = mock(ConstraintReader.class);
    when(constraintReader.isMandatory(NotBlank.class)).thenReturn(true);
    when(constraintReader.getOptionalMessages(Item.class, "field1")).thenReturn(singletonList("false"));
    when(constraintReader.getConstraintMessages(Item.class, "field2"))
            .thenReturn(singletonList("A constraint"));

    this.snippet.expectResponseFields()
            .withContents(tableWithPrefix("\n",
                    tableWithHeader("Path", "Type", "Optional", "Description")
                            .row("field1", "String", "false", "A string.")
                            .row("field2", "Decimal", "true", "A decimal." + lineBreak() + "A constraint.")));

    new JacksonResponseFieldSnippet().document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(ObjectMapper.class.getName(), mapper)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader).request("http://localhost").build());
}

From source file:capital.scalable.restdocs.payload.JacksonResponseFieldSnippetTest.java

@Test
public void pageResponse() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "pagedItems");
    JavadocReader javadocReader = mock(JavadocReader.class);
    when(javadocReader.resolveFieldComment(Item.class, "field1")).thenReturn("A string");
    when(javadocReader.resolveFieldComment(Item.class, "field2")).thenReturn("A decimal");

    ConstraintReader constraintReader = mock(ConstraintReader.class);
    when(constraintReader.isMandatory(NotBlank.class)).thenReturn(true);
    when(constraintReader.getOptionalMessages(Item.class, "field1")).thenReturn(singletonList("false"));
    when(constraintReader.getConstraintMessages(Item.class, "field2"))
            .thenReturn(singletonList("A constraint"));

    this.snippet.expectResponseFields()
            .withContents(tableWithPrefix(paginationPrefix(),
                    tableWithHeader("Path", "Type", "Optional", "Description")
                            .row("field1", "String", "false", "A string.")
                            .row("field2", "Decimal", "true", "A decimal." + lineBreak() + "A constraint.")));

    new JacksonResponseFieldSnippet().document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(ObjectMapper.class.getName(), mapper)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader).request("http://localhost").build());
}

From source file:capital.scalable.restdocs.payload.JacksonResponseFieldSnippetTest.java

@Test
public void responseEntityResponse() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    HandlerMethod handlerMethod = new HandlerMethod(new TestResource(), "responseEntityItem");
    JavadocReader javadocReader = mock(JavadocReader.class);
    when(javadocReader.resolveFieldComment(Item.class, "field1")).thenReturn("A string");
    when(javadocReader.resolveFieldComment(Item.class, "field2")).thenReturn("A decimal");

    ConstraintReader constraintReader = mock(ConstraintReader.class);
    when(constraintReader.isMandatory(NotBlank.class)).thenReturn(true);
    when(constraintReader.getOptionalMessages(Item.class, "field1")).thenReturn(singletonList("false"));
    when(constraintReader.getConstraintMessages(Item.class, "field2"))
            .thenReturn(singletonList("A constraint"));

    this.snippet.expectResponseFields()
            .withContents(tableWithPrefix("\n",
                    tableWithHeader("Path", "Type", "Optional", "Description")
                            .row("field1", "String", "false", "A string.")
                            .row("field2", "Decimal", "true", "A decimal." + lineBreak() + "A constraint.")));

    new JacksonResponseFieldSnippet().document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(ObjectMapper.class.getName(), mapper)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader).request("http://localhost").build());
}

From source file:it.smartcommunitylab.aac.controller.ResourceAccessController.java

@ApiOperation(value = "Get token info")
@RequestMapping(method = RequestMethod.GET, value = "/resources/token")
@Deprecated/*from   w  w w  . java2s.  co  m*/
public @ResponseBody AACTokenValidation getTokenInfo(HttpServletRequest request, HttpServletResponse response) {
    AACTokenValidation result = new AACTokenValidation();

    try {
        String parsedToken = it.smartcommunitylab.aac.common.Utils.parseHeaderToken(request);

        OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(parsedToken);

        OAuth2AccessToken storedToken = tokenStore.getAccessToken(auth);
        long expiresIn = storedToken.getExpiresIn();

        String clientId = auth.getOAuth2Request().getClientId();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.ANY)
                .withSetterVisibility(JsonAutoDetect.Visibility.ANY)
                .withCreatorVisibility(JsonAutoDetect.Visibility.ANY));

        String userName = null;
        String userId = null;
        boolean applicationToken = false;

        //         System.err.println(auth.getPrincipal());

        if (auth.getPrincipal() instanceof User) {
            User principal = (User) auth.getPrincipal();
            userId = principal.getUsername();
            //         } if (auth.getPrincipal() instanceof it.smartcommunitylab.aac.model.User) { 
            //            it.smartcommunitylab.aac.model.User principal = (it.smartcommunitylab.aac.model.User)auth.getPrincipal();
            //            userId = principal.getId().toString();
            //            userName = getWSO2Name(user);
        } else {
            ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId);
            applicationToken = true;
            userId = "" + client.getDeveloperId();
            //            if (client.getParameters() != null) {
            //               Map<String,?> parameters = mapper.readValue(client.getParameters(), Map.class);
            //               userName = (String)parameters.get("username");
            //            } else {
            ////               it.smartcommunitylab.aac.model.User user = userRepository.findOne(Long.parseLong(userId));
            //               userName = "admin";
            //               userName = (String)auth.getPrincipal();
            //            }
        }
        userName = userManager.getUserInternalName(Long.parseLong(userId));

        result.setUsername(userName);
        result.setUserId(userId);
        result.setClientId(clientId);
        result.setScope(Iterables.toArray(auth.getOAuth2Request().getScope(), String.class));
        result.setGrantType(auth.getOAuth2Request().getGrantType());

        long now = System.currentTimeMillis();
        result.setIssuedTime(now);
        result.setValidityPeriod(expiresIn);

        logger.info("Requested token " + parsedToken + " expires in " + result.getValidityPeriod());

        result.setValid(true);

        result.setApplicationToken(applicationToken);

        //         System.err.println(mapper.writeValueAsString(response));         
    } catch (InvalidTokenException e) {
        logger.error("Invalid token: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    } catch (Exception e) {
        logger.error("Error getting info for token: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    return result;
}

From source file:org.hawkular.bus.common.AbstractMessage.java

/**
 * @return object mapper to be used to serialize a message to JSON
 *///from w ww .j a  v  a2 s  .c om
protected ObjectMapper buildObjectMapperForSerialization() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    return mapper;
}

From source file:gaffer.rest.service.SimpleGraphConfigurationService.java

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override/* w w w  . ja v a  2  s.c  om*/
public Set<String> getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(className);
    } catch (Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();

    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }

    return fields;
}