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:wercker4j.request.RequestBuilder.java

/**
 * patch will call token API to update// w  w w  . ja  v a2  s.  c o m
 *
 * @param option option to call update token API
 * @return responseWrapper
 * @throws Wercker4jException fault statusCode and IO error
 */
public ResponseWrapper patch(UpdateTokenOption option) throws Wercker4jException {
    String url = UriTemplate.fromTemplate(endpoint + "/tokens{/tokenId}").set("tokenId", option.tokenId)
            .expand();
    HttpPatch httpPatch = new HttpPatch(url);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    try {
        httpPatch.setEntity(new StringEntity(mapper.writeValueAsString(option), "UTF-8"));
        return callPatchAPI(httpPatch);
    } catch (Exception e) {
        throw new Wercker4jException(e);
    }
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

private static void createPassJSONFile(final PKPass pass, final File tempPassDir,
        final ObjectMapper jsonObjectMapper) throws IOException, JsonGenerationException, JsonMappingException {
    File passJSONFile = new File(tempPassDir.getAbsolutePath() + File.separator + PASS_JSON_FILE_NAME);

    SimpleFilterProvider filters = new SimpleFilterProvider();

    // haven't found out, how to stack filters. Copying the validation one for now.
    filters.addFilter("validateFilter",
            SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors"));
    filters.addFilter("pkPassFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "foregroundColorAsObject", "backgroundColorAsObject", "labelColorAsObject"));
    filters.addFilter("barcodeFilter", SimpleBeanPropertyFilter.serializeAllExcept("valid", "validationErrors",
            "messageEncodingAsString"));
    filters.addFilter("charsetFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
    jsonObjectMapper.setSerializationInclusion(Include.NON_NULL);
    jsonObjectMapper.addMixInAnnotations(Object.class, ValidateFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKPass.class, PkPassFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(PKBarcode.class, BarcodeFilterMixIn.class);
    jsonObjectMapper.addMixInAnnotations(Charset.class, CharsetFilterMixIn.class);

    ObjectWriter objectWriter = jsonObjectMapper.writer(filters);
    objectWriter.writeValue(passJSONFile, pass);
}

From source file:com.esri.geoportal.commons.gpt.client.Client.java

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

    try (CloseableHttpResponse httpResponse = execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }//from w w  w  .java  2  s  .  co 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);
    }
}

From source file:com.netflix.conductor.client.http.ClientBase.java

protected ObjectMapper objectMapper() {
    final ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    om.setSerializationInclusion(Include.NON_NULL);
    om.setSerializationInclusion(Include.NON_EMPTY);
    return om;//w w  w  .ja va2s  .c om
}

From source file:com.esri.geoportal.commons.gpt.client.Client.java

/**
 * Publishes a document./* www  .jav  a  2s  .c o  m*/
 *
 * @param data data to publish
 * @param forceAdd <code>true</code> to force add.
 * @return response information
 * @throws IOException if reading response fails
 * @throws URISyntaxException if URL has invalid syntax
 */
public PublishResponse publish(PublishRequest data, boolean forceAdd) throws IOException, URISyntaxException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = mapper.writeValueAsString(data);
    StringEntity entity = new StringEntity(json);

    List<String> ids = !forceAdd ? queryIds(data.src_uri_s) : Collections.emptyList();
    HttpRequestBase request;
    switch (ids.size()) {
    case 0: {
        HttpPut put = new HttpPut(url.toURI().resolve(REST_ITEM_URL));
        put.setConfig(DEFAULT_REQUEST_CONFIG);
        put.setEntity(entity);
        put.setHeader("Content-Type", "application/json");
        request = put;
    }
        break;
    case 1: {
        HttpPut put = new HttpPut(url.toURI().resolve(REST_ITEM_URL + "/" + ids.get(0)));
        put.setConfig(DEFAULT_REQUEST_CONFIG);
        put.setEntity(entity);
        put.setHeader("Content-Type", "application/json");
        request = put;
    }
        break;
    default:
        throw new IOException(String.format("Error updating item: %s", data.src_uri_s));
    }

    try (CloseableHttpResponse httpResponse = execute(request);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));
        return mapper.readValue(responseContent, PublishResponse.class);
    }
}

From source file:org.springframework.data.rest.tests.RepositoryTestsConfig.java

@Bean
public ObjectMapper objectMapper() {

    RelProvider relProvider = new EvoInflectorRelProvider();
    ObjectMapper mapper = new ObjectMapper();

    mapper.registerModule(new Jackson2HalModule());
    mapper.registerModule(persistentEntityModule());
    mapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator(relProvider, null, null));
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_EMPTY);

    return mapper;
}

From source file:org.wso2.carbon.apimgt.impl.definitions.APIDefinitionUsingOASParser.java

/**
 * Creates a json string using the swagger object. 
 *
 * @param swaggerObj swagger object//from  ww w  .  j  a v a2  s .  c o m
 * @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);
    }
}

From source file:com.siemens.sw360.datahandler.couchdb.MapperFactory.java

/**
 * Creates an object mapper with the given personalization
 *
 * @return the personalized object mapper
 */// w w w. j a v  a 2  s  .  c om
@Override
public ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();

    // General settings
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // auto-detect all member fields
    mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // but only public getters
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE); // and none of "is-setters"

    // Do not include null
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // Classes mix-in
    for (Class type : classes) {
        mapper.addMixInAnnotations(type, DatabaseMixIn.class);
    }

    // Nested classes mix-in
    for (Class type : nestedClasses) {
        mapper.addMixInAnnotations(type, DatabaseNestedMixIn.class);
    }

    return mapper;
}

