· 8 years ago · Mar 03, 2018, 01:04 AM
1package bstms.backend;
2
3
4import org.jetbrains.annotations.Nullable;
5import org.opencv.videoio.VideoCapture;
6
7import java.io.*;
8import java.net.*;
9import java.sql.*;
10
11public class Server implements Runnable {
12
13 public Server_Thread clients[];
14 public ServerSocket server = null;
15 public Thread thread = null;
16 public int clientCount = 0;
17 private final int port = 14000;
18 public Connection conn;
19 private String camera_name,URL;
20 private VideoCapture cameraStream[];
21
22 public Server() {
23 init();//CREATE THE DATABASE TABLES
24 clients = new Server_Thread[10];//MAX of 10 cameras allowed
25 try {
26 server = new ServerSocket(port);//CREATE THE SERVER AS socket server on port 14000
27 System.out.println("SERVER STARTED AT IP : " + InetAddress.getLocalHost() + " ON Port : " + server.getLocalPort());
28 start();
29 } catch (IOException ioe) {
30 System.out.println("Can not bind to port " + port + ": " + ioe.getMessage());
31 }
32 }
33
34 public void run() {
35 while (thread != null) {
36 try {
37 System.out.println("Waiting for a Camera ...");
38 addThread(server.accept());
39 } catch (Exception ioe) {
40 System.out.println("Cam accept error:" + ioe);
41 }
42 }
43 }
44
45 public void start() {
46 if (thread == null) {
47 thread = new Thread(this);
48 thread.start();
49 }
50 }
51
52 public void stop() {
53 if (thread != null) {
54 thread = null;
55 }
56 }
57
58 private int findCameraByID(int ID) {
59 for (int i = 0; i < clientCount; i++) {
60 if (clients[i].getID() == ID) {
61 return i;
62 }
63 }
64 return -1;
65 }
66
67 public synchronized void handle(int ID, Server_MSG msg) throws SQLException {
68 if (msg.type.equals("VIDEO_SOURCE")) {
69 this.camera_name = msg.camera_name;
70 clients[findCameraByID(ID)].send(
71 new Server_MSG("info", msg.camera_name+"LOGGED IN","-- "+msg.camera_name+" --"));
72 }
73
74 if (msg.type.equals("start")) {
75 System.out.println("PAUSING MONITORING USING CAMERA " + msg.camera_name + "");
76 boolean isRunning = start_camera(msg.camera_name,ID);
77 clients[findCameraByID(ID)].send(new Server_MSG("status",isRunning+"","-- "+msg.camera_name+" --"));
78 }
79
80 if (msg.type.equals("stop")) {
81 System.out.println("PAUSING MONITORING USING CAMERA " + msg.camera_name + "");
82 boolean isRunning = stop_camera(ID);
83 clients[findCameraByID(ID)].send(new Server_MSG("status",isRunning+"","-- "+msg.camera_name+" --"));
84 }
85
86 }
87
88 private boolean start_camera(String cameraName,int ID) throws SQLException {
89 if(cameraStream[findCameraByID(ID)].isOpened()){
90 print("camera already running");
91 return true;
92 }else {
93 boolean open = cameraStream[findCameraByID(ID)].open(getURL(cameraName) + "");
94 print("Attempt of running camera stream @ "+cameraName+" returned [--"+open+"--]");
95 if (open){
96 return true;
97 }else{
98 return false;
99 }
100 }
101 }
102
103 private String getURL(String cameraName) throws SQLException {
104 ResultSet R = query("SELECT url from camera WHERE name='"+cameraName+"'",0);
105 String x = "";
106 while (R.next()){
107 x = R.getString("url");
108 }
109 return x;
110 }
111
112 private void init(){
113 String sql0 = "" +
114 "CREATE TABLE IF NOT EXISTS `offense` (" +
115 "`type` int(1) NOT NULL," +
116 "`date_committed` datetime NOT NULL," +
117 "`number_plate` varchar(20) NOT NULL," +
118 "`camera_ID` int(11) NOT NULL," +
119 "`penaltyID` int(11) NOT NULL," +
120 "`ID` int(11) NOT NULL AUTO_INCREMENT," +
121 "PRIMARY KEY (`ID`)," +
122 "KEY `camera_ID` (`camera_ID`)," +
123 "KEY `penaltyID` (`penaltyID`)," +
124 "CONSTRAINT `offense_fk_1` FOREIGN KEY (`camera_ID`) REFERENCES `camera` (`ID`)," +
125 "CONSTRAINT `offense_fk_2` FOREIGN KEY (`penaltyID`) REFERENCES `penalty` (`ID`)" +
126 ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";
127
128 String sql1 = "CREATE TABLE IF NOT EXISTS `penalty` (" +
129 "`ID` int(11) NOT NULL AUTO_INCREMENT," +
130 "`description` text NOT NULL," +
131 "`amount` double NOT NULL," +
132 "`name` varchar(20) NOT NULL," +
133 "PRIMARY KEY (`ID`)" +
134 ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";
135
136 String sql2 = "CREATE TABLE IF NOT EXISTS `road` (" +
137 "`name` varchar(65) NOT NULL," +
138 "`ID` int(11) NOT NULL AUTO_INCREMENT," +
139 "`from_` varchar(65) NOT NULL," +
140 "`to_` varchar(65) NOT NULL," +
141 "PRIMARY KEY (`ID`)" +
142 ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";
143
144 String sql3 = "CREATE TABLE IF NOT EXISTS `camera` (" +
145 "`ID` int(11) NOT NULL AUTO_INCREMENT," +
146 "`name` varchar(40) NOT NULL," +
147 "`roadID` int(11) NOT NULL," +
148 "`url` text NOT NULL," +
149 "PRIMARY KEY (`ID`)," +
150 "KEY `roadName` (`roadID`)," +
151 "CONSTRAINT `camera_fk_1` FOREIGN KEY (`roadID`) REFERENCES `road` (`ID`)" +
152 ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";
153 query(sql0,1);
154 query(sql1,1);
155 query(sql2,1);
156 query(sql3,1);
157 }
158
159 @Nullable
160 private ResultSet query(String sql, int type) {
161 Connection conn;
162 PreparedStatement pst = null;
163 ResultSet rs = null;
164 String url = "jdbc:mysql://localhost:3306/";
165 String dbName = "bstms_db";
166 String driver = "com.mysql.jdbc.Driver";
167 String userName = "root";
168 String password = "/";
169 try {
170 Class.forName(driver).newInstance();
171 conn = DriverManager
172 .getConnection(url + dbName, userName, password);
173 pst = conn.prepareStatement(sql);
174 if (type < 1) {
175 rs = pst.executeQuery();
176 } else {
177 pst.execute();
178 }
179 return rs;
180 } catch (Exception e) {
181 System.out.println(e);
182 }
183 return null;
184 }
185
186 private void print(String m){
187 System.out.println("--"+m+"--");
188 }
189 private boolean stop_camera(int ID) {
190
191 if(cameraStream[findCameraByID(ID)].isOpened()){
192 cameraStream[findCameraByID(ID)].release();
193 return true;
194 }else {
195 return false;
196 }
197 }
198
199 public synchronized void remove(int ID) {
200 int pos = findCameraByID(ID);
201 if (pos >= 0) {
202 Server_Thread toTerminate = clients[pos];
203 System.out.println("Removing Camera Connection thread " + ID + " at " + pos);
204 if (pos < clientCount - 1) {
205 for (int i = pos + 1; i < clientCount; i++) {
206 clients[i - 1] = clients[i];
207 }
208 }
209 clientCount--;
210 try {
211 toTerminate.close();
212 } catch (IOException ioe) {
213 System.out.println("Error closing thread: " + ioe);
214 }
215 }
216 }
217
218 private void addThread(Socket socket) {
219 if (clientCount < clients.length) {
220 System.out.println("Camera connection accepted: " + socket);
221 clients[clientCount] = new Server_Thread(this, socket);
222 try {
223 this.getConnection(); //*** IMPORTANT CREATE CONNECTION OBJECT FOR EACH CAMERA (client object)
224 System.out.println("CONNETED TO Database..");
225 clients[clientCount].open();
226 clients[clientCount].start();
227 cameraStream[clientCount] = null;
228 clientCount++;
229 } catch (IOException ioe) {
230 System.out.println("\nError opening thread: " + ioe);
231 }
232 } else {
233 System.out.println("\nCamera refused: maximum " + clients.length + " reached.");
234
235 }
236 }
237
238 public static void main(String[] args) {
239 new Server();
240 }
241
242 private void getConnection() {
243 String url = "jdbc:mysql://localhost:3306/";
244 String dbName = "bstms_db";
245 String driver = "com.mysql.jdbc.Driver";
246 String userName = "root";
247 String password = "/";
248 try {
249 Class.forName(driver).newInstance();
250 this.conn = DriverManager
251 .getConnection(url + dbName, userName, password);
252 } catch (Exception e) {
253 System.out.println(e);
254 }
255 }
256
257
258}
259
260class Server_MSG implements Serializable {
261
262 private static final long serialVersionUID = 1L;
263 public String type, message;
264 public String camera_name;
265
266 public Server_MSG(String type, String message,String camera_name) {
267 this.type = type;
268 this.message = message;
269 this.camera_name = camera_name;
270 }
271
272 @Override
273 public String toString() {
274 return " *** " + type + " *** SERVER MESSAGE ";
275 }
276}
277
278class Server_Thread extends Thread {
279
280 public Server server = null;
281 public Socket socket = null;
282 public int ID = -1;
283 public ObjectInputStream streamIn = null;
284 public ObjectOutputStream streamOut = null;
285
286 public Server_Thread(Server _server, Socket _socket) {
287 super();
288 server = _server;
289 socket = _socket;
290 ID = socket.getPort();
291 }
292
293 public void send(Server_MSG msg) {
294 try {
295 streamOut.writeObject(msg);
296 streamOut.flush();
297 } catch (IOException ex) {
298 ex.getMessage();
299 }
300 }
301
302 public int getID() {
303 return ID;
304 }
305
306 public void run() {
307 System.out.println("Server Thread " + ID + " running. ");
308 while (true) {
309 try {
310 Server_MSG msg = (Server_MSG) streamIn.readObject();
311 server.handle(ID, msg);
312 } catch (IOException ioe) {
313 System.out.println(ID + " ERROR reading: " + ioe.getMessage());
314 server.remove(ID);
315 stop();
316 } catch (ClassNotFoundException ioe) {
317 System.out.println(ID + "CNFE ERROR reading: " + ioe.getMessage());
318 server.remove(ID);
319 stop();
320 } catch (SQLException ex) {
321 System.out.println(ID + " SQL Error Occurred:"+ex);
322 ex.printStackTrace();
323 }
324 }
325 }
326
327 public void open() throws IOException {
328 streamOut = new ObjectOutputStream(socket.getOutputStream());
329 streamOut.flush();
330 streamIn = new ObjectInputStream(socket.getInputStream());
331 }
332
333 public void close() throws IOException {
334 if (socket != null) {
335 socket.close();
336 }
337 if (streamIn != null) {
338 streamIn.close();
339 }
340 if (streamOut != null) {
341 streamOut.close();
342 }
343 }
344}