Package io.bold

Source Code of io.bold.WebhookHandler

package io.bold;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.util.List;

/**
* Demo of a web server handling the webhook action from Bold.
*/
public class WebhookHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        System.out.println("Incoming request...");
        InputStream in = httpExchange.getRequestBody();
        try {
            ObjectMapper mapper = new ObjectMapper();
            InboundSms sms = mapper.readValue(in, InboundSms.class);
            System.out.println("Received a message:\n\t" + sms);
            httpExchange.sendResponseHeaders(200, 0);
            httpExchange.getResponseBody().close();
        } catch (Exception e) {
            e.printStackTrace();
            String response = "That's no good";
            httpExchange.sendResponseHeaders(403, response.length());
            httpExchange.getResponseBody().write(response.getBytes());
            httpExchange.getResponseBody().close();
        }
    }

    public static void main(String[] args) throws IOException {
        String addr = "0.0.0.0";
        int port = 9000;
        if (args.length > 0) {
            List<String> parts = Lists.newArrayList(Splitter.on(':').trimResults().split(args[0]));
            addr = parts.get(0);
            if (parts.size() > 1) {
                port = Integer.parseInt(parts.get(1));
            }
        }
        HttpServer server = HttpServer.create(new InetSocketAddress(addr, port), 2);
        server.createContext("/", new WebhookHandler());
        server.setExecutor(null);
        server.start();
    }

}
TOP

Related Classes of io.bold.WebhookHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.