From source file:org.geoserver.notification.geonode.GeoNodeJsonEncoder.java

@Override
public byte[] encode(Notification notification) throws Exception {
    byte[] ret = null;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"));
    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    KombuMessage message = new KombuMessage();

    message.setId(new UID().toString());
    message.setType(notification.getType() != null ? notification.getType().name() : null);
    message.setAction(notification.getAction() != null ? notification.getAction().name() : null);
    message.setTimestamp(new Date());
    message.setUser(notification.getUser());
    message.setOriginator(InetAddress.getLocalHost().getHostAddress());
    message.setProperties(notification.getProperties());
    if (notification.getObject() instanceof NamespaceInfo) {
        NamespaceInfo obj = (NamespaceInfo) notification.getObject();
        KombuNamespaceInfo source = new KombuNamespaceInfo();
        source.setId(obj.getId());//from w  ww.j  a v  a 2  s .  c  o  m
        source.setType("NamespaceInfo");
        source.setName(obj.getName());
        source.setNamespaceURI(obj.getURI());
        message.setSource(source);
    }
    if (notification.getObject() instanceof WorkspaceInfo) {
        WorkspaceInfo obj = (WorkspaceInfo) notification.getObject();
        KombuWorkspaceInfo source = new KombuWorkspaceInfo();
        source.setId(obj.getId());
        source.setType("WorkspaceInfo");
        source.setName(obj.getName());
        source.setNamespaceURI("");
        message.setSource(source);
    }
    if (notification.getObject() instanceof LayerInfo) {
        LayerInfo obj = (LayerInfo) notification.getObject();
        KombuLayerInfo source = new KombuLayerInfo();
        source.setId(obj.getId());
        source.setType("LayerInfo");
        source.setName(obj.getName());
        source.setResourceType(obj.getType() != null ? obj.getType().name() : "");
        BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer("name");
        Collection<String> styleNames = CollectionUtils.collect(obj.getStyles(), transformer);
        source.setStyles(StringUtils.join(styleNames.toArray()));
        source.setDefaultStyle(obj.getDefaultStyle() != null ? obj.getDefaultStyle().getName() : "");
        ResourceInfo res = obj.getResource();
        source.setWorkspace(res.getStore() != null
                ? res.getStore().getWorkspace() != null ? res.getStore().getWorkspace().getName() : ""
                : "");
        if (res.getNativeBoundingBox() != null) {
            source.setBounds(new Bounds(res.getNativeBoundingBox()));
        }
        if (res.getLatLonBoundingBox() != null) {
            source.setGeographicBunds(new Bounds(res.getLatLonBoundingBox()));
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof LayerGroupInfo) {
        LayerGroupInfo obj = (LayerGroupInfo) notification.getObject();
        KombuLayerGroupInfo source = new KombuLayerGroupInfo();
        source.setId(obj.getId());
        source.setType("LayerGroupInfo");
        source.setName(obj.getName());
        source.setWorkspace(obj.getWorkspace() != null ? obj.getWorkspace().getName() : "");
        source.setMode(obj.getType().name());
        String rootStyle = obj.getRootLayerStyle() != null ? obj.getRootLayerStyle().getName() : "";
        source.setRootLayerStyle(rootStyle);
        source.setRootLayer(obj.getRootLayer() != null ? obj.getRootLayer().getPath() : "");
        for (PublishedInfo pl : obj.getLayers()) {
            KombuLayerSimpleInfo kl = new KombuLayerSimpleInfo();
            if (pl instanceof LayerInfo) {
                LayerInfo li = (LayerInfo) pl;
                kl.setName(li.getName());
                String lstyle = li.getDefaultStyle() != null ? li.getDefaultStyle().getName() : "";
                if (!lstyle.equals(rootStyle)) {
                    kl.setStyle(lstyle);
                }
                source.addLayer(kl);
            }
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof ResourceInfo) {
        ResourceInfo obj = (ResourceInfo) notification.getObject();
        KombuResourceInfo source = null;
        if (notification.getObject() instanceof FeatureTypeInfo) {
            source = new KombuFeatureTypeInfo();
            source.setType("FeatureTypeInfo");
        }
        if (notification.getObject() instanceof CoverageInfo) {
            source = new KombuCoverageInfo();
            source.setType("CoverageInfo");
        }
        if (notification.getObject() instanceof WMSLayerInfo) {
            source = new KombuWMSLayerInfo();
            source.setType("WMSLayerInfo");
        }
        if (source != null) {
            source.setId(obj.getId());
            source.setName(obj.getName());
            source.setWorkspace(obj.getStore() != null
                    ? obj.getStore().getWorkspace() != null ? obj.getStore().getWorkspace().getName() : ""
                    : "");
            source.setNativeName(obj.getNativeName());
            source.setStore(obj.getStore() != null ? obj.getStore().getName() : "");
            if (obj.getNativeBoundingBox() != null) {
                source.setGeographicBunds(new Bounds(obj.getNativeBoundingBox()));
            }
            if (obj.boundingBox() != null) {
                source.setBounds(new Bounds(obj.boundingBox()));
            }
        }
        message.setSource(source);
    }
    if (notification.getObject() instanceof StoreInfo) {
        StoreInfo obj = (StoreInfo) notification.getObject();
        KombuStoreInfo source = new KombuStoreInfo();
        source.setId(obj.getId());
        source.setType("StoreInfo");
        source.setName(obj.getName());
        source.setWorkspace(obj.getWorkspace() != null ? obj.getWorkspace().getName() : "");
        message.setSource(source);
    }
    ret = mapper.writeValueAsBytes(message);
    return ret;

}