Advertisement
Guest User

Untitled

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