Advertisement
Guest User

Untitled

a guest
Nov 26th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.82 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.sql.*;
  8. import java.util.Random;
  9.  
  10. public class MulticastServer extends Thread {
  11. private static int porto;
  12. private static int nRegistos; // este valor ha de ser carregado de um ficheiro, conta o numero de registos
  13. public static Map logged = new HashMap<String, String>();
  14. private static String user;
  15. public static Config config = new Config("configServer.cfg");
  16. private static int portoRMI = config.getHostRmi();
  17. private static String MULTICAST_ADDRESS = config.getMultiAdd();
  18.  
  19. private static FileOutputStream f;
  20. private static FileInputStream fi;
  21. private static ObjectOutputStream o;
  22. private static ObjectInputStream oi;
  23.  
  24. private static final long serialVersionUID = 1L;
  25. static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
  26. static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
  27. static final String USER = "bd";
  28. static final String PASS = "bd";
  29. static Connection conn = null;
  30. static Savepoint sp = null;
  31.  
  32. // pede os dados de uma data
  33. private static java.sql.Timestamp inserirData(int ano, int mes, int dia, int minutos, int hora) {
  34. int segundos = 0, nanos = 0;
  35. System.out.println(ano + " " + mes + " " + dia + " " + hora + " " + minutos + " ");
  36. java.sql.Timestamp date = new java.sql.Timestamp(ano - 1899, mes - 12, dia - 31, hora, minutos, segundos,
  37. nanos);
  38. System.out.println(date);
  39. return date;
  40.  
  41. }
  42.  
  43. /**
  44. * Método para receber mensagens do cliente via TCP
  45. */
  46. public static void receiveTCP() {
  47. int numero = 0;
  48.  
  49. try {
  50. int serverPort = 6000;
  51. System.out.println("A Escuta no Porto 6000");
  52. ServerSocket listenSocket = new ServerSocket(serverPort);
  53. // System.out.println("LISTEN SOCKET="+listenSocket);
  54. while (true) {
  55. Socket clientSocket = listenSocket.accept(); // BLOQUEANTE
  56. System.out.println("CLIENT_SOCKET (created at accept())=" + clientSocket);
  57. numero++;
  58. new ClientThread(clientSocket);// criar nova classe chamada clientthread que recebe os pedidos que
  59. // chegam do cliente
  60. }
  61. } catch (IOException e) {
  62. System.out.println("Listen:" + e.getMessage());
  63. }
  64. }
  65.  
  66. // thread que envia mensagens para o server rmi e depois cliente; liga no porto
  67. // 4000 que e onde esta ligado o socket do rmi que recebe mensagens
  68. /**
  69. * Método para enivar mensagens para o server RMI
  70. *
  71. * @param texto Texto a enviar
  72. * @throws SocketException
  73. */
  74. public static void sendMsg(String texto) throws SocketException {
  75. new Thread() {
  76. public void run() {
  77. MulticastSocket aSocket = null;// atencao
  78. try {
  79. aSocket = new MulticastSocket();
  80.  
  81. byte[] m = texto.getBytes();
  82.  
  83. InetAddress aHost = InetAddress.getByName(MULTICAST_ADDRESS);
  84. // int serverPort = 4000;
  85. DatagramPacket request = new DatagramPacket(m, m.length, aHost, portoRMI);
  86. aSocket.send(request);
  87.  
  88. } catch (SocketException e) {
  89. System.out.println("Socket: " + e.getMessage());
  90. } catch (IOException e) {
  91. System.out.println("IO: " + e.getMessage());
  92. } finally {
  93. if (aSocket != null)
  94. aSocket.close();
  95. }
  96. }
  97.  
  98. }.start();
  99. }
  100.  
  101. // funcao que trata o comando recebido do cliente
  102. /**
  103. * Método para tratar os pedidos que chegam do cliente via server RMI
  104. *
  105. * @param comando Comando do cliente
  106. * @throws IOException
  107. */
  108. public static void escolheOpcao(String comando) throws IOException, SQLException {
  109.  
  110. // String user = new String();
  111. String password = new String();
  112. String tipo = new String();
  113. Pessoa newPessoa = new Pessoa();
  114. Artista newArtista = new Artista();
  115. Musica newMusica = new Musica();
  116. Album newAlbum = new Album();
  117. Critica newCritica = new Critica();
  118. String toAdmin = new String();
  119. Playlist newPlaylist = new Playlist();
  120. try {
  121. if (comando != null && comando != "\n" && comando != "") {
  122. String parts[] = comando.split(" ; ");
  123. String funcao[] = parts[0].split(" / ");
  124. tipo = funcao[1];
  125. if (funcao[1].equals("login") && funcao != null) {
  126. String username[] = parts[1].split(" / ");
  127. user = username[1].trim();
  128. String[] passwordArray = parts[2].split("/");
  129. password = passwordArray[1].trim();
  130.  
  131. newPessoa.setUsername(user);
  132. newPessoa.setPassword(password);
  133. }
  134. if (funcao[1].equals("logout") && funcao != null) {
  135. String username[] = parts[1].split(" / ");
  136. user = username[1].trim();
  137. }
  138. if (funcao[1].equals("sign up") && funcao != null) {
  139. // type / sign up ; item_count / 2 ; name / gui ; username / gui ; password /
  140. // ola ; mail / g@hot.com
  141. String[] infoArray = new String[4];
  142. String[] f;
  143. int count = 0;
  144. for (int i = 2; i < parts.length; i++) {
  145. f = parts[i].split(" / ");
  146. infoArray[count] = f[1].trim();
  147. count++;
  148. }
  149. newPessoa.setNome(infoArray[0]);
  150. newPessoa.setUsername(infoArray[1]);
  151. newPessoa.setPassword(infoArray[2]);
  152. newPessoa.setMail(infoArray[3]);
  153. }
  154. if (funcao[1].equals("add artist") && funcao != null) {
  155. // type / add artist ; item_count / 4 ; name / zeca ; username / zeca ; password
  156. // / ola ; mail / g@hot.com
  157. String[] infoArtist = new String[4];
  158. String[] f;
  159. int count = 0;
  160. for (int i = 2; i < parts.length; i++) {
  161. f = parts[i].split(" / ");
  162. infoArtist[count] = f[1].trim();
  163. count++;
  164. }
  165. newArtista.setNome(infoArtist[0]);
  166. newArtista.setUsername(infoArtist[1]);
  167. newArtista.setPassword(infoArtist[2]);
  168. newArtista.setMail(infoArtist[3]);
  169. Random rand = new Random();
  170. int n = rand.nextInt(1000) + 8;
  171. newArtista.setId(Integer.toString(n));
  172.  
  173. }
  174. if (funcao[1].equals("remove_artist") && funcao != null) {
  175. // type / remove_artist ; item_count / 2 ; name / gui ; username / gui ;
  176. // password / ola
  177. String[] infoArtist = new String[3];
  178. String[] f;
  179. int count = 0;
  180. for (int i = 2; i < parts.length; i++) {
  181. f = parts[i].split(" / ");
  182. infoArtist[count] = f[1].trim();
  183. count++;
  184. }
  185. newArtista.setNome(infoArtist[0]);
  186. newArtista.setUsername(infoArtist[1]);
  187. newArtista.setPassword(infoArtist[2]);
  188.  
  189. }
  190. if (funcao[1].equals("search_artist") && funcao != null) {
  191. // type / search_artist ; item_count / 1 ; name / zeca
  192. String[] infoArtist = new String[3];
  193. String[] f;
  194. int count = 0;
  195. for (int i = 2; i < parts.length; i++) {
  196. f = parts[i].split(" / ");
  197. infoArtist[count] = f[1].trim();
  198. count++;
  199. }
  200. newArtista.setNome(infoArtist[0]);
  201. }
  202. if (funcao[1].equals("add_music") && funcao != null) {
  203. // type / add_music ; item_count / 6 ; name / vampiros ; historia / nascida a
  204. // partir de blabla ; editora / avante ; letra / eles comem tudo eles comem tudo
  205. // ; artista / zeca ; periodo / 1980 ; musicos / zeca manel antonio
  206. String[] infoMusica = new String[6];
  207. String[] f;
  208. int count = 0;
  209. for (int i = 2; i < parts.length; i++) {
  210. f = parts[i].split(" / ");
  211. infoMusica[count] = f[1].trim();
  212. count++;
  213. }
  214. newMusica.setNome(infoMusica[0]);// atencao
  215. newMusica.setHistoria(infoMusica[1]);
  216. newMusica.setEditora(infoMusica[2]);
  217. newMusica.setLetra(infoMusica[3]);
  218. newMusica.setMusico(infoMusica[4]);
  219. newMusica.setGenero(infoMusica[5]);
  220. Random rand = new Random();
  221. int n2 = rand.nextInt(2000) + 1001;
  222. newMusica.setId(Integer.toString(n2));
  223. }
  224. if (funcao[1].equals("remove_music") && funcao != null) {
  225. // type / remove_music ; item_count / 1 ; name / vampiros
  226. String[] infoMusica = new String[1];
  227. String[] f;
  228. int count = 0;
  229. for (int i = 2; i < parts.length; i++) {
  230. f = parts[i].split(" / ");
  231. infoMusica[count] = f[1].trim();
  232. count++;
  233. }
  234. newMusica.setNome(infoMusica[0]);// atencao
  235. }
  236. if (funcao[1].equals("search_music") && funcao != null) {
  237. // type / search_music ; item_count / 1 ; name / vampiros
  238. String[] infoMusica = new String[1];
  239. String[] f;
  240. int count = 0;
  241. for (int i = 2; i < parts.length; i++) {
  242. f = parts[i].split(" / ");
  243. infoMusica[count] = f[1].trim();
  244. count++;
  245. }
  246. newMusica.setNome(infoMusica[0]);
  247. }
  248. if (funcao[1].equals("add_album") && funcao != null) {
  249. // type / add_album ; item_count / 4 ; name / maxim ; musicas / vampiros ; desc
  250. // / album fixe este ; artista / zeca
  251. // type / add_album ; item_count / 8 ; name / name ; descricao / descricao ;
  252. // genero / genero ; dia / dia ; mes / mes+" ; ano / "+ano+" ; hora / "+hora+" ;
  253. // minuto / "+minutos;
  254. String[] infoAlbum = new String[8];
  255. String[] f;
  256. int count = 0;
  257. for (int i = 2; i < parts.length; i++) {
  258. f = parts[i].split(" / ");
  259. infoAlbum[count] = f[1].trim();
  260. count++;
  261. }
  262. System.out.println();
  263. newAlbum.setNome(infoAlbum[0]);
  264. newAlbum.setDesc(infoAlbum[1]);
  265. newAlbum.setGenero(infoAlbum[2]);
  266. newAlbum.setDataL(inserirData(Integer.parseInt(infoAlbum[3]), Integer.parseInt(infoAlbum[4]),
  267. Integer.parseInt(infoAlbum[5]), Integer.parseInt(infoAlbum[6]),
  268. Integer.parseInt(infoAlbum[7])));
  269. Random rand = new Random();
  270. int n4 = rand.nextInt(4000) + 3001;
  271. newAlbum.setId(Integer.toString(n4));
  272. }
  273. if (funcao[1].equals("change_desc_album") && funcao != null) {
  274. // type / change_desc_album ; item_count / 2 ; name / maxim ; desc / album fixe
  275. // este
  276. String[] infoAlbum = new String[2];
  277. String[] f;
  278. int count = 0;
  279. for (int i = 2; i < parts.length; i++) {
  280. f = parts[i].split(" / ");
  281. infoAlbum[count] = f[1].trim();
  282. count++;
  283. }
  284.  
  285. newAlbum.setNome(infoAlbum[0]);
  286. newAlbum.setDesc(infoAlbum[1]);
  287. /*
  288. * newAlbum=pesquisaAlbumName(infoAlbum[0]); if(newAlbum!=null){
  289. * newAlbum.setDesc(infoAlbum[1]); }
  290. */
  291.  
  292. }
  293.  
  294. if (funcao[1].equals("search_album") && funcao != null) {
  295. // type / search_album ; item_count / 1 ; name / maxim
  296. String[] infoAlbum = new String[1];
  297. String[] f;
  298. int count = 0;
  299. for (int i = 2; i < parts.length; i++) {
  300. f = parts[i].split(" / ");
  301. infoAlbum[count] = f[1].trim();
  302. count++;
  303. }
  304. newAlbum.setNome(infoAlbum[0]);
  305. }
  306. if (funcao[1].equals("write_crit") && funcao != null) {
  307. // type / write_crit ; item_count / 3 ; name / maxim ; crit / este album e muito
  308. // fixe ; pont / 9
  309. String[] infoAlbum = new String[3];
  310. String[] f;
  311. int count = 0;
  312. for (int i = 2; i < parts.length; i++) {
  313. f = parts[i].split(" / ");
  314. infoAlbum[count] = f[1].trim();
  315. count++;
  316. }
  317. newAlbum.setNome(infoAlbum[0]);
  318. newAlbum.setId(procuraAlbumId(infoAlbum[0]));
  319. newCritica.setJust(infoAlbum[1]);
  320. newCritica.setPontuacao(Integer.parseInt(infoAlbum[2]));
  321. Random rand = new Random();
  322. int n3 = rand.nextInt(3000) + 2001;
  323. newCritica.setId(Integer.toString(n3));
  324.  
  325. }
  326. if (funcao[1].equals("download") && funcao != null) {
  327. // type / download ; item_count / 1 ; name / oioi
  328. String[] infoAlbum = new String[1];
  329. String[] f;
  330. int count = 0;
  331. for (int i = 2; i < parts.length; i++) {
  332. f = parts[i].split(" / ");
  333. infoAlbum[count] = f[1].trim();
  334. count++;
  335. }
  336. }
  337. if (funcao[1].equals("make_admin") && funcao != null) {
  338. // type / make_admin ; item_count / 1 ; username / pina
  339.  
  340. String[] f;
  341. f = parts[2].split(" / ");
  342. toAdmin = f[1].trim();
  343.  
  344. newPessoa.setUsername(toAdmin);
  345.  
  346. }
  347. if(funcao[1].equals("add_playlist") && funcao != null){
  348. //type / add_playlist ; item_count / 7 ; name / linda ; musica / x ; dia / dia ; mes / mes ; ano / ano ; hora / hora ; minuto / minuto
  349. String[] infoPlaylist = new String[7];
  350. String[] f;
  351. int count = 0;
  352. for (int i = 2; i < parts.length; i++) {
  353. f = parts[i].split(" / ");
  354. infoPlaylist[count] = f[1].trim();
  355. count++;
  356. }
  357. newPlaylist.setNome(infoPlaylist[0]);
  358. newPlaylist.setMusica(infoPlaylist[1]);
  359. newPlaylist.setDataC(inserirData(Integer.parseInt(infoPlaylist[2]), Integer.parseInt(infoPlaylist[3]),
  360. Integer.parseInt(infoPlaylist[4]), Integer.parseInt(infoPlaylist[5]),
  361. Integer.parseInt(infoPlaylist[6])));
  362. Random rand = new Random();
  363. int n4 = rand.nextInt(6000) + 5001;
  364. newPlaylist.setIdPlaylist(Integer.toString(n4));
  365. newPlaylist.setIdMusica(procuraMusicaId(infoPlaylist[1]));
  366.  
  367. }
  368. if(funcao[1].equals("remove_playlist") && funcao != null){
  369. //type / remove_playlist ; item_count / 1 ; name / nome
  370. String[] infoPlaylist = new String[1];
  371. String[] f;
  372. int count = 0;
  373. for (int i = 2; i < parts.length; i++) {
  374. f = parts[i].split(" / ");
  375. infoPlaylist[count] = f[1].trim();
  376. count++;
  377. }
  378. newPlaylist.setNome(infoPlaylist[0]);
  379. }
  380. if(funcao[1].equals("music_to_album") && funcao != null){
  381. //type / music_to_album ; item_count / 2 ; musica / musica ; album / nome
  382. String[] infoMix = new String[2];
  383. String[] f;
  384. int count = 0;
  385. for (int i = 2; i < parts.length; i++) {
  386. f = parts[i].split(" / ");
  387. infoMix[count] = f[1].trim();
  388. count++;
  389. }
  390. newMusica.setNome(infoMix[0]);
  391. newAlbum.setNome(infoMix[1]);
  392. }
  393. }
  394.  
  395. } catch (ArrayIndexOutOfBoundsException exception) {
  396. }
  397.  
  398. if (tipo.equals("sign up")) {
  399. if (procuraUtilizador(newPessoa) != 1) {
  400. insereUtilizador(newPessoa);
  401. sendMsg("Registado com sucesso");
  402. } else
  403. sendMsg("Nao foi possivel registar");
  404. // envia resposta
  405. // sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  406. }
  407.  
  408. // se for login tem de verificar aqui para atribuir a flag de loggado
  409. if (tipo.equals("login")) {
  410. if (procuraUtilizador(newPessoa) == 1) {// procura na base de dados o utilizador
  411. // pesquisaPessoas(user).setLog(true);
  412. logged.put(user, "logged");
  413. // envia resposta em conforme esta loggado
  414. sendMsg("type / status ; logged / on ; msg / Welcome to DropMusic");
  415. } else {
  416. sendMsg("Utilizador nao registado!");
  417. }
  418. }
  419.  
  420. if (logged.get(user) != null) {
  421. switch (tipo) {
  422. case "login":
  423. break;
  424. case "sign up":
  425. break;
  426. case "add artist":
  427. System.out.println(newPessoa.getUsername());
  428. System.out.println("Welcome to add artist");
  429. if(checkEditor(user) == 1) {
  430. if (procuraMusico(newArtista) != 1) {
  431. insereMusico(newArtista);
  432. sendMsg("Artista registado com sucesso");
  433. } else
  434. sendMsg("Nao foi possivel registar");
  435. }
  436. else{
  437. sendMsg("Nao tem privilegios");
  438. }
  439. // envia resposta
  440. // sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  441. break;
  442. case "remove_artist":
  443. System.out.println("Welcome to remove artist");
  444. newArtista.setId(procuraMusicoId(newArtista.getNome()));// ATENCAO
  445. if(checkEditor(user) == 1) {
  446. if (procuraMusico(newArtista) == 1) {
  447. removeMusico(newArtista);
  448. sendMsg("Artista " + newArtista.getUsername() + " removido com exito!");
  449. } else {
  450. sendMsg("Nao foi possivel remover");
  451. }
  452. }
  453. else{
  454. sendMsg("Nao tem privilegios");
  455. }
  456. break;
  457. case "add_music":
  458. System.out.println("Welcome to add music");
  459. if(checkEditor(user) == 1) {
  460. if (procuraMusica(newMusica) != 1) {
  461. insereMusica(newMusica);
  462. sendMsg("Musica adicionada com sucesso");
  463. } else {
  464. sendMsg("Nao foi possivel adicionar");
  465. }
  466. }
  467. else{
  468. sendMsg("Nao tem privilegios");
  469. }
  470. break;
  471. case "remove_music":
  472. if(checkEditor(user) == 1) {
  473. System.out.println("Welcome to remove music");
  474. if (/* removeMusica(newMusica) == 1 */procuraMusica(newMusica) == 1) {
  475. deleteMusica(newMusica);
  476. sendMsg("Musica removida com sucesso");
  477. } else {
  478. sendMsg("Nao foi possivel remover");
  479. }
  480. }
  481. else{
  482. sendMsg("Nao tem privilegios");
  483. }
  484. break;
  485. case "search_music":
  486. System.out.println("Welcome to search music");
  487. if (/* pesquisaMusicas(newMusica) != null */procuraMusica(newMusica) == 1) {
  488. sendMsg("A sua musica " + newMusica.getNome() + " esta no sistema");
  489. } else {
  490. sendMsg("A sua musica nao se encontra no sistema");
  491. }
  492. break;
  493. case "search_album":
  494. System.out.println("Welcome to search_album");
  495. if (/* pesquisaAlbum(newAlbum) == 1 */procuraAlbum(newAlbum) == 1) {
  496. sendMsg("Album " + newAlbum.getNome() + " encontrado");
  497. } else {
  498. sendMsg("Album nao esta no sistema");
  499. }
  500. break;
  501. case "write_crit":
  502. System.out.println("Welcome to write crit");
  503. if (procuraAlbum(newAlbum) == 1) {
  504. // writeCrit(newAlbum, newCritica);
  505. insereCritica(newCritica, newAlbum);
  506. sendMsg("Avaliacao ao album feita com sucesso");
  507. } else {
  508. sendMsg("Album nao se encontra no sistema");
  509. }
  510. break;
  511. case "add_album":
  512. System.out.println("Welcome to add album");
  513. if(checkEditor(user) == 1) {
  514. if (procuraAlbum(newAlbum) == 1) {
  515. sendMsg("Album ja se encontra no sistema");
  516. } else {
  517. if (procuraAlbum(newAlbum) == 0) {
  518. insereAlbum(newAlbum);
  519. sendMsg("Album adicionado");
  520. } else
  521. sendMsg("Impossivel adicionar album");
  522. }
  523. }else{
  524. sendMsg("Nao tem privilegios");
  525. }
  526. break;
  527. case "search_artist":
  528. System.out.println("Welcome to search artist");
  529. newArtista.setId(procuraMusicoId(newArtista.getNome()));
  530. if (procuraMusico(newArtista) == 1) {
  531. sendMsg("Artista " + newArtista.getNome() + " esta no sistema");
  532. } else
  533. sendMsg("Artista nao esta no sistema");
  534. break;
  535. case "download":
  536.  
  537. break;
  538. case "make_admin":
  539. System.out.println("welcome to make adminss");
  540. newPessoa.setPassword(procuraPass(newPessoa));
  541. if (procuraUtilizador(newPessoa) == 1) {
  542. makeAdmin(newPessoa);
  543. sendMsg("User " + toAdmin + " tornou-se admin");
  544. } else {
  545. sendMsg("Impossivel tornar administrador");
  546. }
  547. // tornaAdmin(newPessoa);
  548. break;
  549. case "change_desc_album":
  550. if (procuraAlbum(newAlbum) == 1) {
  551. updateDescricao(newAlbum);
  552. System.out.println(newAlbum.getDescricao());
  553. sendMsg("Descriçao alterada com sucesso");
  554. } else
  555. sendMsg("não foi possivel alterar");
  556. break;
  557. case "add_playlist":
  558. inserePlaylist(newPlaylist);
  559. sendMsg("Playlist adicionada");
  560. break;
  561. case "remove_playlist":
  562. deletePlaylist(newPlaylist);
  563. sendMsg("Playlist eliminada");
  564. break;
  565. case "music_to_album":
  566. if(checkEditor(user) == 1) {
  567. if (procuraMusica(newMusica) == 1) {
  568. newAlbum.setId(procuraAlbumId(newAlbum.getNome()));
  569. newMusica.setId(procuraMusicaId(newMusica.getNome()));
  570. insereMusicaToAlbum(newMusica, newAlbum);
  571. sendMsg("Musica associada");
  572. } else {
  573. sendMsg("Musica nao encontrada");
  574. }
  575. }else{
  576. sendMsg("Nao tem privilegios");
  577. }
  578. break;
  579. case "logout":
  580. logged.remove(user);
  581. sendMsg("logout feito");
  582. }
  583. }
  584. }
  585.  
  586. public static void insereUtilizador(Pessoa pessoa) throws SQLException {
  587. PreparedStatement preparedStatement;
  588. String cmd;
  589. sp = conn.setSavepoint();
  590. cmd = "INSERT INTO UTILIZADOR" + "(USERNAME, PASSWORD, EMAIL,EDITOR,MUSICAID) VALUES" + "(?,?,?,?,?)";
  591. try {
  592. preparedStatement = conn.prepareStatement(cmd);
  593. preparedStatement.setString(1, pessoa.getUsername());
  594. preparedStatement.setString(2, pessoa.getPassword());
  595. preparedStatement.setString(3, pessoa.getMail());
  596. preparedStatement.setInt(4, 0);
  597. preparedStatement.setString(5, "");
  598. preparedStatement.executeUpdate();
  599. conn.commit();
  600. if (preparedStatement != null) {
  601. preparedStatement.close();
  602. }
  603. } catch (SQLException e) {
  604. conn.rollback(sp);
  605. e.printStackTrace();
  606. }
  607. }
  608.  
  609. public static void insereMusico(Artista artista) throws SQLException {
  610. PreparedStatement preparedStatement;
  611. String cmd;
  612. sp = conn.setSavepoint();
  613. cmd = "INSERT INTO MUSICO" + "(IDMUSICO, NOME, EMAIL,MUSICAID,AUTORID) VALUES" + "(?,?,?,?,?)";
  614. try {
  615. preparedStatement = conn.prepareStatement(cmd);
  616. preparedStatement.setString(1, artista.getId());
  617. preparedStatement.setString(2, artista.getNome());
  618. preparedStatement.setString(3, artista.getMail());
  619. preparedStatement.setString(4, "");
  620. preparedStatement.setString(5, "");
  621. preparedStatement.executeUpdate();
  622. conn.commit();
  623. if (preparedStatement != null) {
  624. preparedStatement.close();
  625. }
  626. } catch (SQLException e) {
  627. conn.rollback(sp);
  628. e.printStackTrace();
  629. }
  630. }
  631.  
  632. public static int procuraMusico(Artista artista) throws SQLException {
  633. String ins = "SELECT IDMUSICO FROM MUSICO WHERE IDMUSICO LIKE ?";
  634. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  635. preparedStatement.setString(1, artista.getId());
  636. int rs = preparedStatement.executeUpdate();
  637. if (rs >= 1)
  638. return 1;
  639. else
  640. return 0;
  641. }
  642.  
  643. public static void removeMusico(Artista artista) throws SQLException {
  644. sp = conn.setSavepoint();
  645. String ins = "DELETE FROM MUSICO WHERE IDMUSICO LIKE ?";
  646. try {
  647. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  648. preparedStatement.setString(1, artista.getId());
  649. preparedStatement.executeUpdate();
  650. conn.commit();
  651. if (preparedStatement != null) {
  652. preparedStatement.close();
  653. }
  654.  
  655. } catch (SQLException e) {
  656. conn.rollback(sp);
  657. e.printStackTrace();
  658. }
  659. }
  660.  
  661. public static int procuraUtilizador(Pessoa pessoa) throws SQLException {
  662. String ins = "SELECT USERNAME FROM UTILIZADOR WHERE USERNAME LIKE ? AND PASSWORD LIKE ?";
  663. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  664. System.out.println("sou o " + pessoa.getUsername() + " " + pessoa.getPassword());
  665. preparedStatement.setString(1, pessoa.getUsername());
  666. preparedStatement.setString(2, pessoa.getPassword());
  667. int rs = preparedStatement.executeUpdate();// numero de vezes que o utilizador foi encontrado
  668. if (rs >= 1) {
  669. return 1;
  670. } else {
  671. return 0;
  672.  
  673. }
  674. }
  675.  
  676. public static int checkEditor(String username) throws SQLException {
  677. String ins = "SELECT USERNAME FROM UTILIZADOR WHERE USERNAME LIKE ? AND EDITOR = ?";
  678. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  679. preparedStatement.setString(1, username);
  680. preparedStatement.setInt(2, 1);
  681. int rs = preparedStatement.executeUpdate();
  682. if (rs >= 1)
  683. return 1;
  684. else
  685. return 0;
  686. }
  687.  
  688. public static void insereMusica(Musica musica) throws SQLException {
  689. PreparedStatement preparedStatement;
  690. String ins;
  691. String historia = musica.getHistoria();
  692. String letra = musica.getLetra();
  693. String nomeEd = musica.getEditora();
  694. String autorid = procuraAutorId(musica.getMusico());
  695. String musicaid = musica.getId();
  696.  
  697. sp = conn.setSavepoint();
  698. ins = "INSERT INTO MUSICA"
  699. + "(ALBUMID, NOME, IDMUSICA,GENERO,HISTORIA,LETRA,NOMEEDITORA,AUTORID,CONCERTOS) VALUES"
  700. + "(?,?,?,?,?,?,?,?,?)";
  701. try {
  702. preparedStatement = conn.prepareStatement(ins);
  703. preparedStatement.setString(1, "");
  704. preparedStatement.setString(2, musica.getNome());
  705. preparedStatement.setString(3, musicaid);
  706. preparedStatement.setString(4, musica.getGenero());// atencao
  707. preparedStatement.setString(5, historia);
  708. preparedStatement.setString(6, letra);
  709. preparedStatement.setString(7, nomeEd);
  710. preparedStatement.setString(8, autorid);
  711. preparedStatement.setString(9, "");
  712. preparedStatement.executeUpdate();
  713. conn.commit();
  714. if (preparedStatement != null) {
  715. preparedStatement.close();
  716. }
  717. } catch (SQLException e) {
  718. conn.rollback(sp);
  719. e.printStackTrace();
  720. }
  721. }
  722.  
  723. public static void insereMusicaToAlbum(Musica musica, Album album) throws SQLException{
  724. PreparedStatement preparedStatement;
  725. String cmd;
  726. sp = conn.setSavepoint();
  727.  
  728. cmd = "UPDATE MUSICA SET ALBUMID = ? WHERE NOME LIKE ?";
  729.  
  730. try {
  731. preparedStatement = conn.prepareStatement(cmd);
  732. preparedStatement.setString(1, album.getId());
  733. preparedStatement.setString(2, musica.getNome());
  734. preparedStatement.executeUpdate();
  735. conn.commit();
  736. if (preparedStatement != null) {
  737. preparedStatement.close();
  738. }
  739. } catch (SQLException e) {
  740. conn.rollback(sp);
  741. e.printStackTrace();
  742. }
  743. }
  744.  
  745. public static void deleteMusica(Musica musica) throws SQLException {
  746. sp = conn.setSavepoint();
  747. String musicaid = procuraMusicaId(musica.getNome());
  748. System.out.println(musicaid);
  749.  
  750. String ins = "DELETE FROM MUSICO WHERE MUSICAID LIKE ?";
  751. try {
  752. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  753. preparedStatement.setString(1, musicaid);
  754. preparedStatement.executeUpdate();
  755. conn.commit();
  756. if (preparedStatement != null) {
  757. preparedStatement.close();
  758. }
  759.  
  760. } catch (SQLException e) {
  761. conn.rollback(sp);
  762. e.printStackTrace();
  763. }
  764.  
  765. ins = "DELETE FROM MUSICA WHERE NOME LIKE ?";
  766. try {
  767. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  768. preparedStatement.setString(1, musica.getNome());
  769. preparedStatement.executeUpdate();
  770. conn.commit();
  771. if (preparedStatement != null) {
  772. preparedStatement.close();
  773. }
  774.  
  775. } catch (SQLException e) {
  776. conn.rollback(sp);
  777. e.printStackTrace();
  778. }
  779.  
  780. }
  781.  
  782. public static int procuraMusica(Musica musica) throws SQLException {
  783. String ins = "SELECT NOME FROM MUSICA WHERE NOME LIKE ?";
  784. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  785. preparedStatement.setString(1, musica.getNome());
  786. int rs = preparedStatement.executeUpdate();
  787. if (rs >= 1)
  788. return 1;
  789. else
  790. return 0;
  791. }
  792.  
  793. public static void insereAlbum(Album album) throws SQLException {
  794. PreparedStatement preparedStatement;
  795. String ins;
  796. sp = conn.setSavepoint();
  797. ins = "INSERT INTO ALBUM" + "(NOME, IDCRITICA, AVAL,IDALBUM,DESCRICAO,GENEROS,DATAL) VALUES"
  798. + "(?,?,?,?,?,?,?)";
  799. try {
  800. preparedStatement = conn.prepareStatement(ins);
  801. preparedStatement.setString(1, album.getNome());
  802. preparedStatement.setString(2, "");
  803. preparedStatement.setInt(3, 0);
  804. preparedStatement.setString(4, album.getId());
  805. preparedStatement.setString(5, album.getDesc());
  806. preparedStatement.setString(6, album.getGenero());
  807. preparedStatement.setTimestamp(7, album.getDataL());
  808. preparedStatement.executeUpdate();
  809. conn.commit();
  810. if (preparedStatement != null) {
  811. preparedStatement.close();
  812. }
  813. } catch (SQLException e) {
  814. conn.rollback(sp);
  815. e.printStackTrace();
  816. }
  817. }
  818.  
  819. public static void inserePlaylist(Playlist playlist) throws SQLException{
  820. PreparedStatement preparedStatement;
  821. String ins;
  822. sp = conn.setSavepoint();
  823. ins = "INSERT INTO PLAYLIST" + "(UTILIZADORNOME, NOME, DATACRIA,IDPLAYLIST,IDMUSICA) VALUES"
  824. + "(?,?,?,?,?)";
  825. try {
  826. preparedStatement = conn.prepareStatement(ins);
  827. preparedStatement.setString(1, user);
  828. preparedStatement.setString(2, playlist.getNome());
  829. preparedStatement.setTimestamp(3, playlist.getDataC());
  830. preparedStatement.setString(4,playlist.getIdPlaylist());
  831. preparedStatement.setString(5, playlist.getIdMusica());
  832. preparedStatement.executeUpdate();
  833. conn.commit();
  834. if (preparedStatement != null) {
  835. preparedStatement.close();
  836. }
  837. } catch (SQLException e) {
  838. conn.rollback(sp);
  839. e.printStackTrace();
  840. }
  841. }
  842.  
  843. public static void deletePlaylist(Playlist playlist) throws SQLException{
  844. sp = conn.setSavepoint();
  845.  
  846. String ins = "DELETE FROM PLAYLIST WHERE NOME LIKE ?";
  847. try {
  848. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  849. preparedStatement.setString(1, playlist.getNome());
  850. preparedStatement.executeUpdate();
  851. conn.commit();
  852. if (preparedStatement != null) {
  853. preparedStatement.close();
  854. }
  855.  
  856. } catch (SQLException e) {
  857. conn.rollback(sp);
  858. e.printStackTrace();
  859. }
  860. }
  861.  
  862. public static int procuraAlbum(Album album) throws SQLException {
  863. String ins = "SELECT NOME FROM ALBUM WHERE NOME LIKE ?";
  864. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  865. preparedStatement.setString(1, album.getNome());
  866. int rs = preparedStatement.executeUpdate();
  867. if (rs >= 1)
  868. return 1;
  869. else
  870. return 0;
  871. }
  872.  
  873. public static String procuraAlbumId(String nome) throws SQLException {
  874. ResultSet rs;
  875. String id = "";
  876. String ins = "SELECT IDALBUM FROM ALBUM WHERE NOME LIKE ?";
  877. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  878. preparedStatement.setString(1, nome);
  879. rs = preparedStatement.executeQuery();
  880. while (rs.next()) {
  881. id = rs.getString("IDALBUM");
  882. }
  883. return id;
  884. }
  885.  
  886. public static String procuraMusicaId(String nome) throws SQLException {
  887. ResultSet rs;
  888. String id = "";
  889. String ins = "SELECT IDMUSICA FROM MUSICA WHERE NOME LIKE ?";
  890. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  891. preparedStatement.setString(1, nome);
  892. rs = preparedStatement.executeQuery();
  893. while (rs.next()) {
  894. id = rs.getString("IDMUSICA");
  895. }
  896. return id;
  897. }
  898.  
  899. public static String procuraAutorId(String nome) throws SQLException {
  900. ResultSet rs;
  901. String id = "";
  902. String ins = "SELECT AUTORID FROM MUSICO WHERE NOME LIKE ?";
  903. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  904. preparedStatement.setString(1, nome);
  905. rs = preparedStatement.executeQuery();
  906. while (rs.next()) {
  907. id = rs.getString("AUTORID");
  908. }
  909. return id;
  910. }
  911.  
  912. public static String procuraMusicoId(String nome) throws SQLException {
  913. ResultSet rs;
  914. String id = "";
  915. String ins = "SELECT IDMUSICO FROM MUSICO WHERE NOME LIKE ?";
  916. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  917. preparedStatement.setString(1, nome);
  918. rs = preparedStatement.executeQuery();
  919. while (rs.next()) {
  920. id = rs.getString("IDMUSICO");
  921. }
  922. return id;
  923. }
  924.  
  925. public static String procuraPass(Pessoa pessoa) throws SQLException{
  926. ResultSet rs;
  927. String id = "";
  928. String ins = "SELECT PASSWORD FROM UTILIZADOR WHERE USERNAME LIKE ?";
  929. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  930. preparedStatement.setString(1, pessoa.getUsername());
  931. rs = preparedStatement.executeQuery();
  932. while (rs.next()) {
  933. id = rs.getString("PASSWORD");
  934. }
  935. return id;
  936. }
  937.  
  938. public static String procuraMusicoEmail(String nome) throws SQLException {
  939. ResultSet rs;
  940. String id = "";
  941. String ins = "SELECT EMAIL FROM MUSICO WHERE NOME LIKE ?";
  942. PreparedStatement preparedStatement = conn.prepareStatement(ins);
  943. preparedStatement.setString(1, nome);
  944. rs = preparedStatement.executeQuery();
  945. while (rs.next()) {
  946. id = rs.getString("EMAIL");
  947. }
  948. return id;
  949. }
  950.  
  951. public static void insereCritica(Critica critica, Album album) throws SQLException {
  952. PreparedStatement preparedStatement;
  953. String cmd;
  954. sp = conn.setSavepoint();
  955. cmd = "INSERT INTO CRITICA" + "(JUSTIFICACAO, PONT, IDCRITICA,UTILIZADORNOME,ALBUMID) VALUES" + "(?,?,?,?,?)";
  956. try {
  957. preparedStatement = conn.prepareStatement(cmd);
  958. preparedStatement.setString(1, critica.getJust());
  959. preparedStatement.setInt(2, critica.getPontuacao());
  960. preparedStatement.setString(3, critica.getId());
  961. preparedStatement.setString(4, user);// atencao
  962. preparedStatement.setString(5, album.getId());
  963. preparedStatement.executeUpdate();
  964. conn.commit();
  965. if (preparedStatement != null) {
  966. preparedStatement.close();
  967. }
  968. } catch (SQLException e) {
  969. conn.rollback(sp);
  970. e.printStackTrace();
  971. }
  972.  
  973. updateCriticaId(critica, album);
  974. }
  975.  
  976. public static void updateCriticaId(Critica critica, Album album) throws SQLException {
  977. PreparedStatement preparedStatement;
  978. String cmd;
  979. sp = conn.setSavepoint();
  980.  
  981. cmd = "UPDATE ALBUM SET IDCRITICA = ? WHERE NOME LIKE ?";
  982.  
  983. try {
  984. preparedStatement = conn.prepareStatement(cmd);
  985. preparedStatement.setString(1, critica.getId());
  986. preparedStatement.setString(2, album.getNome());
  987. preparedStatement.executeUpdate();
  988. conn.commit();
  989. if (preparedStatement != null) {
  990. preparedStatement.close();
  991. }
  992. } catch (SQLException e) {
  993. conn.rollback(sp);
  994. e.printStackTrace();
  995. }
  996. }
  997.  
  998. public static void updateDescricao(Album album) throws SQLException {
  999. PreparedStatement preparedStatement;
  1000. String cmd;
  1001. sp = conn.setSavepoint();
  1002.  
  1003. cmd = "UPDATE ALBUM SET DESCRICAO = ? WHERE NOME LIKE ?";
  1004.  
  1005. try {
  1006. preparedStatement = conn.prepareStatement(cmd);
  1007. preparedStatement.setString(1, album.getDesc());
  1008. preparedStatement.setString(2, album.getNome());
  1009. preparedStatement.executeUpdate();
  1010. conn.commit();
  1011. if (preparedStatement != null) {
  1012. preparedStatement.close();
  1013. }
  1014. } catch (SQLException e) {
  1015. conn.rollback(sp);
  1016. e.printStackTrace();
  1017. }
  1018. }
  1019.  
  1020. public static void makeAdmin(Pessoa pessoa) throws SQLException {
  1021. PreparedStatement preparedStatement;
  1022. String cmd;
  1023. sp = conn.setSavepoint();
  1024.  
  1025. cmd = "UPDATE UTILIZADOR SET EDITOR = ? WHERE USERNAME LIKE ?";
  1026.  
  1027. try {
  1028. preparedStatement = conn.prepareStatement(cmd);
  1029. preparedStatement.setInt(1, 1);
  1030. preparedStatement.setString(2, pessoa.getUsername());
  1031. preparedStatement.executeUpdate();
  1032. conn.commit();
  1033. if (preparedStatement != null) {
  1034. preparedStatement.close();
  1035. }
  1036. } catch (SQLException e) {
  1037. conn.rollback(sp);
  1038. e.printStackTrace();
  1039. }
  1040. }
  1041.  
  1042. public static void main(String[] args)
  1043. throws IOException, InterruptedException, ClassNotFoundException, SQLException {
  1044.  
  1045. // serve para tratar o shutdown, pois assim que aconteca as listas sao guardadas
  1046. Runtime.getRuntime().addShutdownHook(new Thread() {
  1047. @Override
  1048. public void run() {
  1049. try {
  1050. conn.commit();
  1051. } catch (SQLException e) {
  1052. e.printStackTrace();
  1053. }
  1054. }
  1055. });
  1056.  
  1057. try {
  1058. System.out.println("Connecting to database...");
  1059. Class.forName("oracle.jdbc.driver.OracleDriver");
  1060.  
  1061. } catch (ClassNotFoundException e) {
  1062. e.printStackTrace();
  1063. }
  1064.  
  1065. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  1066. conn.setAutoCommit(false);
  1067. porto = config.getHostMulti();
  1068.  
  1069. System.out.println("Server a escuta no porto " + porto);
  1070.  
  1071. // thread que recebe mensagens do rmi; liga no porto 3000 (pedido ao utilizador)
  1072. // que e onde esta ligado o socket do rmi que manda mensagens
  1073. new Thread() { // THREAD QUE TRATA DO MULTICAST (recebe mensagens)
  1074. public void run() {
  1075. MulticastSocket s = null;
  1076. try {
  1077. s = new MulticastSocket(porto);// 3000
  1078. s.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
  1079. } catch (IOException e) {
  1080. e.printStackTrace();
  1081. }
  1082.  
  1083. byte[] buf = new byte[1000];
  1084. DatagramPacket recv = new DatagramPacket(buf, buf.length);
  1085.  
  1086. try {
  1087. while (true) {
  1088. s.receive(recv);
  1089. String msgNew = new String(recv.getData(), 0, recv.getLength());
  1090. escolheOpcao(msgNew);
  1091.  
  1092. }
  1093. } catch (IOException | SQLException e) {
  1094. e.printStackTrace();
  1095. }
  1096.  
  1097. }
  1098. }.start();
  1099.  
  1100. // recebe coisas do tcp client
  1101. receiveTCP();
  1102. }
  1103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement