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

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

Introduction

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

Prototype

public ObjectMapper() 

Source Link

Document

Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider , and BeanSerializerFactory as its SerializerFactory .

Usage

From source file:de.raion.xmppbot.hipchat.HipChatAPIConfig.java

public static void main(String[] args) throws Exception {
    HipChatAPIConfig config = new HipChatAPIConfig();
    config.setAuthenticationToken("b2b1ca1091f0709e60253b76db73ea");
    config.setBaseURL(new URL("https://api.hipchat.com"));
    config.setApiVersion("v1");
    config.setRoomCreatePath("rooms/create");
    config.setRoomDeletePath("rooms/delete");
    config.setRoomHistoryPath("rooms/history");

    ObjectWriter writer = new ObjectMapper().writerWithDefaultPrettyPrinter();

    String filename = config.getClass().getSimpleName().toLowerCase() + ".json";

    writer.writeValue(new File(filename), config);
}

From source file:org.nuxeo.connect.tools.report.viewer.Viewer.java

public static void main(String[] varargs) throws IOException, ParseException {

    class Arguments {
        Options options = new Options()
                .addOption(Option.builder("i").longOpt("input").hasArg().argName("file")
                        .desc("report input file").build())
                .addOption(Option.builder("o").longOpt("output").hasArg().argName("file")
                        .desc("thread dump output file").build());
        final CommandLine commandline = new DefaultParser().parse(options, varargs);

        Arguments() throws ParseException {

        }/*from w w  w  .  j  ava 2  s .  co m*/

        InputStream input() throws IOException {
            if (!commandline.hasOption('i')) {
                return System.in;
            }
            return Files.newInputStream(Paths.get(commandline.getOptionValue('i')));
        }

        PrintStream output() throws IOException {
            if (!commandline.hasOption('o')) {
                return System.out;
            }
            return new PrintStream(commandline.getOptionValue('o'));
        }

    }

    Arguments arguments = new Arguments();
    final JsonFactory jsonFactory = new JsonFactory();
    PrintStream output = arguments.output();
    JsonParser parser = jsonFactory.createParser(arguments.input());
    ObjectMapper mapper = new ObjectMapper();
    while (!parser.isClosed() && parser.nextToken() != JsonToken.NOT_AVAILABLE) {
        String hostid = parser.nextFieldName();
        output.println(hostid);
        {
            parser.nextToken();
            while (parser.nextToken() == JsonToken.FIELD_NAME) {
                if ("mx-thread-dump".equals(parser.getCurrentName())) {
                    parser.nextToken(); // start mx-thread-dump report
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            parser.nextToken();
                            printThreadDump(mapper.readTree(parser), output);
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadDeadlocked(mapper.readerFor(Long.class).readValue(parser), output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else if ("mx-thread-monitor-deadlocked".equals(parser.getCurrentName())) {
                    parser.nextToken();
                    while (parser.nextToken() == JsonToken.FIELD_NAME) {
                        if ("value".equals(parser.getCurrentName())) {
                            if (parser.nextToken() == JsonToken.START_ARRAY) {
                                printThreadMonitorDeadlocked(mapper.readerFor(Long.class).readValues(parser),
                                        output);
                            }
                        } else {
                            parser.nextToken();
                            parser.skipChildren();
                        }
                    }
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    }

}

From source file:org.n52.iceland.statistics.api.utils.KibanaExporter.java

public static void main(String args[]) throws Exception {
    if (args.length != 2) {
        System.out.printf("Usage: java KibanaExporter.jar %s %s\n", "localhost:9300", "my-cluster-name");
        System.exit(0);//  ww w  .  j a  va  2 s. c  o m
    }
    if (!args[0].contains(":")) {
        throw new IllegalArgumentException(
                String.format("%s not a valid format. Expected <hostname>:<port>.", args[0]));
    }

    // set ES address
    String split[] = args[0].split(":");
    InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(split[0]),
            Integer.parseInt(split[1], 10));

    // set cluster name
    Builder tcSettings = Settings.settingsBuilder();
    tcSettings.put("cluster.name", args[1]);
    System.out.println("Connection to " + args[1]);

    client = TransportClient.builder().settings(tcSettings).build();
    client.addTransportAddress(address);

    // search index pattern for needle
    searchIndexPattern();

    KibanaConfigHolderDto holder = new KibanaConfigHolderDto();
    System.out.println("Reading .kibana index");

    SearchResponse resp = client.prepareSearch(".kibana").setSize(1000).get();
    Arrays.asList(resp.getHits().getHits()).stream().map(KibanaExporter::parseSearchHit).forEach(holder::add);
    System.out.println("Reading finished");

    ObjectMapper mapper = new ObjectMapper();
    // we love pretty things
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    File f = new File("kibana_config.json");

    try (FileOutputStream out = new FileOutputStream(f, false)) {
        mapper.writeValue(out, holder);
    }

    System.out.println("File outputted to: " + f.getAbsolutePath());

    client.close();

}

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));
    }//from   w ww . j av  a  2 s.co m
}

From source file:SheetStructure.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here.

    try {/*from ww  w  .ja v a2 s .  c  om*/

        System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale...");
        //First Create a new sheet.
        String sheetName = "Betty's Bake Sale";
        //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON.
        //Their structure directly relates to the JSON that gets passed through the API.
        //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out.
        Sheet newSheet = new Sheet();
        newSheet.setName(sheetName);
        newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null),
                new Column("Baker", "CONTACT_LIST", null, null, null),
                new Column("Price Per Item", "TEXT_NUMBER", null, null, null),
                new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST",
                        null, null, Arrays.asList("Started", "Finished", "Delivered"))));
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Sheet>>() {
                });
        newSheet = newSheetResult.getResult();
        System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId());

        //Now add a column:
        String columnName = "Delivery Date";
        System.out.println("Adding column " + columnName + " to " + sheetName);
        Column newColumn = new Column(columnName, "DATE", 5);

        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newColumn);
        Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });

        System.out.println(
                "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName());

        //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it.
        System.out.println("Fetching " + newSheet.getName() + " sheet columns...");
        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        List<Column> allColumns = mapper.readValue(connection.getInputStream(),
                new TypeReference<List<Column>>() {
                });
        System.out.println("Fetched.");

        //Now we will be adding rows
        System.out.println("Inserting rows into " + newSheet.getName());
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"),
                new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"),
                new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-04"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"),
                new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Started"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"),
                new Cell(allColumns.get(1).id, "sandrassmart@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE),
                new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"),
                new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-05"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"),
                new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"),
                new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created.

        RowWrapper rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move a row to the top.
        System.out.println("Moving row 6 to the top.");
        RowWrapper moveToTop = new RowWrapper();
        moveToTop.setToTop(true);

        connection = (HttpURLConnection) new URL(
                ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection();
        connection.setRequestMethod("PUT");
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), moveToTop);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
        });

        System.out.println("Row 6 moved to top.");

        //Insert empty rows for spacing
        rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, ""))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move Delivered rows to be children of the last spacer row.
        System.out.println("Moving delivered rows to Delivered section...");
        Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(),
                newRowsResult.result.get(4).getId() };
        RowWrapper parentRowLocation = new RowWrapper();
        parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId());

        for (Long deliveredId : deliveredRowIds) {
            System.out.println("Moving " + deliveredId + " to Delivered.");
            connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection();
            connection.setRequestMethod("PUT");
            connection.addRequestProperty("Authorization", "Bearer " + accessToken);
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            mapper.writeValue(connection.getOutputStream(), parentRowLocation);
            mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
            });
            System.out.println("Row id " + deliveredId + " moved.");
        }

        System.out.println("Appending additional rows to items in progress...");

        List<Row> siblingRows = new ArrayList<Row>();
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"),
                new Cell(allColumns.get(1).id, "tomlively@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Finished"))));
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId());
        rowWrapper.setRows(siblingRows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName());

        System.out.println("Moving Status column to index 1...");
        Column statusColumn = allColumns.get(4);
        Column moveColumn = new Column();
        moveColumn.setIndex(1);
        moveColumn.setTitle(statusColumn.title);
        moveColumn.setSheetId(newSheet.getId());
        moveColumn.setType(statusColumn.getType());
        connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        mapper.writeValue(connection.getOutputStream(), moveColumn);
        Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });
        System.out.println("Moved column " + movedColumnResult.getResult().getId());
        System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale.");
    } catch (IOException e) {
        InputStream is = ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:org.jetbrains.webdemo.executors.JavaExecutor.java

public static void main(String[] args) {
    PrintStream defaultOutputStream = System.out;
    try {//ww  w . j a  va2 s.  com
        System.setOut(new PrintStream(standardOutputStream));
        System.setErr(new PrintStream(errorOutputStream));

        RunOutput outputObj = new RunOutput();
        String className;
        if (args.length > 0) {
            className = args[0];
            try {
                Method mainMethod = Class.forName(className).getMethod("main", String[].class);
                mainMethod.invoke(null, (Object) Arrays.copyOfRange(args, 1, args.length));
            } catch (InvocationTargetException e) {
                outputObj.exception = e.getCause();
            } catch (NoSuchMethodException e) {
                System.err.println("No main method found in project.");
            } catch (ClassNotFoundException e) {
                System.err.println("No main method found in project.");
            }
        } else {
            System.err.println("No main method found in project.");
        }

        System.out.flush();
        System.err.flush();
        System.setOut(defaultOutputStream);
        outputObj.text = outputStream.toString().replaceAll("</errStream><errStream>", "")
                .replaceAll("</outStream><outStream>", "");
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Throwable.class, new ThrowableSerializer());
        objectMapper.registerModule(module);
        System.out.print(objectMapper.writeValueAsString(outputObj));
    } catch (Throwable e) {
        System.setOut(defaultOutputStream);
        System.out.println("{\"text\":\"<errStream>" + e.getClass().getName() + ": " + e.getMessage());
        System.out.print("</errStream>\"}");
    }

}

From source file:de.oth.keycloak.TestRun.java

public static void main(String[] args) {
    try {/*from   w w  w.  j  a v  a  2 s  . c  o m*/
        String server = "http://localhost:8888/auth";
        String realm = "master";
        String user = "keycloak_admin";
        String pwd = "k6ycloakAdmin";
        String clientStr = "admin-cli";
        String secret = null;
        String initFileStr = "conf/test_init1.json";
        File initFile = new File(initFileStr);
        if (!initFile.isFile()) {
            URL url = TestRun.class.getClassLoader().getResource(initFileStr);
            if (url != null) {
                initFile = new File(url.getFile());
                if (!initFile.isFile()) {
                    log.error("init file does not exist: " + initFile);
                    System.exit(1);
                }
            } else {
                log.error("init file does not exist: " + initFile);
                System.exit(1);
            }
        }
        Keycloak keycloak = (secret == null) ? Keycloak.getInstance(server, realm, user, pwd, clientStr)
                : Keycloak.getInstance(server, realm, user, pwd, clientStr, secret);

        ObjectMapper mapper = new ObjectMapper();
        RealmsConfig realmsConfig = mapper.readValue(initFile, RealmsConfig.class);

        if (realmsConfig != null) {
            List<RealmConfig> realmList = realmsConfig.getRealms();
            if (realmList == null || realmList.isEmpty()) {
                log.error("no realms config found 1");
                return;
            }
            for (RealmConfig realmConf : realmList) {
                InitKeycloakServer.addRealm(keycloak, realmConf);
            }
        } else
            log.error("no realms config found 2");
    } catch (Exception e) {
        log.error(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:internal.diff.common.launcher.SampleApplication.java

public static void main(String[] args) throws IOException {

    ApplicationContext context = new AnnotationConfigApplicationContext(SampleApplication.class);

    AmazonS3DirectoryMetadataService s3DirectoryMetadataService = context
            .getBean(AmazonS3DirectoryMetadataService.class);
    FileSystemDirectoryMetadataService fileSystemDirectoryMetadataService = context
            .getBean(FileSystemDirectoryMetadataService.class);
    DirectoryMetadataDifferenceService differenceService = context
            .getBean(DirectoryMetadataDifferenceService.class);

    log.info("The metadata of S3 bucket '{}' with prefix '{}' is going to be read.", S3_BUCKET, S3_PREFIX);
    DirectoryMetadata directory2 = s3DirectoryMetadataService.getMetadata(S3_BUCKET, S3_PREFIX);

    log.info("The metadata of file system directory '{}' is going to be read.", FILE_SYSTEM_DIRECTORY);
    DirectoryMetadata directory1 = fileSystemDirectoryMetadataService.getMetadata(FILE_SYSTEM_DIRECTORY);

    log.info("The differences between the metadata is being calculated.");
    DirectoryMetadataDifference difference = differenceService.getDifference(directory1, directory2);

    new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(System.out, difference);
}

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

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**/*from ww  w .j a  v a 2s. 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:la.alsocan.jsonshapeshifter.Main.java

/**
 * An entry point, to test the library in action.
 * @param args Console args (nothing expected here so far)
 * @throws IOException if the payload cannot be read
 *//*from   w  w  w. j  a  v  a2 s. co m*/
public static void main(String[] args) throws IOException {

    Schema source;
    Schema target;
    try {
        source = Schema.buildSchema(SOURCE_SCHEMA);
        target = Schema.buildSchema(TARGET_SCHEMA);
    } catch (IOException ex) {
        System.err.println("Oups: " + ex);
        return;
    }

    // build the transformation incrementally
    Transformation t = new Transformation(source, target);
    Iterator<SchemaNode> it = t.toBind();
    t.bind(it.next(), new ArrayNodeBinding(source.at("/rootSourceArray")));
    t.bind(it.next(), new ArrayNodeBinding(source.at("/rootSourceArray/{i}")));
    t.bind(it.next(), new StringConstantBinding("Constant value"));
    t.bind(it.next(), new StringNodeBinding(source.at("/rootSourceString")));
    t.bind(it.next(), new ArrayNodeBinding(source.at("/rootSourceArray/{i}/{i}/someSourceArray")));
    t.bind(it.next(), new StringNodeBinding(source.at("/rootSourceArray/{i}/{i}/someSourceArray/{i}")));

    // produce something
    JsonNode payload = new ObjectMapper().readTree(new File(SOURCE_PAYLOAD));
    JsonNode result = t.apply(payload);
    ObjectMapper om = new ObjectMapper();
    try {
        System.out.println("Original payload:");
        System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(payload));
        System.out.println("\nResulting payload:");
        System.out.println(om.writerWithDefaultPrettyPrinter().writeValueAsString(result));
    } catch (JsonProcessingException ex) {
        System.err.println("Oups: " + ex);
    }
}