Advertisement
Guest User

Untitled

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