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

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

Introduction

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

Prototype

public final void addMixInAnnotations(Class<?> target, Class<?> mixinSource) 

Source Link

Document

Method to use for adding mix-in annotations to use for augmenting specified class or interface.

Usage

From source file:org.osiam.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<>();
        givenFields.add("schemas");
        Collections.addAll(givenFields, fieldsToReturn);
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }/*from   w w w  . j  a v a  2s.c  o  m*/
    return mapper.writer();
}

From source file:org.osiam.resource_server.resources.helper.AttributesRemovalHelper.java

private ObjectWriter getObjectWriter(ObjectMapper mapper, String[] fieldsToReturn) {

    if (fieldsToReturn.length != 0) {
        mapper.addMixInAnnotations(Object.class, PropertyFilterMixIn.class);

        HashSet<String> givenFields = new HashSet<String>();
        givenFields.add("schemas");
        for (String field : fieldsToReturn) {
            givenFields.add(field);// w w w .  j a v a  2 s .  co  m
        }
        String[] finalFieldsToReturn = givenFields.toArray(new String[givenFields.size()]);

        FilterProvider filters = new SimpleFilterProvider().addFilter("filter properties by name",
                SimpleBeanPropertyFilter.filterOutAllExcept(finalFieldsToReturn));
        return mapper.writer(filters);
    }
    return mapper.writer();
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static String generateJavascript(ModelBean model, OutputConfig outputConfig) {

    if (!outputConfig.isDebug()) {
        JsCacheKey key = new JsCacheKey(model, outputConfig);

        SoftReference<String> jsReference = jsCache.get(key);
        if (jsReference != null && jsReference.get() != null) {
            return jsReference.get();
        }// w w  w. jav a 2 s  . c  om
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);

    if (!outputConfig.isSurroundApiWithQuotes()) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesExtJs5Mixin.class);
        } else {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesMixin.class);
        }
        mapper.addMixInAnnotations(ApiObject.class, ApiObjectMixin.class);
    } else {
        if (outputConfig.getOutputFormat() != OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithApiQuotesMixin.class);
        }
    }

    Map<String, Object> modelObject = new LinkedHashMap<String, Object>();
    modelObject.put("extend", model.getExtend());

    if (!model.getAssociations().isEmpty()) {
        Set<String> usesClasses = new HashSet<String>();
        for (AbstractAssociation association : model.getAssociations()) {
            usesClasses.add(association.getModel());
        }

        usesClasses.remove(model.getName());

        if (!usesClasses.isEmpty()) {
            modelObject.put("uses", usesClasses);
        }
    }

    Map<String, Object> configObject = new LinkedHashMap<String, Object>();
    ProxyObject proxyObject = new ProxyObject(model, outputConfig);

    Map<String, ModelFieldBean> fields = model.getFields();
    Set<String> requires = new HashSet<String>();

    if (!model.getValidations().isEmpty() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires = addValidatorsToField(fields, model.getValidations());
    }

    if (proxyObject.hasContent() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires.add("Ext.data.proxy.Direct");
    }

    if (StringUtils.hasText(model.getIdentifier()) && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        if ("sequential".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Sequential");
        } else if ("uuid".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Uuid");
        } else if ("negative".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Negative");
        }
    }

    if (requires != null && !requires.isEmpty()) {
        configObject.put("requires", requires);
    }

    if (StringUtils.hasText(model.getIdentifier())) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
            configObject.put("identifier", model.getIdentifier());
        } else {
            configObject.put("idgen", model.getIdentifier());
        }
    }

    if (StringUtils.hasText(model.getIdProperty()) && !model.getIdProperty().equals("id")) {
        configObject.put("idProperty", model.getIdProperty());
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
            && StringUtils.hasText(model.getVersionProperty())) {
        configObject.put("versionProperty", model.getVersionProperty());
    }

    if (StringUtils.hasText(model.getClientIdProperty())) {

        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.EXTJS4) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        } else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2
                && !"clientId".equals(model.getClientIdProperty())) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        }
    }

    for (ModelFieldBean field : fields.values()) {
        field.updateTypes(outputConfig);
    }

    List<Object> fieldConfigObjects = new ArrayList<Object>();
    for (ModelFieldBean field : fields.values()) {
        if (field.hasOnlyName(outputConfig)) {
            fieldConfigObjects.add(field.getName());
        } else {
            fieldConfigObjects.add(field);
        }
    }
    configObject.put("fields", fieldConfigObjects);

    if (!model.getAssociations().isEmpty()) {
        configObject.put("associations", model.getAssociations());
    }

    if (!model.getValidations().isEmpty() && !(outputConfig.getOutputFormat() == OutputFormat.EXTJS5)) {
        configObject.put("validations", model.getValidations());
    }

    if (proxyObject.hasContent()) {
        configObject.put("proxy", proxyObject);
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4
            || outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        modelObject.putAll(configObject);
    } else {
        modelObject.put("config", configObject);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Ext.define(\"").append(model.getName()).append("\",");
    if (outputConfig.isDebug()) {
        sb.append("\n");
    }

    String configObjectString;
    Class<?> jsonView = JsonViews.ExtJS4.class;
    if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
        jsonView = JsonViews.Touch2.class;
    } else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        jsonView = JsonViews.ExtJS5.class;
    }

    try {
        if (outputConfig.isDebug()) {
            configObjectString = mapper.writerWithDefaultPrettyPrinter().withView(jsonView)
                    .writeValueAsString(modelObject);
        } else {
            configObjectString = mapper.writerWithView(jsonView).writeValueAsString(modelObject);
        }

    } catch (JsonGenerationException e) {
        throw new RuntimeException(e);
    } catch (JsonMappingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    sb.append(configObjectString);
    sb.append(");");

    String result = sb.toString();

    if (outputConfig.isUseSingleQuotes()) {
        result = result.replace('"', '\'');
    }

    if (!outputConfig.isDebug()) {
        jsCache.put(new JsCacheKey(model, outputConfig), new SoftReference<String>(result));
    }
    return result;
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

/**
 * Write as an RO Bundle JSON-LD manifest
 * /*  w w  w  .j  a  va 2 s  .  c om*/
 * @return The path of the written manifest (e.g. ".ro/manifest.json")
 * @throws IOException
 */
public Path writeAsJsonLD() throws IOException {
    Path jsonld = bundle.getFileSystem().getPath(RO, MANIFEST_JSON);
    createDirectories(jsonld.getParent());
    // Files.createFile(jsonld);
    if (!getManifest().contains(jsonld))
        getManifest().add(0, jsonld);
    ObjectMapper om = new ObjectMapper();
    om.addMixInAnnotations(Path.class, PathMixin.class);
    om.addMixInAnnotations(FileTime.class, FileTimeMixin.class);
    om.enable(INDENT_OUTPUT);
    om.disable(WRITE_EMPTY_JSON_ARRAYS);
    om.disable(FAIL_ON_EMPTY_BEANS);
    om.disable(WRITE_NULL_MAP_VALUES);

    om.setSerializationInclusion(Include.NON_NULL);
    try (Writer w = newBufferedWriter(jsonld, Charset.forName("UTF-8"), WRITE, TRUNCATE_EXISTING, CREATE)) {
        om.writeValue(w, this);
    }
    return jsonld;
}

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.groupon.odo.controllers.PathController.java

@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
public @ResponseBody String testPath(@RequestParam String url, @RequestParam String profileIdentifier,
        @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(
            Constants.OVERRIDE_TYPE_REQUEST, ClientService.getInstance().findClient("-1", profileId),
            ProfileService.getInstance().findProfile(profileId), url, requestType, true);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

From source file:com.groupon.odo.controllers.PathController.java

@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
public @ResponseBody String getPathsForProfile(Model model, String profileIdentifier,
        @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter,
        @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID)
        throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID,
            typeFilter);/*from w  w  w.j a v  a2  s .  co m*/

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = { "possibleEndpoints", "enabledEndpoints" };
    FilterProvider filters = new SimpleFilterProvider().addFilter(
            "Filter properties from the PathController GET",
            SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}

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:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Configures the provided Jackson ObjectMapper for create/update/delete
 * operations of Ckan objects. For reading and generic
 * serialization/deserialization of Ckan objects, use
 * {@link #configureObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) }
 * instead. For future compatibility you will need a different object mapper
 * for each class you want to post to ckan. <b> DO NOT </b> call
 * {@link #configureObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) }
 * on the mapper prior to this call.//from   w w w  . j  a  va  2 s  .  com
 *
 * @param om
 *            a Jackson object mapper
 * @param clazz
 *            the class of the objects you wish to create/update/delete.
 * @since 0.4.1
 */
public static void configureObjectMapperForPosting(ObjectMapper om, Class clazz) {
    configureObjectMapper(om);
    om.setSerializationInclusion(Include.NON_NULL);
    om.addMixInAnnotations(CkanResource.class, CkanResourceForPosting.class);
    om.addMixInAnnotations(CkanDataset.class, CkanDatasetForPosting.class);
    om.addMixInAnnotations(CkanOrganization.class, CkanGroupOrgForPosting.class);
    if (CkanDatasetBase.class.isAssignableFrom(clazz)) {
        // little fix for
        // https://github.com/opendatatrentino/jackan/issues/19
        om.addMixInAnnotations(CkanGroup.class, GroupForDatasetPosting.class);
    } else {
        om.addMixInAnnotations(CkanGroup.class, CkanGroupOrgForPosting.class);
    }

    om.addMixInAnnotations(CkanUser.class, CkanUserForPosting.class);
    om.addMixInAnnotations(CkanTag.class, CkanTagForPosting.class);
}