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

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

Introduction

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

Prototype

public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) 

Source Link

Document

Method for changing AnnotationIntrospector used by this mapper instance for both serialization and deserialization

Usage

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**//from  w w w .ja v  a2s .c  o m
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:gov.bnl.channelfinder.MyJAXBContextResolver.java

private static ObjectMapper createDefaultMapper() {
    final ObjectMapper result = new ObjectMapper();
    result.enable(SerializationFeature.INDENT_OUTPUT);
    result.setAnnotationIntrospector(createJaxbJacksonAnnotationIntrospector());
    return result;
}

From source file:com.pressassociation.pr.filter.json.jackson.JacksonFilters.java

/**
 * Filter all serialised output via the given ObjectMapper with the given matcher.
 */// w  w  w  .ja  va  2 s .  c o m
public static ObjectMapper filterAllOutput(ObjectMapper mapper, Matcher matcher) {
    mapper.setFilters(new SimpleFilterProvider().addFilter(FILTER_ID, new JacksonMatcherFilter(matcher)));
    mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
        @Override
        public Object findFilterId(Annotated a) {
            return FILTER_ID;
        }
    });
    return mapper;
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtilTest.java

static Deployment loadEsxiDeployment() throws IOException {
    // Set up some mock component data
    // Get some deployment data
    URL uri = HostnameUtilTest.class.getClassLoader().getResource("esxi_deployment.json");
    assertNotNull("Failed to load esxi_deployment.json", uri);
    String json = IOUtils.toString(uri, Charsets.UTF_8);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(json, Deployment.class);
}

From source file:br.com.dgimenes.jsonlibscomparison.JSONLibsTest.java

private static String encodeWithJACKSONJAXB(SalesJAXB salesAnnotatedWithJAXB)
        throws JsonGenerationException, JsonMappingException, IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("deprecation")
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // enables "JAXB annotations only" mode
    mapper.setAnnotationIntrospector(introspector);
    mapper.writeValue(outputStream, salesAnnotatedWithJAXB);
    return outputStream.toString();
}

From source file:com.infinities.skyport.util.JsonUtil.java

public static ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper.setAnnotationIntrospector(jaxbAnnotationPair);
    // make deserializer use JAXB annotations (only)
    objectMapper = objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper = objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
    return objectMapper;
}

From source file:com.kingen.web.CommonController.java

public static String serializeOnlyGivenFields(Object o, Collection<String> fields)
        throws JsonProcessingException {
    if ((fields == null) || fields.isEmpty())
        fields = new HashSet<String>();

    Set<String> properties = new HashSet<String>(fields);

    SimpleBeanPropertyFilter filter = new SimpleBeanPropertyFilter.FilterExceptFilter(properties);
    SimpleFilterProvider fProvider = new SimpleFilterProvider();
    fProvider.addFilter(FILTER_NAME, filter);

    ObjectMapper mapper = new ObjectMapper();
    mapper.setAnnotationIntrospector(new AnnotationIntrospector());

    String json = mapper.writer(fProvider).writeValueAsString(o);
    return json;//from ww  w.ja  va 2 s.  c om
}

From source file:org.apache.nifi.toolkit.cli.impl.client.nifi.impl.JerseyNiFiClient.java

private static JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
    JacksonJaxbJsonProvider jacksonJaxbJsonProvider = new JacksonJaxbJsonProvider();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDefaultPropertyInclusion(/*from  w  w  w .  ja  va 2s  .co  m*/
            JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
    mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(mapper.getTypeFactory()));
    // Ignore unknown properties so that deployed client remain compatible with future versions of NiFi that add new fields
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    jacksonJaxbJsonProvider.setMapper(mapper);
    return jacksonJaxbJsonProvider;
}

From source file:org.apache.nifi.registry.client.impl.JerseyNiFiRegistryClient.java

private static JacksonJaxbJsonProvider jacksonJaxbJsonProvider() {
    JacksonJaxbJsonProvider jacksonJaxbJsonProvider = new JacksonJaxbJsonProvider();

    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyInclusion(//  www . j a v  a  2 s  . co  m
            JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
    mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(mapper.getTypeFactory()));
    // Ignore unknown properties so that deployed client remain compatible with future versions of NiFi Registry that add new fields
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(BucketItem[].class, new BucketItemDeserializer());
    mapper.registerModule(module);

    jacksonJaxbJsonProvider.setMapper(mapper);
    return jacksonJaxbJsonProvider;
}

From source file:info.archinnov.achilles.json.DefaultJacksonMapper.java

private static ObjectMapper defaultJacksonMapper() {
    ObjectMapper defaultMapper = new ObjectMapper();
    defaultMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    defaultMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    defaultMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
    defaultMapper.setAnnotationIntrospector(AnnotationIntrospector.pair(primary, secondary));
    return defaultMapper;
}