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

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

Introduction

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

Prototype

public ObjectMapper disable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig features.

Usage

From source file:com.ikanow.aleph2.data_model.utils.BeanTemplateUtils.java

/** Configures a mapper with the desired properties for use in Aleph2
 * @param configure_me - leave this empty to create a new mapper, or add one to configure an existing mapper
 * @return//w  ww.j ava  2s.co m
 */
public static ObjectMapper configureMapper(final Optional<ObjectMapper> configure_me) {
    final ObjectMapper mapper = configure_me.orElse(new ObjectMapper());
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);

    final SimpleModule module = new SimpleModule();
    module.addDeserializer(Number.class, new NumberDeserializer());
    mapper.registerModule(module);

    return mapper;
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapComplexTypes(List<APITypeModel> typeModels, Field fields[], boolean onlyConsumeField) {
    //Should strip duplicate types
    Set<String> typesInList = new HashSet<>();
    typeModels.forEach(type -> {//from   w w w .  j  av  a  2s .co m
        typesInList.add(type.getName());
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    for (Field field : fields) {
        boolean capture = true;
        if (onlyConsumeField) {
            ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
            if (consumeField == null) {
                capture = false;
            }
        }

        if (capture) {

            Class fieldClass = field.getType();
            DataType dataType = (DataType) field.getAnnotation(DataType.class);
            if (dataType != null) {
                fieldClass = dataType.value();
            }

            if (ReflectionUtil.isComplexClass(fieldClass)) {

                APITypeModel typeModel = new APITypeModel();
                typeModel.setName(fieldClass.getSimpleName());

                APIDescription aPIDescription = (APIDescription) fieldClass.getAnnotation(APIDescription.class);
                if (aPIDescription != null) {
                    typeModel.setDescription(aPIDescription.value());
                }

                Set<String> fieldList = mapValueField(typeModel.getFields(), fieldClass.getDeclaredFields(),
                        onlyConsumeField);
                if (fieldClass.isEnum()) {
                    typeModel.setObject(Arrays.toString(fieldClass.getEnumConstants()));
                } else {
                    if (fieldClass.isInterface() == false) {
                        try {
                            typeModel.setObject(objectMapper.writeValueAsString(fieldClass.newInstance()));

                            String cleanUpJson = StringProcessor.stripeFieldJSON(typeModel.getObject(),
                                    fieldList);
                            typeModel.setObject(cleanUpJson);

                        } catch (InstantiationException | IllegalAccessException | JsonProcessingException ex) {
                            log.log(Level.WARNING,
                                    "Unable to process/map complex field: " + fieldClass.getSimpleName(), ex);
                            typeModel.setObject("{ Unable to view }");
                        }
                        mapComplexTypes(typeModels, fieldClass.getDeclaredFields(), onlyConsumeField);
                    }
                }
                typeModels.add(typeModel);
                typesInList.add(typeModel.getName());
            }

        }
    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapConsumedObjects(APIMethodModel methodModel, Parameter parameters[]) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    for (Parameter parameter : parameters) {
        //deterimine if this is "Body" object
        List<Annotation> paramAnnotation = new ArrayList<>();
        paramAnnotation.add(parameter.getAnnotation(QueryParam.class));
        paramAnnotation.add(parameter.getAnnotation(FormParam.class));
        paramAnnotation.add(parameter.getAnnotation(MatrixParam.class));
        paramAnnotation.add(parameter.getAnnotation(HeaderParam.class));
        paramAnnotation.add(parameter.getAnnotation(CookieParam.class));
        paramAnnotation.add(parameter.getAnnotation(PathParam.class));
        paramAnnotation.add(parameter.getAnnotation(BeanParam.class));

        boolean consumeObject = true;
        for (Annotation annotation : paramAnnotation) {
            if (annotation != null) {
                consumeObject = false;//from www  .  jav a2 s. c o m
                break;
            }
        }

        if (consumeObject) {
            APIValueModel valueModel = new APIValueModel();
            try {
                valueModel.setValueObjectName(parameter.getType().getSimpleName());

                DataType dataType = (DataType) parameter.getAnnotation(DataType.class);
                if (dataType != null) {
                    String typeName = dataType.value().getSimpleName();
                    if (StringUtils.isNotBlank(dataType.actualClassName())) {
                        typeName = dataType.actualClassName();
                    }
                    valueModel.setTypeObjectName(typeName);

                    try {
                        valueModel
                                .setTypeObject(objectMapper.writeValueAsString(dataType.value().newInstance()));
                        Set<String> fieldList = mapValueField(valueModel.getTypeFields(),
                                ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true);
                        String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getTypeObject(),
                                fieldList);
                        valueModel.setTypeObject(cleanUpJson);
                        mapComplexTypes(valueModel.getAllComplexTypes(),
                                ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true);

                        APIDescription aPIDescription = (APIDescription) dataType.value()
                                .getAnnotation(APIDescription.class);
                        if (aPIDescription != null) {
                            valueModel.setTypeDescription(aPIDescription.value());
                        }

                    } catch (InstantiationException iex) {
                        log.log(Level.WARNING,
                                MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        parameter.getType()));
                    }
                } else {
                    try {
                        valueModel.setValueObject(
                                objectMapper.writeValueAsString(parameter.getType().newInstance()));
                        Set<String> fieldList = mapValueField(valueModel.getValueFields(),
                                ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true);
                        String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getValueObject(),
                                fieldList);
                        valueModel.setValueObject(cleanUpJson);
                        mapComplexTypes(valueModel.getAllComplexTypes(),
                                ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true);

                        APIDescription aPIDescription = (APIDescription) parameter.getType()
                                .getAnnotation(APIDescription.class);
                        if (aPIDescription != null) {
                            valueModel.setTypeDescription(aPIDescription.value());
                        }

                    } catch (InstantiationException iex) {
                        log.log(Level.WARNING,
                                MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        parameter.getType()));
                    }
                }
            } catch (IllegalAccessException | JsonProcessingException ex) {
                log.log(Level.WARNING, null, ex);
            }

            //There can only be one consume(Request Body Parameter) object
            //We take the first one and ignore the rest.
            methodModel.setConsumeObject(valueModel);
            break;
        }
    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

public static APIResourceModel processRestClass(Class resource, String rootPath) {
    APIResourceModel resourceModel = new APIResourceModel();

    resourceModel.setClassName(resource.getName());
    resourceModel.setResourceName(/*from www  .j  a  va  2s .c  o m*/
            String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName())));

    APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class);
    if (aPIDescription != null) {
        resourceModel.setResourceDescription(aPIDescription.value());
    }

    Path path = (Path) resource.getAnnotation(Path.class);
    if (path != null) {
        resourceModel.setResourcePath(rootPath + "/" + path.value());
    }

    RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class);
    if (requireAdmin != null) {
        resourceModel.setRequireAdmin(true);
    }

    //class parameters
    mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields());

    //methods
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    int methodId = 0;
    for (Method method : resource.getDeclaredMethods()) {

        APIMethodModel methodModel = new APIMethodModel();
        methodModel.setId(methodId++);

        //rest method
        List<String> restMethods = new ArrayList<>();
        GET getMethod = (GET) method.getAnnotation(GET.class);
        POST postMethod = (POST) method.getAnnotation(POST.class);
        PUT putMethod = (PUT) method.getAnnotation(PUT.class);
        DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class);
        if (getMethod != null) {
            restMethods.add("GET");
        }
        if (postMethod != null) {
            restMethods.add("POST");
        }
        if (putMethod != null) {
            restMethods.add("PUT");
        }
        if (deleteMethod != null) {
            restMethods.add("DELETE");
        }
        methodModel.setRestMethod(String.join(",", restMethods));

        if (restMethods.isEmpty()) {
            //skip non-rest methods
            continue;
        }

        //produces
        Produces produces = (Produces) method.getAnnotation(Produces.class);
        if (produces != null) {
            methodModel.setProducesTypes(String.join(",", produces.value()));
        }

        //consumes
        Consumes consumes = (Consumes) method.getAnnotation(Consumes.class);
        if (consumes != null) {
            methodModel.setConsumesTypes(String.join(",", consumes.value()));
        }

        aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class);
        if (aPIDescription != null) {
            methodModel.setDescription(aPIDescription.value());
        }

        path = (Path) method.getAnnotation(Path.class);
        if (path != null) {
            methodModel.setMethodPath(path.value());
        }

        requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class);
        if (requireAdmin != null) {
            methodModel.setRequireAdmin(true);
        }

        try {
            if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) {
                APIValueModel valueModel = new APIValueModel();
                DataType dataType = (DataType) method.getAnnotation(DataType.class);

                boolean addResponseObject = true;
                if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) {
                    addResponseObject = false;
                }

                if (addResponseObject) {
                    valueModel.setValueObjectName(method.getReturnType().getSimpleName());
                    ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class);
                    Class returnTypeClass;
                    if (returnType != null) {
                        returnTypeClass = returnType.value();
                    } else {
                        returnTypeClass = method.getReturnType();
                    }

                    if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) {
                        if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) {
                            try {
                                valueModel.setValueObject(
                                        objectMapper.writeValueAsString(returnTypeClass.newInstance()));
                                mapValueField(valueModel.getValueFields(),
                                        ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]));
                                mapComplexTypes(valueModel.getAllComplexTypes(),
                                        ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]),
                                        false);

                                aPIDescription = (APIDescription) returnTypeClass
                                        .getAnnotation(APIDescription.class);
                                if (aPIDescription != null) {
                                    valueModel.setValueDescription(aPIDescription.value());
                                }
                            } catch (InstantiationException iex) {
                                log.log(Level.WARNING, MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        returnTypeClass));
                            }
                        }
                    }

                    if (dataType != null) {
                        String typeName = dataType.value().getSimpleName();
                        if (StringUtils.isNotBlank(dataType.actualClassName())) {
                            typeName = dataType.actualClassName();
                        }
                        valueModel.setTypeObjectName(typeName);
                        try {
                            valueModel.setTypeObject(
                                    objectMapper.writeValueAsString(dataType.value().newInstance()));
                            mapValueField(valueModel.getTypeFields(),
                                    ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]));
                            mapComplexTypes(valueModel.getAllComplexTypes(),
                                    ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false);

                            aPIDescription = (APIDescription) dataType.value()
                                    .getAnnotation(APIDescription.class);
                            if (aPIDescription != null) {
                                valueModel.setTypeDescription(aPIDescription.value());
                            }

                        } catch (InstantiationException iex) {
                            log.log(Level.WARNING, MessageFormat.format(
                                    "Unable to instantiated type: {0} make sure the type is not abstract.",
                                    dataType.value()));
                        }
                    }

                    methodModel.setResponseObject(valueModel);
                }
            }
        } catch (IllegalAccessException | JsonProcessingException ex) {
            log.log(Level.WARNING, null, ex);
        }

        //method parameters
        mapMethodParameters(methodModel.getMethodParams(), method.getParameters());

        //Handle Consumed Objects
        mapConsumedObjects(methodModel, method.getParameters());

        resourceModel.getMethods().add(methodModel);
    }
    Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>());
    return resourceModel;
}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * Initialize mapper//from  w  w w .  ja v a2s .co  m
 * 
 * @return initialized {@link ObjectMapper}
 */
private static ObjectMapper initMapper() {

    ObjectMapper mapper = new ObjectMapper();
    // to enable standard indentation ("pretty-printing"):
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    // to allow serialization of "empty" POJOs (no properties to serialize)
    // (without this setting, an exception is thrown in those cases)
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    // set writer flush after writer value
    mapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    // ObjectMapper will call close() and root values that implement
    // java.io.Closeable;
    // including cases where exception is thrown and serialization does not
    // completely succeed.
    mapper.enable(SerializationFeature.CLOSE_CLOSEABLE);
    // to write java.util.Date, Calendar as number (timestamp):
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    // disable default date to timestamp
    mapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

    // DeserializationFeature for changing how JSON is read as POJOs:

    // to prevent exception when encountering unknown property:
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    // disable default date to timestamp
    mapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
    // to allow coercion of JSON empty String ("") to null Object value:
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    // Set Default date fromat
    mapper.setDateFormat(df);

    return mapper;

}

From source file:org.jongo.marshall.jackson.configuration.PropertyModifier.java

public void modify(ObjectMapper mapper) {
    mapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setSerializationInclusion(NON_NULL);
}

From source file:org.jongo.marshall.jackson.configuration.VisibilityModifier.java

public void modify(ObjectMapper mapper) {
    mapper.disable(AUTO_DETECT_SETTERS);
    mapper.disable(AUTO_DETECT_GETTERS);

    VisibilityChecker<?> checker = mapper.getSerializationConfig().getDefaultVisibilityChecker();
    mapper.setVisibilityChecker(checker.withFieldVisibility(ANY));
}

From source file:org.moserp.common.json_schema.ObjectMapperBuilder.java

public ObjectMapper build() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    registerQuantitySerializer(mapper);/*from  w w w  .j  a  v  a2s .  c o  m*/
    mapper.registerModules(new MoneyModule(), new JavaTimeModule(), new Jackson2HalModule());

    return mapper;
}

From source file:com.gwtplatform.carstore.server.api.JacksonProvider.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException {
    ObjectMapper mapper = locateMapper(type, mediaType);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}

From source file:uk.co.flax.biosolr.ontology.core.ols.terms.RelatedTermsResultTest.java

@Test
public void deserialize_fromFile() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    RelatedTermsResult result = mapper.readValue(OLSHttpClientTest.getFile(RESULT_FILE),
            RelatedTermsResult.class);
    assertNotNull(result);//from   www  .  jav  a2s.  c  o m
    assertNotNull(result.getLinks());
    assertNotNull(result.getEmbedded());
    assertFalse(result.getTerms().isEmpty());
    assertNotNull(result.getPage());
    assertEquals(0, result.getPage().getNumber());
}