Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package DataBase;
- import java.sql.*;
- public class DBManager {
- private Connection connection;
- public Connection getConnection(){
- return connection;
- }
- public UserSet userSet;
- public MapSet mapSet;
- public LayerSet layerSet;
- public DBManager(String dbName){
- connection = connect(dbName);
- userSet = new UserSet(connection);
- mapSet = new MapSet(connection);
- layerSet = new LayerSet(connection);
- }
- /**
- * Connect to a database
- *
- * @param dbName the database file name without extension
- */
- private static Connection connect(String dbName) {
- Connection conn = null;
- try {
- // db parameters
- String url = "jdbc:sqlite:./db/"+dbName+".db";
- // create a connection to the database
- conn = DriverManager.getConnection(url);
- System.out.println("Connection to SQLite has been established.");
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return conn;
- }
- /**
- * Connect to a sample database
- *
- * @param dbName the database file name
- */
- private static void createDatabase(String dbName) {
- String url = "jdbc:sqlite:./db/" + dbName + ".db";
- try (Connection conn = DriverManager.getConnection(url)) {
- if (conn != null) {
- DatabaseMetaData meta = conn.getMetaData();
- System.out.println("The driver name is " + meta.getDriverName());
- System.out.println("A new database has been created.");
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * Create a new table in the test database
- */
- private static void createTables(Connection connection) {
- // SQL statement for creating a new table
- String sqlUser = "CREATE TABLE IF NOT EXISTS Users"
- + " (\nid integer PRIMARY KEY,\n"
- + " login text NOT NULL UNIQUE,\n"
- + " token text NOT NULL UNIQUE,\n"
- + " password text NOT NULL\n"
- + ");";
- String sqlMap = "CREATE TABLE IF NOT EXISTS Maps"
- + " (\nid integer PRIMARY KEY,\n"
- + " name text NOT NULL,\n"
- + " x double NOT NULL,\n"
- + " y double NOT NULL,\n"
- + " zoom integer NOT NULL,\n"
- + " user_id integer NOT NULL,\n"
- + " FOREIGN KEY(user_id) REFERENCES Users(id)\n"
- + " ON DELETE CASCADE);";
- String sqlLayers = "CREATE TABLE IF NOT EXISTS Layers"
- + " (\nid integer PRIMARY KEY,"
- + " name text NOT NULL,\n"
- + " link text NOT NULL,\n"
- + " map_id integer NOT NULL,\n"
- + " FOREIGN KEY(map_id) REFERENCES Maps(id)\n"
- + " ON DELETE CASCADE);";
- try (Statement stmt = connection.createStatement()) {
- // create a new table
- stmt.execute(sqlUser);
- stmt.execute(sqlMap);
- stmt.execute(sqlLayers);
- System.out.println("Tables have been added!");
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * Initializes db: creates file and tables
- *
- * @param dbName
- */
- public static void initDataBase(String dbName){
- createDatabase(dbName);
- Connection connection = connect(dbName);
- createTables(connection);
- }
- }
- _______________________________________________________________________
- package Core;
- import DataBase.DBManager;
- import Types.MsgType;
- import com.sun.org.apache.xml.internal.utils.WrongParserException;
- import java.util.*;
- public class Interpreter {
- List<String> commands = Arrays.asList("create", "update", "delete", "show", "login");
- List<String> objects = Arrays.asList("map", "layer");
- DBManager manager;
- private int userId;
- public Interpreter(DBManager manager){
- this.manager = manager;
- }
- /**
- * Decides what to do with incoming data
- * @param input
- * @return
- */
- public String start(String input){
- String[] data = input.split("-",2);
- System.out.println("Parts: "+Integer.toString(data.length));
- if (data.length == 1) // Login or registration ot token
- {
- if (input.equals("token"))
- return manager.userSet.generateToken();
- if (authenticate(input))
- return "Success";
- }
- else
- {
- System.out.println("Processing commands");
- if (data.length == 2) {
- String token = data[0];
- if (authenticated(token))
- return interpret(data[1]);
- }
- }
- return "Authentication failed";
- }
- /**
- * Checks if user's token is authenticated
- * @param token
- * @return
- */
- private boolean authenticated(String token){
- userId = manager.userSet.findByToken(token);
- return userId != -1;
- }
- /**
- * Authorizes user
- * @param code
- * @return
- */
- private boolean authenticate(String code){
- String[] cmds = code.trim().split(" ");
- if (cmds.length == 4 && cmds[0].equals("login"))
- return manager.userSet.login(cmds[1], cmds[2], cmds[3]);
- if (cmds.length == 3 && cmds[0].equals("register"))
- return manager.userSet.add(cmds[1], cmds[2]);
- return false;
- }
- /**
- * Runs all the commands in code
- * @param code
- * @return
- */
- public String interpret(String code){
- String[] lines = code.split("\n");
- StringBuilder sb = new StringBuilder();
- for (String line: lines) {
- Map<String, String> args = new HashMap<String, String>();
- String[] words = line.split(" ", 3);
- String result;
- try {
- // Basic syntax check
- if (words.length != 3 ||
- !objects.contains(words[0]) ||
- !commands.contains(words[1]))
- throw new WrongParserException(line);
- String[] argList = words[2].split(" ");
- if (argList.length % 2 == 1)
- throw new WrongParserException(line);
- // Set arguments
- for (int i = 0; i < argList.length - 1; i += 2) {
- args.put(argList[i], argList[i + 1]);
- }
- result = runCommand(words[0], words[1], args);
- }
- catch (Exception e) {
- result = msg(MsgType.syntax, e.getMessage());
- }
- System.out.print(result);
- sb.append(result);
- sb.append("<br>");
- }
- return sb.toString();
- }
- /**
- * Returns message by type with args
- * @param type
- * @param arg
- * @return
- */
- private String msg(MsgType type, String arg){
- String message = "none";
- switch (type){
- case syntax:
- message = String.format("Wrong command syntax: %s", arg);
- break;
- case args:
- message = String.format("Wrong arguments count: %s", arg);
- break;
- }
- return message;
- }
- /**
- * Interprete one line of code
- * @param object
- * @param command
- * @param args
- * @return String result
- */
- private String runCommand(String object, String command, Map<String, String> args){
- try {
- switch (object) {
- case "map":
- if (command.equals("create")) {
- if (manager.mapSet.add(args.get("-map"),
- Double.parseDouble(args.get("-x")),
- Double.parseDouble(args.get("-y")),
- Integer.parseInt(args.get("-zoom")),
- userId))
- return String.format("Map %s has been created", args.get("-map"));
- return "Failed to create map";
- }
- MyMap map = manager.mapSet.find(args.get("-map"));
- if (map == null)
- return String.format("Map %s does not exist", args.get("-map"));
- if (command.equals("show"))
- return new MapGenerator().generateMap(
- manager.mapSet.getLayers(map.getId()), map);
- if (command.equals("update"))
- if (manager.mapSet.update(map.getId(), args))
- return String.format("Map %s has been updated", args.get("-map"));
- if (command.equals("delete"))
- if (manager.mapSet.delete(map.getId()))
- return String.format("Map %s has been deleted", args.get("-map"));
- break;
- case "layer":
- if (command.equals("create")) {
- if (manager.layerSet.add(args.get("-layer"), args.get("-link"),
- manager.mapSet.find(args.get("-map")).getId()))
- return String.format("Layer %s has been added", args.get("-layer"));
- return "Failed to create layer";
- }
- Layer layer = manager.layerSet.find(args.get("-layer"));
- if (layer == null)
- return String.format("Layer %s does not exist", args.get("-layer"));
- if (command.equals("update"))
- if (manager.layerSet.update(layer.getId(), args))
- return "Layer has been updated";
- if (command.equals("show")) {
- return manager.layerSet.show(layer.getId());
- }
- if (command.equals("delete")) {
- if (manager.layerSet.delete(layer.getId()))
- return "Layer has been deleted";
- }
- break;
- }
- }
- catch (Exception e){
- System.out.println(e.getMessage());
- return "Wrong set of arguments";
- }
- return "Failed to run the command";
- }
- }
- _____________________________________________________
- package Core;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Locale;
- public class MapGenerator {
- String begin = "<!DOCTYPE html><html>"+
- " <head>\n" +
- " <!-- Leaflet's CSS -->\n" +
- " <link rel=\"stylesheet\" href=\"https://unpkg.com/leaflet@1.4.0/dist/leaflet.css\"\n" +
- " integrity=\"sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==\"\n" +
- " crossorigin=\"\"/>\n" +
- " <!-- Leaflet JavaScript -->\n" +
- " <script src=\"https://unpkg.com/leaflet@1.4.0/dist/leaflet.js\"\n" +
- " integrity=\"sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==\"\n" +
- " crossorigin=\"\"></script>\n" +
- "\n" +
- " <script>\n" +
- "\t\thtml, body {\n" +
- "\t\t\theight: 100%;\n" +
- "\t\t\tmargin: 0;\n" +
- "\t\t}\n" +
- "\t\t#map {\n" +
- "\t\t\twidth: 600px;\n" +
- "\t\t\theight: 400px;\n" +
- "\t\t}\n" +
- " </script>\n" +
- "\n" +
- " <script type=\"text/javascript\" src=\"chrome-extension://aggiiclaiamajehmlfpkjmlbadmkledi/popup.js\" async=\"\"></script>\n" +
- " <script type=\"text/javascript\" src=\"chrome-extension://aggiiclaiamajehmlfpkjmlbadmkledi/tat_popup.js\" async=\"\"></script>\n" +
- " </head>" +
- " <body>\n" +
- " <!-- map div -->\n" +
- " <div id=\"mapid\" style=\"width: 600px; height: 400px; position: relative;\"></div>\n"+
- "<script> \n"+
- " var mbAttr = 'Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>';\n"+
- " var mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYWRyYXgiLCJhIjoiY2p1OTQ0dW1kMTV5bzN5bnpsemlpbTh3NSJ9.evyvRseaJS0WSTlgR38MXg';\n"+
- " var layer_map_id = 'mapbox.streets';";
- String end = "\nvar control = L.control.layers(baseMaps, overlayMaps);\n" +
- " control.addTo(mymap);" +
- " </script>\n" +
- " </body>\n" +
- "</html>";
- /**
- * Generates html map with Leaflet using map and its layers
- * @param layers
- * @param map
- * @return
- */
- public String generateMap(List<Layer> layers, MyMap map) {
- StringBuilder html = new StringBuilder();
- html.append(begin);
- StringBuilder layersList = new StringBuilder();
- StringBuilder baseMaps = new StringBuilder();
- baseMaps.append("var baseMaps = {");
- StringBuilder overlayMaps = new StringBuilder();
- overlayMaps.append("var overlayMaps = {");
- for (Layer layer: layers) {
- html.append(String.format("var %s = L.tileLayer(mbUrl, {id: '%s', attribution: mbAttr});",
- layer.getName(), layer.getLink()));
- //html.append(buildLayer(layer.getName(), layer.getMapBoxUrl(),layer.getMapBoxAttr(),layer.getLayerId()));
- html.append("\n");
- // Build layers lists
- if (layer.getType().equals("base")) {
- baseMaps.append(String.format("\" %s\":%s,", layer.getName(), layer.getName()));
- }
- else{
- overlayMaps.append(String.format("\" %s\":%s,", layer.getName(), layer.getName()));
- }
- layersList.append(layer.getName());
- layersList.append(',');
- }
- baseMaps.append("};");
- overlayMaps.append("};");
- String mapHtml = String.format(Locale.US, "var mymap = L.map('mapid', {center: [%.2f, %.2f],zoom: %d,layers:[]});",
- map.getX(), map.getY(), map.getZoom());
- html.append(mapHtml);
- html.append(baseMaps.toString());
- html.append(overlayMaps.toString());
- html.append(end);
- return html.toString();
- }
- /**
- * Should be used to make layer js string from Layer
- * @return
- */
- public String buildLayer(String name, String mbUrl, String mbAttr, String id ){
- String layer = String.format("var %s = L.tileLayer('%s', {id: '%s', attribution: '%s'});",
- name, mbUrl, id, mbAttr);
- return layer;
- }
- public List<Layer> generateLayers(){
- List<Layer> layers = new ArrayList<Layer>();
- String mbUrl = "https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYWRyYXgiLCJhIjoiY2p1OTQ0dW1kMTV5bzN5bnpsemlpbTh3NSJ9.evyvRseaJS0WSTlgR38MXg";
- String mbAttr = "Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>";
- /*for(int i = 0; i<5; i++){
- Layer layer = new Layer("layer"+Integer.toString(i),
- "base",
- "mapbox.light",
- mbUrl,
- mbAttr);
- layers.add(layer);
- }
- */
- //Map map = new Map("map1",39.73, -104.99, 6);
- //writeHtml(new MapGenerator().generateMap(layers, map));
- return layers;
- }
- }
- _______________________________________________________________________________
- package DataBase;
- import Core.Layer;
- import Core.MyMap;
- import java.sql.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- public class MapSet {
- private Connection connection;
- public void setConnection(Connection conn){
- connection = conn;
- }
- public MapSet(Connection connection){
- this.connection = connection;
- }
- /**
- * Adds new map to the DataBase
- *
- * @param name
- * @param x
- * @param y
- * @param zoom
- * @param userId
- * @return
- */
- public boolean add(String name, double x, double y, int zoom, int userId) {
- String sql = "INSERT INTO Maps(name, x, y, zoom, user_id) VALUES(?,?,?,?,?)";
- // Check if map already exists
- if (find(name) != null)
- return false;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- pstmt.setString(1, name);
- pstmt.setDouble(2, x);
- pstmt.setDouble(3, y);
- pstmt.setInt(4, zoom);
- pstmt.setInt(5, userId);
- pstmt.executeUpdate();
- System.out.println(String.format("Map %s has been added!", name));
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- /**
- * Update name of a map specified by the id
- *
- * @param id
- * @param args
- */
- public boolean update(int id, Map<String, String> args) {
- // Generate sql string
- StringBuilder sb = new StringBuilder();
- sb.append("UPDATE Maps SET");
- if (args.containsKey("-name")) {
- // Check if layer already exists
- if (find(args.get("-name")) != null)
- return false;
- sb.append(" name = ?,");
- }
- if (args.containsKey("-x"))
- sb.append(" x = ?,");
- if (args.containsKey("-y"))
- sb.append(" y = ?,");
- if (args.containsKey("-zoom"))
- sb.append(" zoom = ?,");
- sb.setLength(sb.length() - 1);
- sb.append(" WHERE id = ?");
- String sql = sb.toString();
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- int counter = 1;
- // Set corresponding parameters
- if (args.containsKey("-name")) {
- pstmt.setString(counter, args.get("-name"));
- counter++;
- }
- if (args.containsKey("-x")) {
- pstmt.setDouble(counter, Double.parseDouble(args.get("-x")));
- counter++;
- }
- if (args.containsKey("-y")){
- pstmt.setDouble(counter, Double.parseDouble(args.get("-y")));
- counter++;
- }
- if (args.containsKey("-zoom")){
- pstmt.setDouble(counter, Integer.parseInt(args.get("-zoom")));
- counter++;
- }
- pstmt.setInt(counter, id);
- // Update
- pstmt.executeUpdate();
- System.out.println("Map's has been updated!");
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- /**
- * Delete a map specified by the id
- *
- * @param id
- */
- public boolean delete(int id) {
- String sql = "DELETE FROM Maps WHERE id = ?";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- pstmt.setInt(1, id);
- pstmt.executeUpdate();
- System.out.println(String.format("Map with id %d is deleted!", id));
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- return false;
- }
- }
- /**
- * Searches for a map by name
- */
- public MyMap find(String name){
- MyMap map = null;
- String sql = "SELECT id, name, x, y, zoom, user_id FROM Maps WHERE name = ?";
- ResultSet rs = null;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setString(1, name);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- map = new MyMap( rs.getInt("id"),
- rs.getString("name"),
- rs.getDouble("x"),
- rs.getDouble("y"),
- rs.getInt("zoom"));
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getDouble("x") + "\t" +
- rs.getDouble("y") + "\t" +
- rs.getInt("zoom") + "\t" +
- rs.getInt("user_id"));
- return map;
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return map;
- }
- /**
- * Searches for a map by name
- */
- public List<Layer> getLayers(int mapId){
- String sql = "SELECT id, name, link FROM Layers WHERE map_id = ?";
- ResultSet rs = null;
- List<Layer> layers = new ArrayList<Layer>();
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setInt(1, mapId);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- layers.add(new Layer(rs.getInt("id"),
- rs.getString("name"),
- rs.getString("link")));
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getString("link"));
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return layers;
- }
- /**
- * Select all rows in the Maps table
- */
- public void selectAll(){
- String sql = "SELECT id, name, user_id FROM Maps";
- try (Statement stmt = connection.createStatement();
- ResultSet rs = stmt.executeQuery(sql)){
- // loop through the result set
- while (rs.next()) {
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getString("user_id"));
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- }
- ____________________________________________________________________
- package DataBase;
- import Core.Layer;
- import java.sql.*;
- import java.util.Map;
- public class LayerSet {
- private Connection connection;
- public void setConnection(Connection conn){
- connection = conn;
- }
- public LayerSet(Connection connection){
- this.connection = connection;
- }
- /**
- * Adds new map to the DataBase
- *
- * @param link
- * @param mapId
- */
- public boolean add(String name, String link, int mapId) {
- String sql = "INSERT INTO Layers (name, link, map_id) VALUES(?,?,?)";
- // Check if layer already exists
- if (find(name) != null)
- return false;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- pstmt.setString(1, name);
- pstmt.setString(2, link);
- pstmt.setInt(3, mapId);
- pstmt.executeUpdate();
- System.out.println(String.format("Layer \" %s \" has been added!", link));
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- /**
- * Update name of a map specified by the id
- *
- * @param id
- * @param args
- */
- public boolean update(int id, Map<String, String> args) {
- // Cook sql request
- StringBuilder sb = new StringBuilder();
- sb.append("UPDATE Layers SET");
- if (args.containsKey("-name")) {
- // Check if layer with "new name" already exists
- if (find(args.get("-name")) != null)
- return false;
- sb.append(" name = ?,");
- }
- if (args.containsKey("-link"))
- sb.append(" link = ?,");
- sb.setLength(sb.length() - 1);
- sb.append(" WHERE id = ?");
- String sql = sb.toString();
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- int counter = 1;
- // Set corresponding parameters
- if (args.containsKey("-name")) {
- pstmt.setString(counter, args.get("-name"));
- counter++;
- }
- if (args.containsKey("-link")) {
- pstmt.setString(counter, args.get("-link"));
- counter++;
- }
- pstmt.setInt(counter, id);
- // update
- pstmt.executeUpdate();
- System.out.println("Layer has been changed");
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- /**
- * Delete a map specified by the id
- * @param id
- * @return true|false
- */
- public boolean delete(int id) {
- String sql = "DELETE FROM Layers WHERE id = ?";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- pstmt.setInt(1, id);
- pstmt.executeUpdate();
- System.out.println(String.format("Layer with id %d is deleted!", id));
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- return false;
- }
- }
- /**
- * Searches for a map by name
- * @param name
- * @return Layer
- */
- public Layer find(String name){
- Layer layer = null;
- String sql = "SELECT id, name, link, map_id FROM Layers WHERE name = ?";
- ResultSet rs = null;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setString(1, name);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- layer = new Layer( rs.getInt("id"),
- rs.getString("name"),
- rs.getString("link"));
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getString("link") + "\t" +
- rs.getInt("map_id"));
- return layer;
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return layer;
- }
- /**
- * Make a representation of layer with its attributes
- * @param id
- * @return String
- */
- public String show(int id){
- String sql = "SELECT id, name, link, map_id FROM Layers WHERE id = ?";
- StringBuilder sb = new StringBuilder();
- ResultSet rs = null;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setInt(1, id);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- sb.append(rs.getString("id"));
- sb.append("\t");
- sb.append(rs.getString("name"));
- sb.append("\t");
- sb.append(rs.getString("link"));
- sb.append("\t");
- sb.append(rs.getString("map_id"));
- }
- System.out.println(sb.toString());
- return sb.toString();
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return "Failed";
- }
- /**
- * Select all rows in the Layers table
- */
- public String selectAll(){
- String sql = "SELECT id, name, link, map_id FROM Layers";
- StringBuilder sb = new StringBuilder();
- try (Statement stmt = connection.createStatement();
- ResultSet rs = stmt.executeQuery(sql)){
- // loop through the result set
- while (rs.next()) {
- sb.append(rs.getString("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getString("link") + "\t" +
- rs.getString("map_id") + "\n");
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("name") + "\t" +
- rs.getString("link") + "\t" +
- rs.getInt("map_id"));
- }
- return sb.toString();
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return "Failed";
- }
- }
- __________________________________________________________________________
- package DataBase;
- import java.security.SecureRandom;
- import java.sql.*;
- public class UserSet {
- private Connection connection;
- public void setConnection(Connection conn){
- connection = conn;
- }
- public UserSet(Connection connection){
- this.connection = connection;
- }
- public String generateToken(){
- SecureRandom random = new SecureRandom();
- byte bytes[] = new byte[20];
- random.nextBytes(bytes);
- String token = bytes.toString();
- return token;
- }
- /**
- * Adds new user to the DataBase
- *
- * @param login
- * @param password
- */
- public boolean add(String login, String password) {
- String sql = "INSERT INTO Users(login, password, token) VALUES(?,?,?)";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- pstmt.setString(1, login);
- pstmt.setString(2, password);
- pstmt.setString(3, generateToken());
- pstmt.executeUpdate();
- System.out.println(String.format("User %s has been added!", login));
- return true;
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- /**
- * Update data of a user specified by the id
- *
- * @param id
- * @param login name of the warehouse
- * @param password capacity of the warehouse
- */
- public void update(int id, String login, String password) {
- String sql = "UPDATE Users SET login = ? , "
- + "password = ? "
- + "WHERE id = ?";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- // set the corresponding param
- pstmt.setString(1, login);
- pstmt.setString(2, password);
- pstmt.setInt(3, id);
- // update
- pstmt.executeUpdate();
- System.out.println(String.format("User %s has been updated!", login));
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * Delete a user specified by the id
- *
- * @param id
- */
- public void delete(int id) {
- String sql = "DELETE FROM Users WHERE id = ?";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- // set the corresponding param
- pstmt.setInt(1, id);
- // execute the delete statement
- pstmt.executeUpdate();
- System.out.println(String.format("User with id %d is deleted!", id));
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * Select all rows in the Users table
- */
- public void selectAll(){
- String sql = "SELECT id, login, password FROM Users";
- try (Statement stmt = connection.createStatement();
- ResultSet rs = stmt.executeQuery(sql)){
- // loop through the result set
- while (rs.next()) {
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("login") + "\t" +
- rs.getString("password"));
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- /**
- * Searches for a user by login
- */
- public int findByToken(String token){
- String sql = "SELECT id, login FROM Users WHERE token = ?";
- ResultSet rs = null;
- int userId = -1;
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setString(1, token);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- userId = rs.getInt("id");
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("login"));
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return userId;
- }
- /**
- * Searches for a user by login
- */
- public boolean login(String login, String password, String token){
- String sql = "SELECT id, login, password FROM Users WHERE login = ?";
- ResultSet rs = null;
- int userId = -1;
- System.out.println(String.format("Requested %s %s", login, password));
- try (PreparedStatement pstmt = connection.prepareStatement(sql)){
- pstmt.setString(1, login);
- rs = pstmt.executeQuery();
- // loop through the result set
- while (rs.next()) {
- System.out.println(rs.getInt("id") + "\t" +
- rs.getString("login") + "\t" +
- rs.getString("password"));
- if (password.equals(rs.getString("password"))) {
- updateToken(rs.getInt("id"), token);
- return true;
- }
- }
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- return false;
- }
- private void updateToken(int id, String token) {
- String sql = "UPDATE Users SET token = ? "
- + "WHERE id = ?";
- try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
- // set the corresponding param
- pstmt.setString(1, token);
- pstmt.setInt(2, id);
- // update
- pstmt.executeUpdate();
- System.out.println(String.format("Token for User %s has been updated!", id));
- } catch (SQLException e) {
- System.out.println(e.getMessage());
- }
- }
- }
- _______________________________________________________________________________________
- import Core.Interpreter;
- import DataBase.DBManager;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.websocketx.*;
- public class WebSocketHandler extends ChannelInboundHandlerAdapter {
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- if (msg instanceof WebSocketFrame) {
- System.out.println("This is a WebSocket frame");
- System.out.println("Client Channel : " + ctx.channel());
- if (msg instanceof BinaryWebSocketFrame) {
- System.out.println("BinaryWebSocketFrame Received : ");
- System.out.println(((BinaryWebSocketFrame) msg).content());
- } else if (msg instanceof TextWebSocketFrame) {
- System.out.println("TextWebSocketFrame Received : ");
- String input = ((TextWebSocketFrame) msg).text();
- System.out.println(input);
- String result = processCode(input);
- ctx.channel().writeAndFlush(new TextWebSocketFrame(result));
- System.out.println(result);
- } else if (msg instanceof PingWebSocketFrame) {
- System.out.println("PingWebSocketFrame Received : ");
- System.out.println(((PingWebSocketFrame) msg).content());
- } else if (msg instanceof PongWebSocketFrame) {
- System.out.println("PongWebSocketFrame Received : ");
- System.out.println(((PongWebSocketFrame) msg).content());
- } else if (msg instanceof CloseWebSocketFrame) {
- System.out.println("CloseWebSocketFrame Received : ");
- System.out.println("ReasonText :" + ((CloseWebSocketFrame) msg).reasonText());
- System.out.println("StatusCode : " + ((CloseWebSocketFrame) msg).statusCode());
- } else {
- System.out.println("Unsupported WebSocketFrame");
- ctx.channel().writeAndFlush(new TextWebSocketFrame("What do you mean?"));
- }
- }
- }
- private String processCode(String code){
- String result = "none";
- try {
- DBManager manager = new DBManager("new");
- result = new Interpreter(manager).start(code);
- } catch (NullPointerException e) {
- System.out.println(e.toString());
- }
- return result;
- }
- }
- _________________________________________________________________
- import Core.Interpreter;
- import DataBase.DBManager;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.ChannelInboundHandlerAdapter;
- import io.netty.handler.codec.http.HttpContentEncoder;
- import io.netty.handler.codec.http.HttpHeaderNames;
- import io.netty.handler.codec.http.HttpHeaders;
- import io.netty.handler.codec.http.HttpRequest;
- import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
- import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
- import io.netty.util.CharsetUtil;
- /**
- * Handles a server-side channel.
- */
- public class ServerHandler extends ChannelInboundHandlerAdapter {
- WebSocketServerHandshaker handshaker;
- @Override
- public void channelRead(ChannelHandlerContext ctx, Object msg) {
- //((ByteBuf) msg).release();
- if (msg instanceof HttpRequest) {
- HttpRequest httpRequest = (HttpRequest) msg;
- System.out.println("Http Request Received");
- HttpHeaders headers = httpRequest.headers();
- System.out.println("Connection : " +headers.toString());
- if ("Upgrade".equalsIgnoreCase(headers.get(HttpHeaderNames.CONNECTION)) &&
- "WebSocket".equalsIgnoreCase(headers.get(HttpHeaderNames.UPGRADE))) {
- //Adding new handler to the existing pipeline to handle WebSocket Messages
- ctx.pipeline().replace(this, "websocketHandler", new WebSocketHandler());
- System.out.println("WebSocketHandler added to the pipeline");
- System.out.println("Opened Channel : " + ctx.channel());
- //Do the Handshake to upgrade connection from HTTP to WebSocket protocol
- handleHandshake(ctx, httpRequest);
- System.out.println("Handshake is done");
- }
- }
- else
- {
- System.out.println("Unsupported message was received");
- }
- }
- /* Do the handshaking for WebSocket request */
- protected void handleHandshake(ChannelHandlerContext ctx, HttpRequest req) {
- WebSocketServerHandshakerFactory wsFactory =
- new WebSocketServerHandshakerFactory(getWebSocketURL(req), null, true);
- handshaker = wsFactory.newHandshaker(req);
- if (handshaker == null) {
- WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
- } else {
- handshaker.handshake(ctx.channel(), req);
- }
- }
- protected String getWebSocketURL(HttpRequest req) {
- String url = "ws://" + req.headers().get("Host");
- System.out.println("Constructed URL : " + url);
- return url;
- }
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
- // Close the connection when an exception is raised.
- cause.printStackTrace();
- ctx.close();
- }
- }
- _______________________________________________________
- import Core.Interpreter;
- import DataBase.DBManager;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.ChannelOption;
- import io.netty.channel.EventLoopGroup;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- import io.netty.handler.codec.http.HttpServerCodec;
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- /**
- * Discards any incoming data.
- */
- public class Server {
- private int port;
- public Server(int port) {
- this.port = port;
- }
- public void run() throws Exception {
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast("httpServerCodec", new HttpServerCodec());
- ch.pipeline().addLast("httpHandler", new ServerHandler());
- }
- })
- .option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
- // Bind and start to accept incoming connections.
- ChannelFuture f = b.bind(port).sync();
- // Wait until the server socket is closed.
- // In this example, this does not happen, but you can do that to gracefully
- // shut down your server.
- f.channel().closeFuture().sync();
- } finally {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
- public static void main(String[] args) throws Exception {
- int port = 9090;
- if (args.length > 0) {
- port = Integer.parseInt(args[0]);
- }
- //initDB();
- //initUser();
- new Server(port).run();
- //DBManager manager = new DBManager("new");
- //System.out.println(new Interpreter(manager).interpret("map create -map map2 -x 1 -y 2 -zoom 3"));
- //test();
- }
- private static void initDB(){
- DBManager.initDataBase("new");
- }
- private static void initUser(){
- DBManager manager = new DBManager("new");
- manager.userSet.add("Gosha", "pswd");
- }
- private static void test() {
- //DBManager.initDataBase("new");
- DBManager manager = new DBManager("new");
- //manager.userSet.add("Gosha", "password");
- //String code = "create map new_map 3 5 4";
- String code = "update map new_map newMap";
- String result = new Interpreter(manager).start(code);
- System.out.print(result);
- //writeHtml(result);
- manager.mapSet.selectAll();
- }
- public static void writeHtml(String text) throws IOException
- {
- BufferedWriter writer = new BufferedWriter(new FileWriter("samplefile1.html"));
- writer.write(text);
- writer.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement