Commits

Kenneth Endfinger committed 8dcf615

Add Original JSON API Code

  • Participants
  • Parent commits d338c62

Comments (0)

Files changed (13)

+/dist/
+/compiled/
+/.gradle/
+/build
+/lib
+<project name="JSONApi" default="jar">
+
+    <property name="name.KenBot" value="KenBot.jar"/>
+    <property name="download.KenBot" value="http://cdn.bitbucket.org/KenBot/kenbot/downloads/KenBot.jar"/>
+    <property name="download.Gson" value="http://repo.maven.apache.org/maven2/com/google/code/gson/gson/2.2.4/gson-2.2.4.jar"/>
+
+    <target name="download-libs">
+	<mkdir dir="lib"/>
+        <get usetimestamp="true" src="${download.KenBot}" dest="lib/${name.KenBot}"/>
+	<get usetimestamp="true" src="${download.Gson}" dest="lib/gson.jar"/>
+    </target>
+
+    <target name="build" depends="download-libs">
+        <delete dir="compiled"/>
+        <mkdir dir="compiled"/>
+        <javac srcdir="src" destdir="compiled" includeantruntime="false" target="1.7" source="1.7">
+            <compilerarg line="-XDignore.symbol.file"/>
+	    <classpath>
+                <pathelement path="lib/${name.KenBot}"/>
+		<pathelement path="lib/gson.jar"/>
+            </classpath>
+        </javac>
+        <unzip src="lib/gson.jar" dest="compiled">
+            <patternset>
+	        <exclude name="META-INF/**"/>
+            </patternset>
+        </unzip>
+    </target>
+
+    <target name="jar" depends="build">
+        <delete dir="dist"/>
+        <mkdir dir="dist"/>
+        <jar destfile="dist/JSONApi.jar">
+            <fileset dir="compiled"/>
+            <manifest>
+                <attribute name="Module-class" value="kenbot.web.json.ModuleJSONApi"/>
+            </manifest>
+        </jar>
+    </target>
+    <target name="clean">
+        <delete dir="dist"/>
+	<delete dir="lib"/>
+        <delete dir="compiled"/>
+    </target>
+</project>

src/kenbot/web/json/Config.java

+package kenbot.web.json;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import kaendfinger.kenbot.core.KenBotConfig;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Map;
+
+public class Config implements HttpHandler {
+    @Override
+    public void handle(HttpExchange t) throws IOException {
+        Map<String, Object> params = (Map<String, Object>) t.getAttribute("parameters");
+        GsonBuilder builder = new GsonBuilder();
+        if (params.containsKey("pretty")) {
+            if (!params.get("pretty").equals("false")) {
+                builder.setPrettyPrinting();
+            }
+        }
+        Gson gson = builder.create();
+        BufferedWriter out = new BufferedWriter(new PrintWriter(t.getResponseBody()));
+        if (!params.containsKey("key")) {
+            out.write(gson.toJson("No Key Specified"));
+            out.flush();
+            out.close();
+            return;
+        }
+        String key = (String) params.get("key");
+        String value = KenBotConfig.get(key);
+        ConfigJson json = new ConfigJson(key, value);
+        String response = gson.toJson(json);
+        t.sendResponseHeaders(200, response.length());
+        t.getResponseBody().write(response.getBytes());
+        out.flush();
+        out.close();
+    }
+}

src/kenbot/web/json/ConfigJson.java

+package kenbot.web.json;
+
+public class ConfigJson {
+    private String key;
+    private String value;
+
+    public ConfigJson(String key, String value) {
+        this.key = key;
+        this.value = value;
+    }
+}

src/kenbot/web/json/MainAuth.java

+package kenbot.web.json;
+
+import com.sun.net.httpserver.BasicAuthenticator;
+
+public class MainAuth extends BasicAuthenticator {
+    public MainAuth(String realm) {
+        super(realm);
+    }
+
+    @Override
+    public boolean checkCredentials(String username, String password) {
+        return ModuleJSONApi.usernames.contains(username) && ModuleJSONApi.passwords.contains(password);
+    }
+}

src/kenbot/web/json/ModuleJSONApi.java

+package kenbot.web.json;
+
+import com.sun.net.httpserver.HttpContext;
+import com.sun.net.httpserver.HttpServer;
+import kaendfinger.kenbot.api.IModule;
+import kaendfinger.kenbot.api.events.ConfigurationEvent;
+import kaendfinger.kenbot.api.utils.StringUtils;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.Arrays;
+import java.util.List;
+
+public class ModuleJSONApi implements IModule {
+    private static HttpServer server;
+    private int port;
+    protected static List<String> usernames;
+    protected static List<String> passwords;
+
+    @Override
+    public void setup(ConfigurationEvent configurationEvent) {
+        configurationEvent.getConfiguration().header("Port to use for Configuration");
+        port = Integer.parseInt(configurationEvent.getConfiguration().get("port", "7000"));
+        usernames = Arrays.asList(StringUtils.getQuoted(configurationEvent.getConfiguration().get("usernames", "kaendfinger")));
+        passwords = Arrays.asList(StringUtils.getQuoted(configurationEvent.getConfiguration().get("passwords", "kaendfinger")));
+    }
+
+    @Override
+    public void load() {
+        try {
+            server = HttpServer.create(new InetSocketAddress(port), 0);
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        server.createContext("/", new Root());
+        HttpContext run = server.createContext("/run", new RunCommand());
+        run.getFilters().add(new ParameterFilter());
+        run.setAuthenticator(new MainAuth("BotAPI:RunCommand"));
+        server.createContext("/users", new Users()).getFilters().add(new ParameterFilter());
+        HttpContext send = server.createContext("/sendMessage", new SendMessage());
+        send.getFilters().add(new ParameterFilter());
+        send.setAuthenticator(new MainAuth("BotAPI:SendMessage"));
+        HttpContext config = server.createContext("/config", new Config());
+        config.getFilters().add(new ParameterFilter());
+        config.setAuthenticator(new MainAuth("BotAPI:Config"));
+        server.setExecutor(null);
+        System.out.println("Starting JSON Api server on port " + port);
+        server.start();
+    }
+
+    @Override
+    public void unload() {
+        server.stop(0);
+    }
+
+    @Override
+    public String[] classes() {
+        return new String[0];
+    }
+
+    @Override
+    public String name() {
+        return "JSONApi";
+    }
+}

src/kenbot/web/json/ParameterFilter.java

+package kenbot.web.json;
+
+import com.sun.net.httpserver.Filter;
+import com.sun.net.httpserver.HttpExchange;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ParameterFilter extends Filter {
+
+    @Override
+    public String description() {
+        return "Parses the requested URI for parameters";
+    }
+
+    @Override
+    public void doFilter(HttpExchange exchange, Chain chain)
+            throws IOException {
+        parseGetParameters(exchange);
+        parsePostParameters(exchange);
+        chain.doFilter(exchange);
+    }
+
+    private void parseGetParameters(HttpExchange exchange)
+            throws UnsupportedEncodingException {
+
+        Map<String, Object> parameters = new HashMap<String, Object>();
+        URI requestedUri = exchange.getRequestURI();
+        String query = requestedUri.getRawQuery();
+        parseQuery(query, parameters);
+        exchange.setAttribute("parameters", parameters);
+    }
+
+    private void parsePostParameters(HttpExchange exchange)
+            throws IOException {
+
+        if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
+            @SuppressWarnings("unchecked")
+            Map<String, Object> parameters =
+                    (Map<String, Object>)exchange.getAttribute("parameters");
+            InputStreamReader isr =
+                    new InputStreamReader(exchange.getRequestBody(),"utf-8");
+            BufferedReader br = new BufferedReader(isr);
+            String query = br.readLine();
+            parseQuery(query, parameters);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private void parseQuery(String query, Map<String, Object> parameters)
+            throws UnsupportedEncodingException {
+
+        if (query != null) {
+            String pairs[] = query.split("[&]");
+
+            for (String pair : pairs) {
+                String param[] = pair.split("[=]");
+
+                String key = null;
+                String value = null;
+                if (param.length > 0) {
+                    key = URLDecoder.decode(param[0],
+                            System.getProperty("file.encoding"));
+                }
+
+                if (param.length > 1) {
+                    value = URLDecoder.decode(param[1],
+                            System.getProperty("file.encoding"));
+                }
+
+                if (parameters.containsKey(key)) {
+                    Object obj = parameters.get(key);
+                    if(obj instanceof List<?>) {
+                        List<String> values = (List<String>)obj;
+                        values.add(value);
+                    } else if(obj instanceof String) {
+                        List<String> values = new ArrayList<String>();
+                        values.add((String)obj);
+                        values.add(value);
+                        parameters.put(key, values);
+                    }
+                } else {
+                    parameters.put(key, value);
+                }
+            }
+        }
+    }
+}

src/kenbot/web/json/Root.java

+package kenbot.web.json;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import kaendfinger.kenbot.api.utils.BotUtils;
+import kaendfinger.kenbot.core.KenBotConfig;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.*;
+
+public class Root implements HttpHandler {
+    @Override
+    public void handle(HttpExchange t) throws IOException {
+        Gson gson = new GsonBuilder().
+                setPrettyPrinting().
+                serializeNulls().
+                create();
+        String server = BotUtils.getBot().getServer();
+        String user = BotUtils.getBot().getNick();
+        String prefix = KenBotConfig.get("prefix");
+        String realName = BotUtils.getBot().getVersion();
+        Set<String> channelsNames = BotUtils.getBot().getChannelsNames();
+        List<String> channels = Arrays.asList(channelsNames.toArray(new String[channelsNames.size()]));
+        RootJson json = new RootJson(channels, server, user, prefix, realName);
+        byte[] response = gson.toJson(json).getBytes();
+        t.sendResponseHeaders(200, response.length);
+        OutputStream os = t.getResponseBody();
+        os.write(response);
+        os.close();
+    }
+}

src/kenbot/web/json/RootJson.java

+package kenbot.web.json;
+
+import java.util.Date;
+import java.util.List;
+
+public class RootJson {
+    private long timestamp;
+    private configuration configuration;
+    private List<String> channels;
+
+    public RootJson(List<String> channels, String server, String user, String prefix, String realName) {
+        this.configuration = new configuration(server, user, prefix, realName);
+        this.channels = channels;
+        this.timestamp = new Date().getTime();
+    }
+
+    class configuration {
+        private String server;
+        private String user;
+        private String prefix;
+        private String realName;
+
+        public configuration(String server, String user, String prefix, String realName) {
+            this.server = server;
+            this.user = user;
+            this.prefix = prefix;
+            this.realName = realName;
+        }
+    }
+}

src/kenbot/web/json/RunCommand.java

+package kenbot.web.json;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import kaendfinger.kenbot.api.utils.BotUtils;
+import kaendfinger.kenbot.core.KenBotConfig;
+import kaendfinger.kenbot.listeners.CommandListener;
+import org.pircbotx.hooks.events.MessageEvent;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class RunCommand implements HttpHandler {
+    @Override
+    public void handle(HttpExchange t) throws IOException {
+        Map<String, Object> params = (Map<String, Object>) t.getAttribute("parameters");
+        GsonBuilder builder = new GsonBuilder();
+        if (params.containsKey("pretty")) {
+            if (!params.get("pretty").equals("false")) {
+                builder.setPrettyPrinting();
+            }
+        }
+        Gson gson = builder.create();
+        OutputStream out = t.getResponseBody();
+        if (!params.containsKey("command") || !params.containsKey("channel")) {
+            byte[] response = gson.toJson("No Command/Channel Specified").getBytes();
+            t.sendResponseHeaders(200, response.length);
+            out.write(response);
+            out.close();
+            return;
+        }
+        String command = (String) params.get("command");
+        String channel = (String) params.get("channel");
+        String args = (String) params.get("args");
+        if (args==null) {
+            args = "";
+        } else {
+            args = " " + args;
+        }
+        boolean didRun = false;
+        if (CommandListener.commandExists(command) || BotUtils.getBot().getChannelsNames().contains(channel)) {
+            String prefix = KenBotConfig.get("prefix");
+            Method method = CommandListener.getCommandMethod(command);
+            try {
+                if (method.getParameterTypes().length>1) {
+                    method.invoke(null, new MessageEvent<>(BotUtils.getBot(), BotUtils.getBot().getChannel(channel), BotUtils.getBot().getUserBot(), prefix + command + args), args.substring(1));
+                } else {
+                    method.invoke(null, new MessageEvent<>(BotUtils.getBot(), BotUtils.getBot().getChannel(channel), BotUtils.getBot().getUserBot(), prefix + command + args));
+                }
+            } catch (IllegalAccessException | InvocationTargetException e) {
+                e.printStackTrace();
+            }
+            didRun = true;
+        }
+        byte[] response = gson.toJson(new Response(didRun)).getBytes();
+        t.sendResponseHeaders(200, response.length);
+        out.write(response);
+        out.flush();
+        out.close();
+    }
+
+    class Response {
+        private boolean didRun;
+
+        public Response(boolean didRun) {
+            this.didRun = didRun;
+        }
+    }
+}

src/kenbot/web/json/SendMessage.java

+package kenbot.web.json;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import kaendfinger.kenbot.api.utils.BotUtils;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Map;
+
+public class SendMessage implements HttpHandler {
+    @Override
+    public void handle(HttpExchange t) throws IOException {
+        Gson gson = new GsonBuilder().
+                setPrettyPrinting().
+                serializeNulls().
+                create();
+        Map<String, Object> params = (Map<String, Object>) t.getAttribute("parameters");
+        Object json;
+        if (!params.containsKey("target") || !params.containsKey("message")) {
+            json = "ERROR! Target or Message was not specified!";
+        } else {
+            boolean sent;
+            String target = (String) params.get("target");
+            String message = (String) params.get("message");
+            if (!BotUtils.getBot().isConnected()) {
+                sent = false;
+            } else {
+                BotUtils.getBot().sendMessage(target, message);
+                sent = true;
+            }
+            json = new SendMessageJson(sent);
+        }
+        byte[] response = gson.toJson(json).getBytes();
+        t.sendResponseHeaders(200, response.length);
+        OutputStream os = t.getResponseBody();
+        os.write(response);
+        os.close();
+    }
+}

src/kenbot/web/json/SendMessageJson.java

+package kenbot.web.json;
+
+public class SendMessageJson {
+    private boolean sent;
+
+    public SendMessageJson(boolean sent) {
+        this.sent = sent;
+    }
+}

src/kenbot/web/json/Users.java

+package kenbot.web.json;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import kaendfinger.kenbot.api.utils.BotUtils;
+import org.pircbotx.User;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.*;
+
+public class Users implements HttpHandler {
+
+    @Override
+    public void handle(HttpExchange t) throws IOException {
+        Gson gson = new GsonBuilder().setPrettyPrinting().create();
+        Map<String, Object> params = (Map<String, Object>) t.getAttribute("parameters");
+        OutputStream stream = t.getResponseBody();
+        Set<String> channels = BotUtils.getBot().getChannelsNames();
+        HashMap<String, List> users = new HashMap<>();
+        if (params.containsKey("channel")) {
+            String channel = (String) params.get("channel");
+            ArrayList<String> list = new ArrayList<>();
+            if (!BotUtils.getBot().getChannelsNames().contains(channel)) {
+                byte[] response = gson.toJson(new Error("error_not_in_channel")).getBytes();
+                t.sendResponseHeaders(200, response.length);
+                stream.write(response);
+                stream.flush();
+                stream.close();
+                return;
+            }
+            for (User user : BotUtils.getBot().getChannel(channel).getUsers()) {
+                list.add(user.getNick());
+            }
+            users.put(channel, list);
+            byte[] response = gson.toJson(users).getBytes();
+            t.sendResponseHeaders(200, response.length);
+            stream.write(response);
+            stream.close();
+            return;
+        }
+        for (String channel : channels) {
+            ArrayList<String> list = new ArrayList<>();
+            for (User user : BotUtils.getBot().getChannel(channel).getUsers()) {
+                list.add(user.getNick());
+            }
+            users.put(channel, list);
+        }
+        byte[] response = gson.toJson(users).getBytes();
+        t.sendResponseHeaders(200, response.length);
+        stream.write(response);
+        stream.close();
+    }
+
+    class Error {
+        private String error;
+
+        public Error(String error) {
+            this.error = error;
+        }
+    }
+}