Advertisement
Guest User

Untitled

a guest
Jan 9th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.33 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package tcpserver;
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.IOException;
  10. import java.io.InputStreamReader;
  11. import java.io.PrintWriter;
  12.  
  13. import java.net.ServerSocket;
  14. import java.net.Socket;
  15. import java.net.SocketException;
  16. import java.sql.Connection;
  17. import java.sql.DriverManager;
  18. import java.sql.ResultSet;
  19. import java.sql.SQLException;
  20. import java.sql.Statement;
  21. import java.util.Date;
  22. import java.util.HashSet;
  23. import java.util.StringTokenizer;
  24.  
  25. /**
  26. *
  27. * @author Mariusz
  28. */
  29. public class TCPServer implements Runnable {
  30.  
  31. /**
  32. * @param args the command line arguments
  33. * @throws java.io.IOException
  34. */
  35.  
  36. public String getMessage(String login){
  37. String result="";
  38. String id=String.valueOf(getLoginId(login));
  39.  
  40. String sSQL = " SELECT LOGIN, DATE, BODY FROM messages, users WHERE " ;
  41. sSQL+= " id_from =" + id + "AND users.id = messages.id_to ORDER BY date";
  42.  
  43. Statement st;
  44. Connection conn;
  45. ResultSet rs;
  46.  
  47. try {
  48. conn = DriverManager.getConnection("jdbc:derby:db;create=true");
  49. st = conn.createStatement();
  50. // wstaw llogin do bazy
  51. rs = st.executeUpdate(sSQL);
  52.  
  53. result += rs.getString(1)+" " +rs.getString(2)+" "+rs.getString(3);
  54.  
  55. }
  56. catch (SQLException ex) {
  57. System.out.println("SQLException : "+ ex) ;
  58. }
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65. return result;
  66. }
  67. public int saveMessage(String login, String sendTo, String message){
  68.  
  69. String id_from = String.valueOf(getLoginId(login));
  70. String id_to = String.valueOf(getLoginId(sendTo));
  71.  
  72. Statement st;
  73. Connection conn;
  74. ResultSet rs;
  75. String d = simpleDateHere.forma(new Date());
  76.  
  77.  
  78. String sSQL = "INSERT INTO messages (id_from, id_to, mdate, body)";
  79. sSQL +="VALUES ( " + id_from + ", " +id_to + ", "+ d + " + message +")";
  80.  
  81. try {
  82. conn = DriverManager.getConnection("jdbc:derby:db;create=true");
  83. st = conn.createStatement();
  84. // wstaw llogin do bazy
  85. st.executeUpdate(sSQL);
  86.  
  87. }
  88. catch (SQLException ex) {
  89. System.out.println("SQLException : "+ ex) ;
  90. }
  91.  
  92. return 0;
  93. }
  94.  
  95. public int registerLogin(String login){
  96.  
  97. int id=getLoginId(login);
  98.  
  99. Statement st;
  100. Connection conn;
  101. ResultSet rs;
  102.  
  103.  
  104. System.out.println("registerLogin: id="+ String.valueOf(id)) ;
  105.  
  106. if (id==0){
  107. System.out.println("registerLogin: "+ login) ;
  108. try {
  109. conn = DriverManager.getConnection("jdbc:derby:db;create=true");
  110. st = conn.createStatement();
  111. // wstaw llogin do bazy
  112. st.executeUpdate("INSERT INTO users (login) VALUES ('" + login+"')");
  113.  
  114. }
  115. catch (SQLException ex) {
  116. System.out.println("SQLException : "+ ex) ;
  117. id=0;
  118. }
  119. }
  120. else id=1;
  121. return id;
  122.  
  123. }
  124.  
  125.  
  126.  
  127. public int getLoginId(String login){
  128.  
  129. Statement st;
  130. Connection conn;
  131. ResultSet rs;
  132. int id=0;
  133.  
  134. try {
  135. conn = DriverManager.getConnection("jdbc:derby:db;create=true");
  136. st = conn.createStatement();
  137. rs = st.executeQuery("SELECT id FROM users WHERE login='"+login+"'");
  138.  
  139. if (rs.next()){
  140. id =rs.getInt("id");
  141.  
  142. }
  143. }
  144. catch (SQLException ex) {
  145.  
  146. }
  147.  
  148. return id;
  149. }
  150.  
  151.  
  152.  
  153. public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
  154.  
  155. Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
  156.  
  157. Connection conn = DriverManager.getConnection("jdbc:derby:db;create=true");
  158.  
  159. Statement st = conn.createStatement();
  160.  
  161. try {
  162. st.execute(
  163. "CREATE TABLE users (" +
  164. "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
  165. "login VARCHAR(24) NOT NULL)"
  166. );
  167. st.executeUpdate("INSERT INTO users (login) VALUES ('Szymon')");
  168. }
  169. catch (SQLException ex) {
  170. }
  171.  
  172.  
  173. try {
  174. st.execute(
  175. "CREATE TABLE messages (" +
  176. "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
  177. "id_from INTEGER NOT NULL, " +
  178. "id_to INTEGER NOT NULL, " +
  179. "date DATE NOT NULL, " +
  180. "body VARCHAR(2048)"+
  181. ")"
  182. );
  183.  
  184. }
  185. catch (SQLException ex) {
  186. System.out.println("CREATE TABLE messages: " + ex);
  187. }
  188.  
  189. ResultSet rs = st.executeQuery("SELECT id,login FROM users ORDER BY login");
  190. while(rs.next()) {
  191. System.out.println(rs.getInt("id") + ";" + rs.getString("login"));
  192. }
  193. ServerSocket ssock = new ServerSocket(8888);
  194. for(;;) {
  195. Socket sock = ssock.accept();
  196. TCPServer client = new TCPServer(sock);
  197. clients.add(client);
  198. new Thread(client).start();
  199. }
  200. }
  201. private static HashSet<TCPServer> clients = new HashSet<>();
  202. private Socket sock;
  203. private String login = null;
  204. private String sendTo = null;
  205. private PrintWriter out = null;
  206.  
  207. private TCPServer(Socket sock) throws IOException {
  208. this.sock = sock;
  209. out = new PrintWriter(sock.getOutputStream(), true);
  210. }
  211.  
  212. @Override
  213. public void run() {
  214. try {
  215.  
  216. BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  217. for(;;) {
  218. String s = null;
  219. try {
  220. s = in.readLine();
  221. } catch(SocketException e) {
  222. break;
  223. }
  224. if(s == null) break;
  225. /*
  226. interpretation of a command/data sent from clients
  227. */
  228. if(s.charAt(0) == '/') {
  229. // out.println("You entered a command " + s);
  230. StringTokenizer st = new StringTokenizer(s);
  231. String cmd = st.nextToken();
  232. switch(cmd) {
  233. case "/login":
  234. // zalogować się mozna gdy login jest juz w bazie zarejestrowany
  235. login = st.nextToken();
  236. if (getLoginId(login)!=0) {
  237. System.out.println("/login: " + login);
  238. out.println("OK " + login);
  239. }
  240. else {
  241. out.println(login + " not registered");
  242. login=null;
  243.  
  244. }
  245.  
  246. break;
  247. case "/whoami":
  248. if(login != null)
  249. out.println(login);
  250. else
  251. out.println("You are not logged in");
  252. break;
  253. case "/to":
  254. if(login != null) {
  255. sendTo = st.nextToken();
  256. out.println("OK " + login + " -> " + sendTo);
  257. } else
  258. out.println("You are not logged in");
  259. break;
  260. case "/exit":
  261. sock.close();
  262. clients.remove(this);
  263. return;
  264. case "/who":
  265.  
  266. int nli = 0;
  267. for(TCPServer client: clients) {
  268. if(client.login != null) {
  269. out.println(client.login + " -> " + (client.sendTo != null ? client.sendTo : ""));
  270. }
  271. else
  272. nli++;
  273. }
  274. out.println("not logged in: " + nli);
  275.  
  276.  
  277.  
  278. break;
  279. case "/reg":
  280. // zarejestrowanie urzytkownika w rejestrze
  281. // sprawdzenie czy user jest w bazie
  282. // jezeli nie to insert user do bazy danych i zwroc jego id
  283. // jezeli jest to zwroc jego id
  284. // + procedurea sprawdzająca
  285. // + metoda check user zraza null gdy nie ma usera
  286. // dopuszczenie w logowaniu tylko zarejestrowanych
  287. // run now !!
  288.  
  289.  
  290. // tableka na bufor
  291. // |id_msg|id_from|id_to|msg_body|date|
  292.  
  293. login = st.nextToken();
  294.  
  295. if (registerLogin(login) ==0)
  296. out.println("new login: "+login +" registered!");
  297. else out.println(login +" already registered!");
  298. login = null;
  299. break;
  300.  
  301. default:
  302. out.println("Unknown command " + cmd);
  303. }
  304. } else {
  305. if(login != null) {
  306. // out.println("You entered data [" + s + "]");
  307. int nrec = 0;
  308. for(TCPServer client: clients) {
  309. if(client.login != null && client.login.equals(sendTo)) {
  310. client.out.println(login + " says: " + s);
  311. nrec++;
  312. }
  313. else
  314. // nie zalogowany odbiorca
  315. // sprawdzanie czy jest w bazie login sendTo
  316. if (getLoginId(sendTo) != 0 ) {
  317. out.println(sendTo +" niezalogowany - zapisano wiadomość na później");
  318. saveMessage(login,sendTo,s);
  319. }
  320. }
  321.  
  322. out.println("messages sent: " + nrec+ " " +s);
  323. } else {
  324. out.println("You have to log in first");
  325. }
  326. }
  327. }
  328. } catch(IOException e) {}
  329. clients.remove(this);
  330. }
  331.  
  332. @Override
  333. public String toString() {
  334. return sock + " [" + (login != null ? (login + "->" + (sendTo != null ? sendTo : "")) : "") + "]";
  335. }
  336. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement