mitm.common.sms.transport.clickatell.ClickatellServerSimulator.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.sms.transport.clickatell.ClickatellServerSimulator.java

Source

/*
 * Copyright (c) 2009-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.sms.transport.clickatell;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * Class that simulates a Clickatell server so we can do stress tests
 * 
 * @author Martijn Brinkers
 *
 */
public class ClickatellServerSimulator {
    private static class ClickatellHandler implements HttpHandler {
        private AtomicLong requestCount = new AtomicLong();

        private Map<String, String> parseQuery(String query) {
            String[] params = query.split("&");

            Map<String, String> map = new HashMap<String, String>();

            for (String param : params) {
                String[] nameValue = param.split("=");

                if (nameValue == null || nameValue.length == 0) {
                    continue;
                }

                String name = nameValue[0];
                String value = nameValue.length > 1 ? nameValue[1] : "";

                name = StringUtils.trim(name);

                if (StringUtils.isEmpty(name)) {
                    continue;
                }

                try {
                    name = URLDecoder.decode(name, "US-ASCII");
                    value = URLDecoder.decode(StringUtils.defaultString(StringUtils.trim(value)), "US-ASCII");
                } catch (UnsupportedEncodingException e) {
                    // should never happen
                    throw new IllegalStateException(e);
                }

                map.put(name, value);
            }
            return map;
        }

        private void sendResponse(HttpExchange exchange, String body, int statusCode) throws IOException {
            exchange.sendResponseHeaders(statusCode, body.length());

            OutputStream response = exchange.getResponseBody();

            try {
                response.write(body.getBytes());
            } finally {
                IOUtils.closeQuietly(response);
            }
        }

        private void handleSendMsg(HttpExchange exchange) throws IOException {
            InputStream request = exchange.getRequestBody();

            String requestBody = IOUtils.toString(request, "US-ASCII");

            Map<String, String> parameters = parseQuery(requestBody);

            System.out.println("[sendmsg, " + requestCount.longValue() + "]: " + parameters);

            requestCount.incrementAndGet();

            String responseBody = "ID:" + requestCount;

            sendResponse(exchange, responseBody, 200);
        }

        private void handleGetBalance(HttpExchange exchange) throws IOException {
            InputStream request = exchange.getRequestBody();

            String requestBody = IOUtils.toString(request, "US-ASCII");

            Map<String, String> parameters = parseQuery(requestBody);

            System.out.println("[getbalance]: " + parameters);

            String responseBody = "CREDIT:" + (100000 - requestCount.longValue());

            sendResponse(exchange, responseBody, 200);
        }

        private void unknownRequest(HttpExchange exchange) throws IOException {
            InputStream request = exchange.getRequestBody();

            List<?> requestBody = IOUtils.readLines(request);

            System.out.println(requestBody);

            String responseBody = "Unknown request";

            sendResponse(exchange, responseBody, 450);
        }

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            URI requestURI = exchange.getRequestURI();

            System.out.println("Request URI: " + requestURI + ", Remote address: " + exchange.getRemoteAddress());

            String path = requestURI.getPath();

            if ("/http/sendmsg".equalsIgnoreCase(path)) {
                handleSendMsg(exchange);
            } else if ("/http/getbalance".equalsIgnoreCase(path)) {
                handleGetBalance(exchange);
            } else {
                unknownRequest(exchange);
            }
        }
    }

    public static void startServer() throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 10);

        server.createContext("/http", new ClickatellHandler());
        server.setExecutor(null);
        server.start();
    }

    public static void main(String[] args) {
        try {
            startServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}