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:com.olacabs.fabric.compute.builder.Linker.java

public ComputationPipeline build(ComputationSpec spec) {
    final NotificationBus notificationBus = new NotificationBus(spec.getProperties());
    final ProcessingContext processingContext = new ProcessingContext();
    processingContext.setTopologyName(spec.getName());
    ComputationPipeline pipeline = ComputationPipeline.builder();
    pipeline.notificationBus(notificationBus);
    pipeline.computationName(spec.getName());
    Map<String, PipelineStreamSource> sources = Maps.newHashMap();
    Map<String, PipelineStage> stages = Maps.newHashMap();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    spec.getSources().forEach(sourceMetadata -> {
        final ComponentMetadata meta = sourceMetadata.getMeta();
        PipelineSource source = null;// w  w w  .j av a2 s  . co m
        final String errorMessage = String.format("Source object not loaded properly [%s:%s:%s]",
                meta.getNamespace(), meta.getName(), meta.getVersion());
        try {
            PipelineSource sourceCopy = loader.loadSource(meta);
            if (sourceCopy != null) {
                source = sourceCopy.getClass().getDeclaredConstructor().newInstance();
            }
        } catch (Exception e) {
            throw new RuntimeException(errorMessage, e);
        }
        Preconditions.checkNotNull(source, errorMessage);
        LOGGER.info("Loaded source: {}:{}:{}", meta.getNamespace(), meta.getName(), meta.getVersion());
        PipelineStreamSource sourceStage = PipelineStreamSource.builder().instanceId(sourceMetadata.getId())
                .properties(sourceMetadata.getProperties()).notificationBus(notificationBus)
                .sourceMetadata(sourceMetadata.getMeta()).source(source).processingContext(processingContext)
                .objectMapper(objectMapper).registry(metricRegistry).build();
        pipeline.addSource(sourceStage);
        sources.put(sourceMetadata.getId(), sourceStage);
    });
    spec.getProcessors().forEach(processorMetadata -> {
        final ComponentMetadata meta = processorMetadata.getMeta();
        ProcessorBase processorBase = null;
        final String errorMessage = String.format("Processor object not loaded properly [%s:%s:%s]",
                meta.getNamespace(), meta.getName(), meta.getVersion());
        try {
            ProcessorBase processorBaseCopy = loader.loadProcessor(meta);
            if (processorBaseCopy != null) {
                processorBase = processorBaseCopy.getClass().getDeclaredConstructor().newInstance();
            }
        } catch (Exception e) {
            throw new RuntimeException(errorMessage, e);
        }
        Preconditions.checkNotNull(processorBase, errorMessage);
        LOGGER.info("Loaded processor: {}:{}:{}", meta.getNamespace(), meta.getName(), meta.getVersion());

        PipelineStage stage = PipelineStage.builder().instanceId(processorMetadata.getId())
                .properties(processorMetadata.getProperties()).notificationBus(notificationBus)
                .processorMetadata(processorMetadata.getMeta()).processor(processorBase)
                .context(processingContext).build();
        pipeline.addPipelineStage(stage);
        stages.put(processorMetadata.getId(), stage);
    });
    spec.getConnections().forEach(connection -> {
        switch (connection.getFromType()) {
        case SOURCE:
            pipeline.connect(sources.get(connection.getFrom()), stages.get(connection.getTo()));
            break;

        case PROCESSOR:
            pipeline.connect(stages.get(connection.getFrom()), stages.get(connection.getTo()));
            break;
        default:
            break;

        }
    });
    return pipeline;
}

From source file:net.sf.gazpachoquest.questionnaires.resource.ResourceProducer.java

@Produces
@GazpachoResource/*from  w  w  w.  j a v  a 2  s . c om*/
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}

From source file:keywhiz.cli.CliModule.java

@Provides
public ObjectMapper generalMapper() {
    /**/*from   ww w.  j  a  v  a  2  s .  c  o m*/
     * Customizes ObjectMapper for common settings.
     *
     * @param objectMapper to be customized
     * @return customized input factory
     */
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModules(new JavaTimeModule());
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL//w  w  w  .  j av  a 2s .com
    String taxget = svcURL + "/1.0/tax/cancel";
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);         //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:io.qdb.server.controller.JsonService.java

