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:net.koddistortion.swagger.SwaggerApiClient.java

public static void main(String[] args) throws IOException {
    SwaggerApiClient c = new SwaggerApiClient();
    c.setBaseUrl("http://petstore.swagger.wordnik.com/api/api-docs");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ResourceListing listing = c.getResourceListing();
    ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
    for (Resource resource : listing.getApis()) {
        ApiDeclaration declaration = c.getApiDeclaration(resource);
        System.out.println(writer.writeValueAsString(declaration));
    }/*ww  w  .  ja  v a  2s .  c  om*/
}

From source file:com.skcraft.launcher.builder.PackageBuilder.java

/**
 * Build a package given the arguments./*from  ww w .  j  a v  a  2s  . c  om*/
 *
 * @param args arguments
 * @throws IOException thrown on I/O error
 */
public static void main(String[] args) throws IOException {
    BuilderOptions options = parseArgs(args);

    // Initialize
    SimpleLogFormatter.configureGlobalLogger();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);

    Manifest manifest = new Manifest();
    manifest.setMinimumVersion(Manifest.MIN_PROTOCOL_VERSION);
    PackageBuilder builder = new PackageBuilder(mapper, manifest);
    builder.setPrettyPrint(options.isPrettyPrinting());

    // From config
    builder.readConfig(options.getConfigPath());
    builder.readVersionManifest(options.getVersionManifestPath());

    // From options
    manifest.updateName(options.getName());
    manifest.updateTitle(options.getTitle());
    manifest.updateGameVersion(options.getGameVersion());
    manifest.setVersion(options.getVersion());
    manifest.setLibrariesLocation(options.getLibrariesLocation());
    manifest.setObjectsLocation(options.getObjectsLocation());

    builder.scan(options.getFilesDir());
    builder.addFiles(options.getFilesDir(), options.getObjectsDir());
    builder.writeManifest(options.getManifestPath());

    log.info("Wrote manifest to " + options.getManifestPath().getAbsolutePath());
    log.info("Done.");
}

From source file:squash.tools.FakeBookingCreator.java

public static void main(String[] args) throws IOException {
    int numberOfDays = 21;
    int numberOfCourts = 5;
    int maxCourtSpan = 5;
    int numberOfSlots = 16;
    int maxSlotSpan = 3;
    int minSurnameLength = 2;
    int maxSurnameLength = 20;
    int minBookingsPerDay = 0;
    int maxBookingsPerDay = 8;
    LocalDate startDate = LocalDate.of(2016, 7, 5);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    List<Booking> bookings = new ArrayList<>();
    for (LocalDate date = startDate; date.isBefore(startDate.plusDays(numberOfDays)); date = date.plusDays(1)) {
        int numBookings = ThreadLocalRandom.current().nextInt(minBookingsPerDay, maxBookingsPerDay + 1);
        List<Booking> daysBookings = new ArrayList<>();
        for (int bookingIndex = 0; bookingIndex < numBookings; bookingIndex++) {
            String player1 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));
            String player2 = RandomStringUtils.randomAlphabetic(1) + "." + RandomStringUtils.randomAlphabetic(
                    ThreadLocalRandom.current().nextInt(minSurnameLength, maxSurnameLength + 1));

            Set<ImmutablePair<Integer, Integer>> bookedCourts = new HashSet<>();
            daysBookings.forEach((booking) -> {
                addBookingToSet(booking, bookedCourts);
            });//from  www. j ava  2  s. c o m

            Booking booking;
            Set<ImmutablePair<Integer, Integer>> courtsToBook = new HashSet<>();
            do {
                // Loop until we create a booking of free courts
                int court = ThreadLocalRandom.current().nextInt(1, numberOfCourts + 1);
                int courtSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxCourtSpan + 1, numberOfCourts - court + 2));
                int slot = ThreadLocalRandom.current().nextInt(1, numberOfSlots + 1);
                int slotSpan = ThreadLocalRandom.current().nextInt(1,
                        Math.min(maxSlotSpan + 1, numberOfSlots - slot + 2));
                booking = new Booking(court, courtSpan, slot, slotSpan, player1 + "/" + player2);
                booking.setDate(date.format(formatter));
                courtsToBook.clear();
                addBookingToSet(booking, courtsToBook);
            } while (Boolean.valueOf(Sets.intersection(courtsToBook, bookedCourts).size() > 0));

            daysBookings.add(booking);
        }
        bookings.addAll(daysBookings);
    }

    // Encode bookings as JSON
    // Create the node factory that gives us nodes.
    JsonNodeFactory factory = new JsonNodeFactory(false);
    // Create a json factory to write the treenode as json.
    JsonFactory jsonFactory = new JsonFactory();
    ObjectNode rootNode = factory.objectNode();

    ArrayNode bookingsNode = rootNode.putArray("bookings");
    for (int i = 0; i < bookings.size(); i++) {
        Booking booking = bookings.get(i);
        ObjectNode bookingNode = factory.objectNode();
        bookingNode.put("court", booking.getCourt());
        bookingNode.put("courtSpan", booking.getCourtSpan());
        bookingNode.put("slot", booking.getSlot());
        bookingNode.put("slotSpan", booking.getSlotSpan());
        bookingNode.put("name", booking.getName());
        bookingNode.put("date", booking.getDate());
        bookingsNode.add(bookingNode);
    }
    // Add empty booking rules array - just so restore works
    rootNode.putArray("bookingRules");
    rootNode.put("clearBeforeRestore", true);

    try (JsonGenerator generator = jsonFactory.createGenerator(new File("FakeBookings.json"),
            JsonEncoding.UTF8)) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_EMPTY);
        mapper.setSerializationInclusion(Include.NON_NULL);
        mapper.writeTree(generator, rootNode);
    }
}

From source file:com.tmo.swagger.main.GenrateSwaggerJson.java

public static void main(String[] args)
        throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows {

    PropertyReader pr = new PropertyReader();

    Properties prop = pr.readPropertiesFile(args[0]);
    //Properties prop =pr.readClassPathPropertyFile("common.properties");
    String swaggerFile = prop.getProperty("swagger.json");
    String sw = "";
    if (swaggerFile != null && swaggerFile.length() > 0) {
        Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile));
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        sw = mapper.writeValueAsString(swagger);
    } else {/*from w ww .j  ava  2  s  .c  om*/
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        Swagger swagger = populateProperties(prop);
        sw = mapper.writeValueAsString(swagger);
    }
    try {
        File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json");
        //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(sw);
        logger.info("Swagger Genration Done!");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**/* w  ww .j a v a2s . com*/
     * 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:fi.helsinki.opintoni.web.WebTestUtils.java

public static byte[] toJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.registerModule(new JavaTimeModule());
    return mapper.writeValueAsBytes(object);
}

From source file:it.reply.orchestrator.util.TestUtil.java

/**
 * Convert Object To a Json byte array.// ww w.ja  va 2s .co  m
 * 
 * @return byte[]
 */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(object);
}

From source file:com.elearning.rest1.config.TestUtils.java

public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(object);
}

From source file:org.openremote.server.util.JsonUtil.java

public static ObjectMapper configure(ObjectMapper objectMapper) {
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
            .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
            .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE);

    // Debugging/* w w  w  . j  av  a  2  s .  c om*/
    // objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    return objectMapper;
}

From source file:com.codemacro.jcm.util.JsonUtil.java

public static String toString(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    String json = "";
    try {//w ww.  j ava  2 s . c o  m
        json = mapper.writeValueAsString(obj);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}