Advertisement
Guest User

Untitled

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