private ObjectMapper createMapper(boolean prettyPrint, boolean datesAsTimestamps, boolean borg) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, datesAsTimestamps);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(Date.class, dateDeserializer);
    module.addDeserializer(Integer.class, integerJsonDeserializer);
    module.addDeserializer(Integer.TYPE, integerJsonDeserializer);
    module.addDeserializer(Long.class, longJsonDeserializer);
    module.addDeserializer(Long.TYPE, longJsonDeserializer);
    if (!borg) {//  w w w  .  j  av a2s . c o m
        module.addSerializer(Integer.TYPE, integerSerializer);
        module.addSerializer(Integer.class, integerSerializer);
        module.addSerializer(Long.TYPE, longSerializer);
        module.addSerializer(Long.class, longSerializer);
    }
    if (!datesAsTimestamps)
        module.addSerializer(Date.class, new ISO8601DateSerializer());
    mapper.registerModule(module);

    return mapper;
}

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL/*from   w ww . j a  v a  2s  .c  o  m*/
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:biz.dfch.j.clickatell.ClickatellClient.java

public MessageResponse sendMessage(String recipient, String message, int maxCredits, int maxParts)
        throws IOException, HttpResponseException {
    class ClickatellMessage {
        public ArrayList<String> to = new ArrayList<String>();
        public String text;
        public String maxCredits;
        public String maxMessageParts;
    }/* w  w  w  .  j  av a 2s  .  c  o  m*/
    try {
        ClickatellMessage clickatellMessage = new ClickatellMessage();
        clickatellMessage.to.add(recipient);
        clickatellMessage.text = message;
        clickatellMessage.maxCredits = (0 == maxCredits) ? null : Integer.toString(maxCredits);
        clickatellMessage.maxMessageParts = (0 == maxParts) ? null : Integer.toString(maxParts);

        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        String request = om.writeValueAsString(clickatellMessage);
        String response = Request.Post(uriMessage.toString()).setHeader(headerApiVersion)
                .setHeader(headerContentType).setHeader(headerAccept).setHeader("Authorization", bearerToken)
                .bodyString(request, ContentType.APPLICATION_JSON).execute().returnContent().asString();
        MessageResponse messageResponse = om.readValue(response, MessageResponse.class);
        return messageResponse;
    } catch (HttpResponseException ex) {
        int statusCode = ex.getStatusCode();
        switch (statusCode) {
        case 410:
            LOG.error(String.format("Sending message to '%s' FAILED with HTTP %d. No coverage of recipient.",
                    recipient, statusCode));
            break;
        default:
            break;
        }
        throw ex;
    }
}

From source file:info.archinnov.achilles.persistence.PersistenceManagerFactoryTest.java

@Test
public void should_serialize_to_json() throws Exception {
    //Given/*from w  w w .  j  av a2s.  com*/
    pmf.configContext = configContext;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    when(configContext.getMapperFor(CompleteBean.class)).thenReturn(mapper);
    CompleteBean entity = CompleteBeanTestBuilder.builder().id(10L).name("name").buid();

    //When
    final String serialized = pmf.serializeToJSON(entity);

    //Then
    assertThat(serialized)
            .isEqualTo("{\"id\":10,\"name\":\"name\",\"friends\":[],\"followers\":[],\"preferences\":{}}");
}

From source file:info.archinnov.achilles.persistence.PersistenceManagerFactoryTest.java

@Test
public void should_deserialize_from_json() throws Exception {
    //Given//from www .ja  v a  2 s .com
    pmf.configContext = configContext;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    when(configContext.getMapperFor(CompleteBean.class)).thenReturn(mapper);

    //When
    final CompleteBean actual = pmf.deserializeFromJSON(CompleteBean.class, "{\"id\":10,\"name\":\"name\"}");

    //Then
    assertThat(actual.getId()).isEqualTo(10L);
    assertThat(actual.getName()).isEqualTo("name");
    assertThat(actual.getFriends()).isNull();
    assertThat(actual.getFollowers()).isNull();
    assertThat(actual.getPreferences()).isNull();
}

From source file:info.pancancer.arch3.beans.Job.java

public String toJSON() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    try {/* w  w w.j  av a  2  s .c o m*/
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}