Advertisement
Guest User

Multi

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