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

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

Introduction

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

Prototype

public ObjectMapper setSerializationInclusion(JsonInclude.Include incl) 

Source Link

Document

Method for setting defalt POJO property inclusion strategy for serialization.

Usage

From source file:whitespell.net.websockets.socketio.parser.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(JsonObject.class, jsonObjectDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //        TODO If jsonObjectDeserializer will be not enough
    //        TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL);
    //        typer.init(JsonTypeInfo.Id.CLASS, null);
    //        typer.inclusion(JsonTypeInfo.As.PROPERTY);
    //        typer.typeProperty(configuration.getJsonTypeFieldName());
    //        objectMapper.setDefaultTyping(typer);
}

From source file:org.codemine.smartgarden.controller.SmartGardenServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www.  j  a  v  a2 s  .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    DateFormat chartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(chartDateFormat);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    RequestResult requestResult = new RequestResult();
    SmartGardenService smartGardenService = (SmartGardenService) request.getServletContext()
            .getAttribute(SERVICE_KEY);
    String action = (String) request.getParameter("action");
    if (action.equalsIgnoreCase("get_image")) {
        String filename = (String) request.getParameter("filename");
        File imageFile = smartGardenService.getImage(filename);
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        try (OutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", outputStream);
        }
        return;
    }
    try {

        if (!StringUtils.isEmpty(action)) {
            if (action.equalsIgnoreCase("start_irrigation")) {
                logger.log(Level.INFO, "processRequest:start_irrigation");
                requestResult = new RequestResult<Integer>();
                Integer historyId = smartGardenService.startIrrigationAsync(this.getDataSource());
                requestResult.setSuccess(true);
                requestResult.setValue(historyId);
            }
            if (action.equalsIgnoreCase("get_irrigation_history")) {
                logger.log(Level.INFO, "processRequest:get_irrigation_history");
                List<IrrigationHistory> historyList = smartGardenService
                        .getIrrigationHistoryList(this.getDataSource(), 10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_garden_status")) {
                logger.log(Level.INFO, "processRequest:get_garden_status");
                GardenStatus gardenStatus = smartGardenService.getGardenStatus(this.getDataSource());
                requestResult.setValue(gardenStatus);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("stop_irrigation")) {
                logger.log(Level.INFO, "processRequest:stop_irrigation");

                String historyIdParam = request.getParameter("historyId");
                Integer historyId = null;
                if (!StringUtils.isEmpty(historyIdParam)) {
                    historyId = Integer.parseInt(historyIdParam);
                }
                smartGardenService.stopIrrigation(this.getDataSource(), historyId);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("set_irrigation_duration")) {
                logger.log(Level.INFO, "processRequest:set_irrigation_duration");
                String irrigationDurationInSecond = (String) request.getParameter("duration");
                final long newIrrigationDurationInSecond = smartGardenService
                        .setIrrigationDuration(Integer.parseInt(irrigationDurationInSecond));
                requestResult.setSuccess(true);
                requestResult.setValue(newIrrigationDurationInSecond);
            }

            if (action.equalsIgnoreCase("get_soil_status_history")) {
                logger.log(Level.INFO, "processRequest:get_soil_status_history");
                List<SoilStatus> historyList = smartGardenService.getSoilStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_power_status_history")) {
                logger.log(Level.INFO, "processRequest:get_power_status_history");
                List<PowerStatus> historyList = smartGardenService.getPowerStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("take_photo")) {
                logger.log(Level.INFO, "processRequest:take_photo");
                String photoFilename = smartGardenService.takePhoto();
                requestResult.setValue(photoFilename);
                requestResult.setSuccess(true);
            }

        } else {
            request.getRequestDispatcher("/index.html").forward(request, response);
        }
    } catch (Throwable t) {
        logger.log(Level.ERROR, "processRequest", t);
        requestResult.setSuccess(false);
        requestResult.setErrorMessage(t.toString());
    } finally {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        String responseJSON = mapper.writeValueAsString(requestResult);
        out.print(responseJSON);
        out.flush();
        out.close();
    }

}

From source file:com.proofpoint.json.ObjectMapperProvider.java

@Override
public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_FIELDS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_SETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS);
    objectMapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
    objectMapper.disable(MapperFeature.INFER_PROPERTY_MUTATORS);
    objectMapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS);

    if (jsonSerializers != null || jsonDeserializers != null || keySerializers != null
            || keyDeserializers != null) {
        SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null, null, null));
        if (jsonSerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
                addSerializer(module, entry.getKey(), entry.getValue());
            }/*  w w w.  j ava 2s .c o  m*/
        }
        if (jsonDeserializers != null) {
            for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
                addDeserializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keySerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : keySerializers.entrySet()) {
                addKeySerializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keyDeserializers != null) {
            for (Entry<Class<?>, KeyDeserializer> entry : keyDeserializers.entrySet()) {
                module.addKeyDeserializer(entry.getKey(), entry.getValue());
            }
        }
        modules.add(module);
    }

    for (Module module : modules) {
        objectMapper.registerModule(module);
    }

    return objectMapper;
}

From source file:io.airlift.json.ObjectMapperProvider.java

@Override
public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_FIELDS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_SETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS);
    objectMapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
    objectMapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);

    if (jsonSerializers != null || jsonDeserializers != null || keySerializers != null
            || keyDeserializers != null) {
        SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null));
        if (jsonSerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
                addSerializer(module, entry.getKey(), entry.getValue());
            }/*w w w.  ja v  a 2 s  .c o m*/
        }
        if (jsonDeserializers != null) {
            for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
                addDeserializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keySerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : keySerializers.entrySet()) {
                addKeySerializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keyDeserializers != null) {
            for (Entry<Class<?>, KeyDeserializer> entry : keyDeserializers.entrySet()) {
                module.addKeyDeserializer(entry.getKey(), entry.getValue());
            }
        }
        modules.add(module);
    }

    for (Module module : modules) {
        objectMapper.registerModule(module);
    }

    return objectMapper;
}

From source file:com.aerofs.baseline.Service.java

public final void runWithConfiguration(T configuration) throws Exception {
    // initialize the validation subsystem
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
            .buildValidatorFactory();/* ww  w  . j ava  2  s .c om*/
    Validator validator = validatorFactory.getValidator();

    // validate the configuration
    Configuration.validateConfiguration(validator, configuration);

    // at this point we have a valid configuration
    // we can start logging to the correct location,
    // initialize common services, and start up
    // the jersey applications

    // reset the logging subsystem with the configured levels
    Logging.setupLogging(configuration.getLogging());

    // display the server banner if it exists
    displayBanner();

    // add a shutdown hook to release all resources cleanly
    Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

    // setup some default metrics for the JVM
    MetricRegistries.getRegistry().register(Constants.JVM_BUFFERS,
            new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    MetricRegistries.getRegistry().register(Constants.JVM_GC, new GarbageCollectorMetricSet());
    MetricRegistries.getRegistry().register(Constants.JVM_MEMORY, new MemoryUsageGaugeSet());
    MetricRegistries.getRegistry().register(Constants.JVM_THREADS, new ThreadStatesGaugeSet());

    // create the root service locator
    ServiceLocator rootLocator = ServiceLocatorFactory.getInstance().create("root");
    rootLocatorReference.set(rootLocator);

    // grab a reference to our system-wide class loader (we'll use this for the jersey service locators)
    ClassLoader classLoader = rootLocator.getClass().getClassLoader();

    // create the lifecycle manager
    LifecycleManager lifecycleManager = new LifecycleManager(rootLocator);
    lifecycleManagerReference.set(lifecycleManager);

    // after this point any services
    // added to the LifecycleManager will be
    // shut down cleanly

    // create and setup the system-wide Jackson object mapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    // create a few singleton objects
    Authenticators authenticators = new Authenticators();
    RegisteredCommands registeredCommands = new RegisteredCommands();
    RegisteredHealthChecks registeredHealthChecks = new RegisteredHealthChecks();

    // create the root environment
    Environment environment = new Environment(rootLocator, lifecycleManager, validator, mapper, authenticators,
            registeredCommands, registeredHealthChecks);

    // start configuring injectable objects
    // we'll be adding all instances and implementation classes to the root service locator
    // this makes them visible to the jersey applications

    environment.addBinder(new ConfigurationBinder<>(configuration, configuration.getClass()));
    environment.addBinder(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(name).to(String.class).named(Constants.SERVICE_NAME_INJECTION_KEY);
            bind(validator).to(Validator.class);
            bind(mapper).to(ObjectMapper.class);
            bind(environment).to(Environment.class);
            bind(lifecycleManager.getScheduledExecutorService()).to(ScheduledExecutorService.class);
            bind(lifecycleManager.getTimer()).to(Timer.class); // FIXME (AG): use our own timer interface
            bind(authenticators).to(Authenticators.class);
            bind(registeredCommands).to(RegisteredCommands.class);
            bind(registeredHealthChecks).to(RegisteredHealthChecks.class);
        }
    });

    // register some basic commands
    environment.registerCommand("gc", GarbageCollectionCommand.class);
    environment.registerCommand("metrics", MetricsCommand.class);
    environment.addAdminProvider(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(GarbageCollectionCommand.class).to(GarbageCollectionCommand.class).in(Singleton.class);
            bind(MetricsCommand.class).to(MetricsCommand.class).in(Singleton.class);
        }
    });

    // add exception mappers that only apply to the admin environment
    environment.addAdminProvider(InvalidCommandExceptionMapper.class);

    // add the resources we expose via the admin api
    environment.addAdminResource(CommandsResource.class);
    environment.addAdminResource(HealthCheckResource.class);

    // create the two environments (admin and service)
    String adminName = name + "-" + Constants.ADMIN_IDENTIFIER;
    initializeJerseyApplication(adminName, classLoader, validator, mapper, environment.getAdminResourceConfig(),
            configuration.getAdmin());

    String serviceName = name + "-" + Constants.SERVICE_IDENTIFIER;
    initializeJerseyApplication(serviceName, classLoader, validator, mapper,
            environment.getServiceResourceConfig(), configuration.getService());

    // punt to subclasses for further configuration
    init(configuration, environment);

    // after this point we can't add any more jersey providers
    // resources, etc. and we're ready to expose our server to the world

    // list the objects that are registered with the root service locator
    listInjected(rootLocator);

    // initialize the admin http server
    if (configuration.getAdmin().isEnabled()) {
        ApplicationHandler adminHandler = new ApplicationHandler(environment.getAdminResourceConfig(), null,
                rootLocator);
        listInjected(adminHandler.getServiceLocator());
        HttpServer adminHttpServer = new HttpServer(Constants.ADMIN_IDENTIFIER, configuration.getAdmin(),
                lifecycleManager.getTimer(), adminHandler);
        lifecycleManager.add(adminHttpServer);
    }

    // initialize the service http server
    if (configuration.getService().isEnabled()) {
        ApplicationHandler serviceHandler = new ApplicationHandler(environment.getServiceResourceConfig(), null,
                rootLocator);
        listInjected(serviceHandler.getServiceLocator());
        HttpServer serviceHttpServer = new HttpServer(Constants.SERVICE_IDENTIFIER, configuration.getService(),
                lifecycleManager.getTimer(), serviceHandler);
        lifecycleManager.add(serviceHttpServer);
    }

    // finally, start up all managed services (which includes the two servers above)
    lifecycleManager.start();
}

From source file:org.springframework.boot.actuate.context.properties.ConfigurationPropertiesReportEndpoint.java

/**
 * Configure Jackson's {@link ObjectMapper} to be used to serialize the
 * {@link ConfigurationProperties} objects into a {@link Map} structure.
 * @param mapper the object mapper//  w w w  .  java2s.  co  m
 */
protected void configureObjectMapper(ObjectMapper mapper) {
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(MapperFeature.USE_STD_BEAN_NAMING, true);
    mapper.setSerializationInclusion(Include.NON_NULL);
    applyConfigurationPropertiesFilter(mapper);
    applySerializationModifier(mapper);
}

From source file:com.corundumstudio.socketio.parser.JacksonJsonSupport.java

protected void init(ObjectMapper objectMapper) {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Event.class, eventDeserializer);
    module.addDeserializer(JsonObject.class, jsonObjectDeserializer);
    module.addDeserializer(AckArgs.class, ackArgsDeserializer);
    objectMapper.registerModule(module);

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);

    //        TODO If jsonObjectDeserializer will be not enough
    //        TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL);
    //        typer.init(JsonTypeInfo.Id.CLASS, null);
    //        typer.inclusion(JsonTypeInfo.As.PROPERTY);
    //        typer.typeProperty(configuration.getJsonTypeFieldName());
    //        objectMapper.setDefaultTyping(typer);
}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Create a Jira project.//ww w  .j a va  2  s.c  o m
 * 
 * Return the id of the created project.
 * 
 * Return null if the project is already existing in Jira.
 * 
 * @param project
 *            the project to create
 */
public String createProject(Project project) throws JiraServiceException {

    JsonNode content = null;

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        content = mapper.valueToTree(project);
        Logger.debug("project: " + mapper.writeValueAsString(project));
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/createProject: error when processing the project to a Json node", e);
    }

    JsonNode response = this.callPost(CREATE_PROJECT_ACTION, content);

    CreateProjectResponse createProjectResponse = null;
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        createProjectResponse = objectMapper.treeToValue(response, CreateProjectResponse.class);
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/createProject: error when processing the response to CreateProjectResponse.class",
                e);
    }

    if (createProjectResponse.success) {
        return createProjectResponse.projectRefId;
    } else {
        if (createProjectResponse.alreadyExists) {
            return null;
        } else {
            throw new JiraServiceException(
                    "JiraService/createProject: the response is a 200 with an unknown error.");
        }
    }

}

From source file:com.sothawo.taboo2.Taboo2ServiceTests.java

private byte[] convertObjectToJsonBytes(Object o) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(o);
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException {

    try (CloseableHttpResponse httpResponse = httpClient.execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }// w  w w . ja  v a2s .c o  m
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(responseContent, clazz);
    }
}