Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.ArrayList;
- import java.util.Scanner;
- import java.util.HashMap;
- import java.util.Map;
- import java.sql.*;
- import java.util.Random;
- public class MulticastServer extends Thread {
- private static int porto;
- private static int nRegistos; // este valor ha de ser carregado de um ficheiro, conta o numero de registos
- public static Map logged = new HashMap<String,String>();
- private static String user;
- public static Config config=new Config("configServer.cfg");
- private static int portoRMI = config.getHostRmi();
- private static String MULTICAST_ADDRESS = config.getMultiAdd();
- private static FileOutputStream f;
- private static FileInputStream fi;
- private static ObjectOutputStream o;
- private static ObjectInputStream oi;
- private static final long serialVersionUID = 1L;
- static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
- static final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
- static final String USER = "bd";
- static final String PASS = "bd";
- static Connection conn = null;
- static Savepoint sp = null;
- //pede os dados de uma data
- private static java.sql.Timestamp inserirData( int ano,int mes, int dia, int minutos, int hora) {
- int segundos=0, nanos=0;
- System.out.println(ano + " " + mes + " " + dia + " " + hora + " " + minutos + " ");
- java.sql.Timestamp date = new java.sql.Timestamp(ano-1899, mes-12, dia-31, hora, minutos,segundos, nanos);
- System.out.println(date);
- return date;
- }
- /**
- * Método para receber mensagens do cliente via TCP
- */
- public static void receiveTCP(){
- int numero=0;
- try{
- int serverPort = 6000;
- System.out.println("A Escuta no Porto 6000");
- ServerSocket listenSocket = new ServerSocket(serverPort);
- // System.out.println("LISTEN SOCKET="+listenSocket);
- while(true) {
- Socket clientSocket = listenSocket.accept(); // BLOQUEANTE
- System.out.println("CLIENT_SOCKET (created at accept())="+clientSocket);
- numero ++;
- new ClientThread(clientSocket);//criar nova classe chamada clientthread que recebe os pedidos que chegam do cliente
- }
- }catch(IOException e)
- {System.out.println("Listen:" + e.getMessage());}
- }
- //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
- /**
- * Método para enivar mensagens para o server RMI
- * @param texto Texto a enviar
- * @throws SocketException
- */
- public static void sendMsg(String texto) throws SocketException {
- new Thread(){
- public void run(){
- MulticastSocket aSocket = null;//atencao
- try {
- aSocket = new MulticastSocket();
- byte [] m = texto.getBytes();
- InetAddress aHost = InetAddress.getByName(MULTICAST_ADDRESS);
- //int serverPort = 4000;
- DatagramPacket request = new DatagramPacket(m,m.length,aHost,portoRMI);
- aSocket.send(request);
- }catch (SocketException e){System.out.println("Socket: " + e.getMessage());
- }catch (IOException e){System.out.println("IO: " + e.getMessage());
- }finally {if(aSocket != null) aSocket.close();}
- }
- }.start();
- }
- //funcao que trata o comando recebido do cliente
- /**
- * Método para tratar os pedidos que chegam do cliente via server RMI
- * @param comando Comando do cliente
- * @throws IOException
- */
- public static void escolheOpcao(String comando) throws IOException, SQLException {
- //String user = new String();
- String password = new String();
- String tipo = new String();
- Pessoa newPessoa = new Pessoa();
- Artista newArtista=new Artista();
- Musica newMusica = new Musica();
- Album newAlbum = new Album();
- Critica newCritica = new Critica();
- String toAdmin = new String();
- try {
- if (comando != null && comando != "\n" && comando != "") {
- String parts[] = comando.split(" ; ");
- String funcao[] = parts[0].split(" / ");
- tipo = funcao[1];
- if (funcao[1].equals("login") && funcao != null) {
- String username[] = parts[1].split(" / ");
- user = username[1].trim();
- String[] passwordArray = parts[2].split("/");
- password = passwordArray[1].trim();
- newPessoa.setUsername(user);
- newPessoa.setPassword(password);
- }
- if (funcao[1].equals("logout") && funcao != null) {
- String username[] = parts[1].split(" / ");
- user = username[1].trim();
- }
- if (funcao[1].equals("sign up") && funcao != null) {
- //type / sign up ; item_count / 2 ; name / gui ; username / gui ; password / ola ; mail / g@hot.com
- String[] infoArray = new String[4];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoArray[count] =f[1].trim();
- count++;
- }
- newPessoa.setNome(infoArray[0]);
- newPessoa.setUsername(infoArray[1]);
- newPessoa.setPassword(infoArray[2]);
- newPessoa.setMail(infoArray[3]);
- }
- if (funcao[1].equals("add artist") && funcao != null) {
- //type / add artist ; item_count / 4 ; name / zeca ; username / zeca ; password / ola ; mail / g@hot.com
- String[] infoArtist = new String[4];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoArtist[count] =f[1].trim();
- count++;
- }
- newArtista.setNome(infoArtist[0]);
- newArtista.setUsername(infoArtist[1]);
- newArtista.setPassword(infoArtist[2]);
- newArtista.setMail(infoArtist[3]);
- Random rand = new Random();
- int n = rand.nextInt(1000) + 8;
- newArtista.setId(Integer.toString(n));
- }
- if (funcao[1].equals("remove_artist") && funcao != null) {
- //type / remove_artist ; item_count / 2 ; name / gui ; username / gui ; password / ola
- String[] infoArtist = new String[3];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoArtist[count] =f[1].trim();
- count++;
- }
- newArtista.setNome(infoArtist[0]);
- newArtista.setUsername(infoArtist[1]);
- newArtista.setPassword(infoArtist[2]);
- }
- if(funcao[1].equals("search_artist") && funcao != null){
- //type / search_artist ; item_count / 1 ; name / zeca
- String[] infoArtist = new String[3];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoArtist[count] =f[1].trim();
- count++;
- }
- newArtista.setNome(infoArtist[0]);
- }
- if (funcao[1].equals("add_music") && funcao != null){
- //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
- String[] infoMusica = new String[6];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoMusica[count] =f[1].trim();
- count++;
- }
- newMusica.setNome(infoMusica[0]);//atencao
- newMusica.setHistoria(infoMusica[1]);
- newMusica.setEditora(infoMusica[2]);
- newMusica.setLetra(infoMusica[3]);
- newMusica.setMusico(infoMusica[4]);
- newMusica.setGenero(infoMusica[5]);
- Random rand = new Random();
- int n2 = rand.nextInt(2000) + 1001;
- newMusica.setId(Integer.toString(n2));
- }
- if(funcao[1].equals("remove_music") && funcao != null){
- //type / remove_music ; item_count / 1 ; name / vampiros
- String[] infoMusica = new String[1];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoMusica[count] =f[1].trim();
- count++;
- }
- newMusica.setNome(infoMusica[0]);//atencao
- }
- if(funcao[1].equals("search_music") && funcao != null){
- //type / search_music ; item_count / 1 ; name / vampiros
- String[] infoMusica = new String[1];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoMusica[count] =f[1].trim();
- count++;
- }
- newMusica.setNome(infoMusica[0]);
- }
- if(funcao[1].equals("add_album") && funcao != null){
- //type / add_album ; item_count / 4 ; name / maxim ; musicas / vampiros ; desc / album fixe este ; artista / zeca
- //type / add_album ; item_count / 8 ; name / name ; descricao / descricao ; genero / genero ; dia / dia ; mes / mes+" ; ano / "+ano+" ; hora / "+hora+" ; minuto / "+minutos;
- String[] infoAlbum = new String[8];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoAlbum[count] =f[1].trim();
- count++;
- }
- System.out.println();
- newAlbum.setNome(infoAlbum[0]);
- newAlbum.setDesc(infoAlbum[1]);
- newAlbum.setGenero(infoAlbum[2]);
- newAlbum.setDataL(inserirData(Integer.parseInt(infoAlbum[3]),Integer.parseInt(infoAlbum[4]),Integer.parseInt(infoAlbum[5]),Integer.parseInt(infoAlbum[6]),Integer.parseInt(infoAlbum[7])));
- Random rand = new Random();
- int n4 = rand.nextInt(4000) + 3001;
- newAlbum.setId(Integer.toString(n4));
- }
- if(funcao[1].equals("change_desc_album") && funcao != null){
- //type / change_desc_album ; item_count / 2 ; name / maxim ; desc / album fixe este
- String[] infoAlbum = new String[2];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoAlbum[count] =f[1].trim();
- count++;
- }
- newAlbum.setNome(infoAlbum[0]);
- newAlbum.setDesc(infoAlbum[1]);
- /*newAlbum=pesquisaAlbumName(infoAlbum[0]);
- if(newAlbum!=null){
- newAlbum.setDesc(infoAlbum[1]);
- }*/
- }
- if(funcao[1].equals("search_album") && funcao != null){
- //type / search_album ; item_count / 1 ; name / maxim
- String[] infoAlbum = new String[1];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoAlbum[count] =f[1].trim();
- count++;
- }
- newAlbum.setNome(infoAlbum[0]);
- }
- if(funcao[1].equals("write_crit") && funcao != null){
- //type / write_crit ; item_count / 3 ; name / maxim ; crit / este album e muito fixe ; pont / 9
- String[] infoAlbum = new String[3];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoAlbum[count] =f[1].trim();
- count++;
- }
- newAlbum.setNome(infoAlbum[0]);
- newAlbum.setId(procuraAlbumId(infoAlbum[0]));
- newCritica.setJust(infoAlbum[1]);
- newCritica.setPontuacao(Integer.parseInt(infoAlbum[2]));
- Random rand = new Random();
- int n3 = rand.nextInt(3000) + 2001;
- newCritica.setId(Integer.toString(n3));
- }
- if(funcao[1].equals("download") && funcao != null){
- //type / download ; item_count / 1 ; name / oioi
- String[] infoAlbum = new String[1];
- String[] f;
- int count=0;
- for (int i=2; i<parts.length; i++){
- f=parts[i].split(" / ");
- infoAlbum[count] =f[1].trim();
- count++;
- }
- }
- if (funcao[1].equals("make_admin") && funcao != null) {
- //type / make_admin ; item_count / 1 ; username / pina
- String[] f;
- f = parts[2].split(" / ");
- toAdmin = f[1].trim();
- }
- }
- }catch (ArrayIndexOutOfBoundsException exception){}
- if(tipo.equals("sign up")) {
- if (procuraUtilizador(newPessoa) != 1) {
- insereUtilizador(newPessoa);
- sendMsg("Registado com sucesso");
- } else
- sendMsg("Nao foi possivel registar");
- //envia resposta
- //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
- }
- //se for login tem de verificar aqui para atribuir a flag de loggado
- if(tipo.equals("login")){
- if (procuraUtilizador(newPessoa)==1){//procura na base de dados o utilizador
- //pesquisaPessoas(user).setLog(true);
- logged.put(user, "logged");
- //envia resposta em conforme esta loggado
- sendMsg("type / status ; logged / on ; msg / Welcome to DropMusic");
- }
- else{
- sendMsg("Utilizador nao registado!");
- }
- }
- if(logged.get(user) != null) {
- switch (tipo) {
- case "login":
- break;
- case "sign up":
- break;
- case "add artist":
- System.out.println(newPessoa.getUsername());
- System.out.println("Welcome to add artist");
- if (/*addArtist(newArtista) == true*/procuraMusico(newArtista) != 1) {
- insereMusico(newArtista);
- sendMsg("Artista registado com sucesso");
- } else
- sendMsg("Nao foi possivel registar");
- //envia resposta
- //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
- break;
- case "remove_artist":
- System.out.println("Welcome to remove artist");
- newArtista.setId(procuraMusicoId(newArtista.getNome()));//ATENCAO
- if (procuraMusico(newArtista) == 1) {
- removeMusico(newArtista);
- sendMsg("Artista " + newArtista.getUsername() + " removido com exito!");
- } else {
- sendMsg("Nao foi possivel remover");
- }
- break;
- case "add_music":
- System.out.println("Welcome to add music");
- if (procuraMusica(newMusica) != 1) {
- insereMusica(newMusica);
- sendMsg("Musica adicionada com sucesso");
- } else {
- sendMsg("Nao foi possivel adicionar");
- }
- break;
- case "remove_music":
- System.out.println("Welcome to remove music");
- if (/*removeMusica(newMusica) == 1*/procuraMusica(newMusica) == 1) {
- deleteMusica(newMusica);
- sendMsg("Musica removida com sucesso");
- } else {
- sendMsg("Nao foi possivel remover");
- }
- break;
- case "search_music":
- System.out.println("Welcome to search music");
- if (/*pesquisaMusicas(newMusica) != null*/procuraMusica(newMusica) == 1) {
- sendMsg("A sua musica " + newMusica.getNome() + " esta no sistema");
- } else {
- sendMsg("A sua musica nao se encontra no sistema");
- }
- break;
- case "search_album":
- System.out.println("Welcome to search_album");
- if (/*pesquisaAlbum(newAlbum) == 1*/procuraAlbum(newAlbum) == 1) {
- sendMsg("Album " + newAlbum.getNome()+" encontrado");
- } else {
- sendMsg("Album nao esta no sistema");
- }
- break;
- case "write_crit":
- System.out.println("Welcome to write crit");
- if (procuraAlbum(newAlbum) == 1) {
- //writeCrit(newAlbum, newCritica);
- insereCritica(newCritica,newAlbum);
- sendMsg("Avaliacao ao album feita com sucesso");
- } else {
- sendMsg("Album nao se encontra no sistema");
- }
- break;
- case "add_album":
- System.out.println("Welcome to add album");
- if (procuraAlbum(newAlbum) == 1) {
- sendMsg("Album ja se encontra no sistema");
- } else {
- if (procuraAlbum(newAlbum) == 0) {
- insereAlbum(newAlbum);
- sendMsg("Album adicionado");
- }
- else
- sendMsg("Impossivel adicionar album");
- }
- break;
- case "search_artist":
- System.out.println("Welcome to search artist");
- newArtista.setId(procuraMusicoId(newArtista.getNome()));
- if (procuraMusico(newArtista) == 1) {
- sendMsg("Artista " + newArtista.getNome() + " esta no sistema");
- } else
- sendMsg("Artista nao esta no sistema");
- break;
- case "download":
- break;
- case "make_admin":
- System.out.println("welcome to make adminss");
- newPessoa.setUsername(toAdmin);
- if(procuraUtilizador(newPessoa) == 1){
- makeAdmin(newPessoa);
- sendMsg("User " + toAdmin + " tornou-se admin");
- }
- else{
- sendMsg("Impossivel tornar administrador");
- }
- //tornaAdmin(newPessoa);
- break;
- case "change_desc_album":
- if(procuraAlbum(newAlbum) == 1){
- updateDescricao(newAlbum);
- System.out.println(newAlbum.getDescricao());
- sendMsg("Descriçao alterada com sucesso");
- }
- else
- sendMsg("não foi possivel alterar" );
- break;
- case "logout":
- logged.remove(user);
- sendMsg("logout feito");
- }
- }
- }
- public static void insereUtilizador(Pessoa pessoa) throws SQLException {
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "INSERT INTO UTILIZADOR"
- + "(USERNAME, PASSWORD, EMAIL,EDITOR,MUSICAID) VALUES"
- + "(?,?,?,?,?)";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setString(1,pessoa.getUsername());
- preparedStatement.setString(2,pessoa.getPassword() );
- preparedStatement.setString(3,pessoa.getMail());
- preparedStatement.setInt(4,1 );
- preparedStatement.setString(5, "");
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static void insereMusico(Artista artista) throws SQLException{
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "INSERT INTO MUSICO"
- + "(IDMUSICO, NOME, EMAIL,MUSICAID,AUTORID) VALUES"
- + "(?,?,?,?,?)";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setString(1,artista.getId());
- preparedStatement.setString(2,artista.getNome());
- preparedStatement.setString(3,artista.getMail());
- preparedStatement.setString(4,"");
- preparedStatement.setString(5,"");
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static int procuraMusico(Artista artista) throws SQLException{
- String ins = "SELECT IDMUSICO FROM MUSICO WHERE IDMUSICO LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1, artista.getId());
- int rs = preparedStatement.executeUpdate();
- if(rs >= 1)
- return 1;
- else
- return 0;
- }
- public static void removeMusico(Artista artista) throws SQLException{
- sp = conn.setSavepoint();
- String ins = "DELETE FROM MUSICO WHERE IDMUSICO LIKE ?";
- try {
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1, artista.getId());
- preparedStatement.executeUpdate();
- conn.commit();
- if(preparedStatement != null){
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static int procuraUtilizador(Pessoa pessoa) throws SQLException{
- String ins = "SELECT USERNAME FROM UTILIZADOR WHERE USERNAME LIKE ? AND PASSWORD LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- System.out.println("sou o "+pessoa.getUsername()+" "+pessoa.getPassword());
- preparedStatement.setString(1, pessoa.getUsername());
- preparedStatement.setString(2, pessoa.getPassword());
- int rs = preparedStatement.executeUpdate();//numero de vezes que o utilizador foi encontrado
- if(rs >= 1) {
- return 1;
- }else{
- return 0;
- }
- }
- public static int checkEditor(Pessoa pessoa) throws SQLException{
- String ins = "SELECT USERNAME FROM UTILIZADOR WHERE USERNAME LIKE ? AND EDITOR = ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,pessoa.getUsername());
- preparedStatement.setInt(2,1);
- System.out.println("fdsfd "+pessoa.getUsername());
- int rs = preparedStatement.executeUpdate();
- if(rs >= 1)
- return 1;
- else
- return 0;
- }
- public static void insereMusica(Musica musica) throws SQLException{
- PreparedStatement preparedStatement;
- String ins;
- String historia = musica.getHistoria();
- String letra = musica.getLetra();
- String nomeEd = musica.getEditora();
- String autorid = procuraAutorId(musica.getMusico());
- String musicaid = musica.getId();
- sp = conn.setSavepoint();
- ins = "INSERT INTO MUSICA"
- + "(ALBUMID, NOME, IDMUSICA,GENERO,HISTORIA,LETRA,NOMEEDITORA,AUTORID,CONCERTOS) VALUES"
- + "(?,?,?,?,?,?,?,?,?)";
- try{
- preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,"");
- preparedStatement.setString(2,musica.getNome());
- preparedStatement.setString(3,musicaid);
- preparedStatement.setString(4,musica.getGenero());//atencao
- preparedStatement.setString(5,historia);
- preparedStatement.setString(6,letra);
- preparedStatement.setString(7,nomeEd);
- preparedStatement.setString(8,autorid);
- preparedStatement.setString(9,"");
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static void deleteMusica(Musica musica) throws SQLException{
- sp = conn.setSavepoint();
- String musicaid = procuraMusicaId(musica.getNome());
- System.out.println(musicaid);
- String ins = "DELETE FROM MUSICO WHERE MUSICAID LIKE ?";
- try {PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1, musicaid);
- preparedStatement.executeUpdate();
- conn.commit();
- if(preparedStatement != null){
- preparedStatement.close();
- }
- }catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- ins = "DELETE FROM MUSICA WHERE NOME LIKE ?";
- try {PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1, musica.getNome());
- preparedStatement.executeUpdate();
- conn.commit();
- if(preparedStatement != null){
- preparedStatement.close();
- }
- }catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static int procuraMusica(Musica musica) throws SQLException{
- String ins = "SELECT NOME FROM MUSICA WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,musica.getNome());
- int rs = preparedStatement.executeUpdate();
- if(rs >= 1)
- return 1;
- else
- return 0;
- }
- public static void insereAlbum(Album album) throws SQLException{
- PreparedStatement preparedStatement;
- String ins;
- sp = conn.setSavepoint();
- ins = "INSERT INTO ALBUM"
- + "(NOME, IDCRITICA, AVAL,IDALBUM,DESCRICAO,GENEROS,DATAL) VALUES"
- + "(?,?,?,?,?,?,?)";
- try{
- preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,album.getNome());
- preparedStatement.setString(2,"");
- preparedStatement.setInt(3,0);
- preparedStatement.setString(4,album.getId());
- preparedStatement.setString(5,album.getDesc());
- preparedStatement.setString(6,album.getGenero());
- preparedStatement.setTimestamp(7,album.getDataL());
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static int procuraAlbum(Album album) throws SQLException{
- String ins = "SELECT NOME FROM ALBUM WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,album.getNome());
- int rs = preparedStatement.executeUpdate();
- if(rs >= 1)
- return 1;
- else
- return 0;
- }
- public static String procuraAlbumId(String nome) throws SQLException{
- ResultSet rs;
- String id = "";
- String ins = "SELECT IDALBUM FROM ALBUM WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,nome);
- rs = preparedStatement.executeQuery();
- while(rs.next()){
- id = rs.getString("IDALBUM");
- }
- return id;
- }
- public static String procuraMusicaId(String nome) throws SQLException{
- ResultSet rs;
- String id = "";
- String ins = "SELECT IDMUSICA FROM MUSICA WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,nome);
- rs = preparedStatement.executeQuery();
- while(rs.next()){
- id = rs.getString("IDMUSICA");
- }
- return id;
- }
- public static String procuraAutorId(String nome) throws SQLException{
- ResultSet rs;
- String id = "";
- String ins = "SELECT AUTORID FROM MUSICO WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,nome);
- rs = preparedStatement.executeQuery();
- while(rs.next()){
- id = rs.getString("AUTORID");
- }
- return id;
- }
- public static String procuraMusicoId(String nome) throws SQLException{
- ResultSet rs;
- String id = "";
- String ins = "SELECT IDMUSICO FROM MUSICO WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,nome);
- rs = preparedStatement.executeQuery();
- while(rs.next()){
- id = rs.getString("IDMUSICO");
- }
- return id;
- }
- public static String procuraMusicoEmail(String nome) throws SQLException{
- ResultSet rs;
- String id = "";
- String ins = "SELECT EMAIL FROM MUSICO WHERE NOME LIKE ?";
- PreparedStatement preparedStatement = conn.prepareStatement(ins);
- preparedStatement.setString(1,nome);
- rs = preparedStatement.executeQuery();
- while(rs.next()){
- id = rs.getString("EMAIL");
- }
- return id;
- }
- public static void insereCritica(Critica critica, Album album) throws SQLException{
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "INSERT INTO CRITICA"
- + "(JUSTIFICACAO, PONT, IDCRITICA,UTILIZADORNOME,ALBUMID) VALUES"
- + "(?,?,?,?,?)";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setString(1,critica.getJust());
- preparedStatement.setInt(2,critica.getPontuacao());
- preparedStatement.setString(3,critica.getId());
- preparedStatement.setString(4,user);//atencao
- preparedStatement.setString(5,album.getId());
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- updateCriticaId(critica, album);
- }
- public static void updateCriticaId(Critica critica, Album album) throws SQLException{
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "UPDATE ALBUM SET IDCRITICA = ? WHERE NOME LIKE ?";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setString(1,critica.getId());
- preparedStatement.setString(2,album.getNome());
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static void updateDescricao(Album album) throws SQLException{
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "UPDATE ALBUM SET DESCRICAO = ? WHERE NOME LIKE ?";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setString(1,album.getDesc());
- preparedStatement.setString(2,album.getNome());
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static void makeAdmin(Pessoa pessoa) throws SQLException{
- PreparedStatement preparedStatement;
- String cmd;
- sp = conn.setSavepoint();
- cmd = "UPDATE UTILIZADOR SET EDITOR = ? WHERE USERNAME LIKE ?";
- try{
- preparedStatement = conn.prepareStatement(cmd);
- preparedStatement.setInt(1,1);
- preparedStatement.setString(2,pessoa.getUsername());
- preparedStatement.executeUpdate();
- conn.commit();
- if (preparedStatement != null) {
- preparedStatement.close();
- }
- } catch (SQLException e) {
- conn.rollback(sp);
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, SQLException {
- //serve para tratar o shutdown, pois assim que aconteca as listas sao guardadas
- Runtime.getRuntime().addShutdownHook(new Thread()
- {
- @Override
- public void run()
- {
- try {
- conn.commit();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- });
- try {
- System.out.println("Connecting to database...");
- Class.forName("oracle.jdbc.driver.OracleDriver");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- conn = DriverManager.getConnection(DB_URL,USER,PASS);
- conn.setAutoCommit(false);
- /*
- System.out.println("Escolha o porto a iniciar ([4000], [3000], [2000])");//NOTA: ligar no 3000
- while(true){
- Scanner sc = new Scanner(System.in);
- porto = sc.nextInt();
- if(porto == 4000 || porto == 3000 || porto == 2000)
- break;
- else{
- System.out.println("Porto invalido");
- continue;
- }
- }*/
- porto=config.getHostMulti();
- System.out.println("Server a escuta no porto "+porto);
- //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
- new Thread() { //THREAD QUE TRATA DO MULTICAST (recebe mensagens)
- public void run() {
- MulticastSocket s = null;
- try {
- s = new MulticastSocket(porto );//3000
- s.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
- } catch (IOException e) {
- e.printStackTrace();
- }
- byte[] buf = new byte[1000];
- DatagramPacket recv = new DatagramPacket(buf, buf.length);
- try {
- while (true) {
- s.receive(recv);
- String msgNew = new String(recv.getData(), 0, recv.getLength());
- escolheOpcao(msgNew);
- }
- } catch (IOException | SQLException e) {
- e.printStackTrace();
- }
- }
- }.start();
- //recebe coisas do tcp client
- receiveTCP();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement