Advertisement
Guest User

Untitled

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