Advertisement
Guest User

Untitled

a guest
Oct 27th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 23.37 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import java.util.Scanner;
  7.  
  8. public class MulticastServer extends Thread {
  9.     private static ArrayList<Pessoa> bdPessoas = new ArrayList<>();
  10.     private static ArrayList<Musica> bdMusicas = new ArrayList<>();
  11.     private static ArrayList<Album> bdAlbuns = new ArrayList<>();
  12.     private static ArrayList<Artista> bdArtistas = new ArrayList<>();
  13.     private String MULTICAST_ADDRESS = "224.3.2.1";
  14.     private int PORT = 4321;
  15.     private long SLEEP_TIME = 5000;
  16.     private static int porto;
  17.     private static int nRegistos; // este valor ha de ser carregado de um ficheiro, conta o numero de registos
  18.     public static Map logged = new HashMap<String,String>();
  19.  
  20.     //funcao que serve para pesquisar musicas por nome de musica
  21.     public static Musica pesquisaMusicas(Musica musica){
  22.         for(Musica m : bdMusicas){
  23.             if(m.getNome().equals(musica.getNome())){
  24.                 return musica;
  25.             }
  26.         }
  27.         System.out.println("Musica nao se encontra no sistema!");
  28.         return null;
  29.     }
  30.     //pesquisar musicas por album
  31.     public Album pesquisaMusicaAlb(String nome){
  32.         for(Album a : bdAlbuns){
  33.             if(a.getNome().equals(nome)){
  34.                 return a;
  35.             }
  36.         }
  37.         System.out.println("Album nao esta no sistema!");
  38.         return null;
  39.     }
  40.  
  41.     public static int pesquisaAlbum(Album a){
  42.         for(Album al : bdAlbuns){
  43.             if(al.getNome().equals(a.getNome())){
  44.                 return 1;
  45.             }
  46.         }
  47.         return 0;
  48.     }
  49.  
  50.     public static void writeCrit(Album al, Critica c){
  51.         for(Album a : bdAlbuns){
  52.             if(a.getNome().equals(al.getNome())){
  53.                 a.addCritica(c);
  54.                 return;
  55.             }
  56.         }
  57.     }
  58.  
  59.     public static String printCriticas(Album al){
  60.         for(Album a : bdAlbuns){
  61.             if(a.getNome().equals(al.getNome())){
  62.                 return a.printCriticas();
  63.             }
  64.         }
  65.         return "Album nao esta no sistema";
  66.     }
  67.  
  68.     public static int checkLogin(String username, String pass){
  69.         for(Pessoa p : bdPessoas){
  70.             if(p.getUsername().equals(username) && p.getPassword().equals(pass)){
  71.                 return 1;
  72.             }
  73.         }
  74.         return 0;
  75.     }
  76.  
  77.     public static Pessoa pesquisaPessoas(String username){
  78.         for (Pessoa p : bdPessoas){
  79.             if(p.getUsername().equals(username)){
  80.                 return p;
  81.             }
  82.         }
  83.         System.out.println("Pessoa nao esta no sistema!");
  84.         return null;
  85.     }
  86.  
  87.     public static boolean signUp(Pessoa p){
  88.         if(pesquisaPessoas(p.getUsername())==null){
  89.             bdPessoas.add(p);
  90.             return true;
  91.         }
  92.         else
  93.             return false;
  94.     }
  95.  
  96.     public static void tornaAdmin(Pessoa p){
  97.         for (Pessoa pe : bdPessoas){
  98.             if(pe.getUsername().equals(p.getUsername())){
  99.                 pe.setAdmin(true);
  100.                 return;
  101.             }
  102.         }
  103.     }
  104.  
  105.     public static Artista pesquisaArtistas(String username){
  106.         for (Artista a: bdArtistas){
  107.             if(a.getUsername().equals(username)){
  108.                 return a;
  109.             }
  110.         }
  111.         return null;
  112.     }
  113.     public static Boolean addArtist(Artista a){
  114.         if(pesquisaArtistas(a.getUsername())==null){
  115.             bdArtistas.add(a);
  116.             return true;
  117.         }
  118.         else
  119.             return false;
  120.  
  121.     }
  122.  
  123.     public static int addAlbum(Artista a, Album al, Musica m){
  124.         if(pesquisaMusicas(m) != null && pesquisaArtistas(a.getUsername()) != null){
  125.             al.setArtista(a);
  126.             al.setMusica(m);
  127.             bdAlbuns.add(al);
  128.             return 1;
  129.         }
  130.         return 0;
  131.     }
  132.  
  133.     //remove artista
  134.     public static Boolean removeArtist(Artista a){
  135.         if(pesquisaArtistas(a.getUsername()) != null){
  136.             bdArtistas.remove(a);
  137.             return true;
  138.         }
  139.         else
  140.             return false;
  141.  
  142.     }
  143.  
  144.     public static int addMusica(Musica m){
  145.         if(pesquisaMusicas(m) == null){
  146.             bdMusicas.add(m);
  147.             return 1;
  148.         }
  149.         System.out.println("Nao foi possivel adicionar musica");
  150.         return 0;
  151.     }
  152.  
  153.     public static int removeMusica(Musica m){
  154.         if(pesquisaMusicas(m) != null){
  155.             bdMusicas.remove(m);
  156.             return 1;
  157.         }
  158.         return 0;
  159.     }
  160.  
  161.     public static void printAdmins(){
  162.         for(Pessoa p:bdPessoas){
  163.             if(p.isAdmin())
  164.                 System.out.println("Admin: "+p.getMail());
  165.  
  166.         }
  167.         return;
  168.     }
  169.  
  170.  
  171.  
  172.     //escrever nos fichehiros
  173.     public static void escreveFicheiro(String fich, Object obj){
  174.         ObjectOutputStream ooS = null;
  175.         try{
  176.             FileOutputStream foS = new FileOutputStream(fich);
  177.             ooS = new ObjectOutputStream(foS);
  178.             ooS.writeObject(obj);
  179.             ooS.flush();
  180.         }catch (IOException e) {
  181.             System.out.println("Erro a abrir o ficheiro " + fich);
  182.         }finally {
  183.             if(ooS  != null){
  184.                 try {
  185.                     ooS.close();
  186.                 } catch (IOException e) {
  187.                     System.out.println("Erro a fechar o ficheiro " + fich);
  188.                 }
  189.             }
  190.         }
  191.     }
  192.  
  193.     public static void receiveTCP(){
  194.         int numero=0;
  195.  
  196.         try{
  197.             int serverPort = 6000;
  198.             System.out.println("A Escuta no Porto 6000");
  199.             ServerSocket listenSocket = new ServerSocket(serverPort);
  200.             System.out.println("LISTEN SOCKET="+listenSocket);
  201.             while(true) {
  202.                 Socket clientSocket = listenSocket.accept(); // BLOQUEANTE
  203.                 System.out.println("CLIENT_SOCKET (created at accept())="+clientSocket);
  204.                 numero ++;
  205.                 new ClientThread(clientSocket, bdMusicas);//criar nova classe chamada clientthread que recebe os pedidos que chegam do cliente
  206.             }
  207.         }catch(IOException e)
  208.         {System.out.println("Listen:" + e.getMessage());}
  209.     }
  210.  
  211.  
  212.     //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
  213.     public static void sendMsg(String texto) throws SocketException {
  214.         new Thread(){
  215.             public void run(){
  216.                 MulticastSocket aSocket = null;//atencao
  217.                 try {
  218.                     aSocket = new MulticastSocket();
  219.  
  220.                         byte [] m = texto.getBytes();
  221.  
  222.                         InetAddress aHost = InetAddress.getByName("224.3.2.1");
  223.                         int serverPort = 4000;
  224.                         DatagramPacket request = new DatagramPacket(m,m.length,aHost,serverPort);
  225.                         aSocket.send(request);
  226.  
  227.  
  228.                 }catch (SocketException e){System.out.println("Socket: " + e.getMessage());
  229.                 }catch (IOException e){System.out.println("IO: " + e.getMessage());
  230.                 }finally {if(aSocket != null) aSocket.close();}
  231.             }
  232.  
  233.         }.start();
  234.     }
  235.  
  236.     //funcao que trata o comando recebido do cliente
  237.     public static void escolheOpcao(String comando) throws IOException {
  238.  
  239.         String user = new String();
  240.         String password = new String();
  241.         String tipo = new String();
  242.         Pessoa newPessoa = new Pessoa();
  243.         Artista newArtista=new Artista();
  244.         Musica newMusica = new Musica();
  245.         Album newAlbum = new Album();
  246.         Critica newCritica = new Critica();
  247.         String toAdmin = new String();
  248.         try {
  249.             if (comando != null && comando != "\n" && comando != "") {
  250.                 String parts[] = comando.split(" ; ");
  251.                 String funcao[] = parts[0].split(" / ");
  252.                 tipo = funcao[1];
  253.                 if (funcao[1].equals("login") && funcao != null) {
  254.                     String username[] = parts[1].split(" / ");
  255.                     user = username[1].trim();
  256.                     String[] passwordArray = parts[2].split("/");
  257.                     password = passwordArray[1].trim();
  258.                 }
  259.                 if (funcao[1].equals("sign up") && funcao != null) {
  260.                     //type / sign up ; item_count / 2 ; name / gui ; username / gui ; password / ola ; mail / g@hot.com
  261.                     String[] infoArray = new String[4];
  262.                     String[] f;
  263.                     int count=0;
  264.                     for (int i=2; i<parts.length; i++){
  265.                         f=parts[i].split(" / ");
  266.                         infoArray[count] =f[1].trim();
  267.                         count++;
  268.                     }
  269.                     newPessoa.setNome(infoArray[0]);
  270.                     newPessoa.setUsername(infoArray[1]);
  271.                     newPessoa.setPassword(infoArray[2]);
  272.                     newPessoa.setMail(infoArray[3]);
  273.                 }
  274.                 if (funcao[1].equals("add artist") && funcao != null) {
  275.                     //type / add artist ; item_count / 4 ; name / zeca ; username / zeca ; password / ola ; mail / g@hot.com
  276.                     String[] infoArtist = new String[4];
  277.                     String[] f;
  278.                     int count=0;
  279.                     for (int i=2; i<parts.length; i++){
  280.                         f=parts[i].split(" / ");
  281.                         infoArtist[count] =f[1].trim();
  282.                         count++;
  283.                     }
  284.                     newArtista.setNome(infoArtist[0]);
  285.                     newArtista.setUsername(infoArtist[1]);
  286.                     newArtista.setPassword(infoArtist[2]);
  287.                     newArtista.setMail(infoArtist[3]);
  288.  
  289.                 }
  290.                 if (funcao[1].equals("remove_artist") && funcao != null) {
  291.                     //type / remove_artist ; item_count / 2 ; name / gui ; username / gui ; password / ola
  292.                     String[] infoArtist = new String[3];
  293.                     String[] f;
  294.                     int count=0;
  295.                     for (int i=2; i<parts.length; i++){
  296.                         f=parts[i].split(" / ");
  297.                         infoArtist[count] =f[1].trim();
  298.                         count++;
  299.                     }
  300.                     newArtista.setNome(infoArtist[0]);
  301.                     newArtista.setUsername(infoArtist[1]);
  302.                     newArtista.setPassword(infoArtist[2]);
  303.  
  304.                 }
  305.                 if(funcao[1].equals("search_artist") && funcao != null){
  306.                     //type / search_artist ; item_count / 1 ; username / zeca
  307.                     String[] infoArtist = new String[3];
  308.                     String[] f;
  309.                     int count=0;
  310.                     for (int i=2; i<parts.length; i++){
  311.                         f=parts[i].split(" / ");
  312.                         infoArtist[count] =f[1].trim();
  313.                         count++;
  314.                     }
  315.                     newArtista.setUsername(infoArtist[0]);
  316.                 }
  317.                 if (funcao[1].equals("add_music") && funcao != null){
  318.                     //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
  319.                     String[] infoMusica = new String[7];
  320.                     String[] f;
  321.                     int count=0;
  322.                     for (int i=2; i<parts.length; i++){
  323.                         f=parts[i].split(" / ");
  324.                         infoMusica[count] =f[1].trim();
  325.                         count++;
  326.                     }
  327.                     newMusica.setNome(infoMusica[0]);//atencao
  328.                 }
  329.                 if(funcao[1].equals("remove_music") && funcao != null){
  330.                     //type / remove_music ; item_count / 1 ; name / vampiros
  331.                     String[] infoMusica = new String[1];
  332.                     String[] f;
  333.                     int count=0;
  334.                     for (int i=2; i<parts.length; i++){
  335.                         f=parts[i].split(" / ");
  336.                         infoMusica[count] =f[1].trim();
  337.                         count++;
  338.                     }
  339.                     newMusica.setNome(infoMusica[0]);//atencao
  340.                 }
  341.                 if(funcao[1].equals("search_music") && funcao != null){
  342.                     //type / search_music ; item_count / 1 ; name / vampiros
  343.                     String[] infoMusica = new String[1];
  344.                     String[] f;
  345.                     int count=0;
  346.                     for (int i=2; i<parts.length; i++){
  347.                         f=parts[i].split(" / ");
  348.                         infoMusica[count] =f[1].trim();
  349.                         count++;
  350.                     }
  351.                     newMusica.setNome(infoMusica[0]);
  352.                 }
  353.                 if(funcao[1].equals("add_album") && funcao != null){
  354.                     //type / add_album ; item_count / 4 ; name / maxim ; musicas / vampiros ; desc / album fixe este ; artista / zeca
  355.                     String[] infoAlbum = new String[4];
  356.                     String[] f;
  357.                     int count=0;
  358.                     for (int i=2; i<parts.length; i++){
  359.                         f=parts[i].split(" / ");
  360.                         infoAlbum[count] =f[1].trim();
  361.                         count++;
  362.                     }
  363.                     newAlbum.setNome(infoAlbum[0]);
  364.                     newMusica.setNome(infoAlbum[1]);
  365.                     newAlbum.setDesc(infoAlbum[2]);
  366.                     newArtista.setUsername(infoAlbum[3]);
  367.                 }
  368.                 if(funcao[1].equals("search_album") && funcao != null){
  369.                     //type / search_album ; item_count / 1 ; name / maxim
  370.                     String[] infoAlbum = new String[1];
  371.                     String[] f;
  372.                     int count=0;
  373.                     for (int i=2; i<parts.length; i++){
  374.                         f=parts[i].split(" / ");
  375.                         infoAlbum[count] =f[1].trim();
  376.                         count++;
  377.                     }
  378.                     newAlbum.setNome(infoAlbum[0]);
  379.                 }
  380.                 if(funcao[1].equals("write_crit") && funcao != null){
  381.                     //type / write_crit ; item_count / 3 ; name / maxim ; crit / este album e muito fixe ; pont / 9
  382.                     String[] infoAlbum = new String[3];
  383.                     String[] f;
  384.                     int count=0;
  385.                     for (int i=2; i<parts.length; i++){
  386.                         f=parts[i].split(" / ");
  387.                         infoAlbum[count] =f[1].trim();
  388.                         count++;
  389.                     }
  390.                     newAlbum.setNome(infoAlbum[0]);
  391.                     newCritica.setJust(infoAlbum[1]);
  392.                     newCritica.setPontuacao(Integer.parseInt(infoAlbum[2]));
  393.  
  394.                 }
  395.                 if(funcao[1].equals("download") && funcao != null){
  396.                     //type / download ; item_count / 1 ; name / oioi
  397.                     String[] infoAlbum = new String[1];
  398.                     String[] f;
  399.                     int count=0;
  400.                     for (int i=2; i<parts.length; i++){
  401.                         f=parts[i].split(" / ");
  402.                         infoAlbum[count] =f[1].trim();
  403.                         count++;
  404.                     }
  405.                 }
  406.                 if (funcao[1].equals("make_admin") && funcao != null) {
  407.                     //type / make_admin ; item_count / 1 ; username / pina
  408.  
  409.                     String[] f;
  410.                     f = parts[2].split(" / ");
  411.                     toAdmin = f[1].trim();
  412.  
  413.                 }
  414.             }
  415.  
  416.         }catch (ArrayIndexOutOfBoundsException exception){}
  417.  
  418.         if(tipo.equals("sign up")){
  419.             System.out.println("Welcome to sign up");
  420.             if (signUp(newPessoa) == true) {
  421.                 nRegistos++;
  422.                 if (nRegistos == 1) {//torna a primeira pessoa a registar se admin
  423.                     tornaAdmin(newPessoa);
  424.                 }
  425.                 sendMsg("Registado com sucesso");
  426.             } else
  427.                 sendMsg("Nao foi possivel registar");
  428.  
  429.         }
  430.         if (tipo.equals("login")){
  431.             if (checkLogin(user, password) == 1){
  432.                 loginfeito=true;
  433.                 pesquisaPessoas(user).setLog(true);
  434.                 logged.put(user,"logged");
  435.                 //envia resposta em conforme esta loggado
  436.                 sendMsg("type / status ; logged / on ; msg / Welcome to DropMusic");
  437.             }
  438.             else{
  439.                 sendMsg("Utilizador nao registado!");
  440.             }
  441.         }
  442.         if (logged.get(user)!=null) {
  443.             switch (tipo) {
  444.                 case "add artist":
  445.                     System.out.println("Welcome to add artist");
  446.                     if (addArtist(newArtista) == true) {
  447.                         sendMsg("Artista registado com sucesso");
  448.                     } else
  449.                         sendMsg("Nao foi possivel registar");
  450.                     //envia resposta
  451.                     //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  452.                     break;
  453.                 case "remove_artist":
  454.                     System.out.println("Welcome to remove artist");
  455.                     if (removeArtist(newArtista) == true) {
  456.                         sendMsg("Artista " + newArtista.getUsername() + " removido com exito!");
  457.                     } else {
  458.                         sendMsg("Nao foi possivel remover");
  459.                     }
  460.                     break;
  461.                 case "add_music":
  462.                     System.out.println("Welcome to add music");
  463.                     if (addMusica(newMusica) == 1) {
  464.                         sendMsg("Musica adicionada com sucesso");
  465.                     } else {
  466.                         sendMsg("Nao foi possivel adicionar");
  467.                     }
  468.                     break;
  469.                 case "remove_music":
  470.                     System.out.println("Welcome to remove music");
  471.                     if (removeMusica(newMusica) == 1) {
  472.                         sendMsg("Musica removida com sucesso");
  473.                     } else {
  474.                         sendMsg("Nao foi possivel remover");
  475.                     }
  476.                     break;
  477.                 case "search_music":
  478.                     System.out.println("Welcome to search music");
  479.                     if (pesquisaMusicas(newMusica) != null) {
  480.                         sendMsg("A sua musica " + newMusica.getNome() + " esta no sistema");
  481.                     } else {
  482.                         sendMsg("A sua musica nao se encontra no sistema");
  483.                     }
  484.                     break;
  485.                 case "search_album":
  486.                     System.out.println("Welcome to search_album");
  487.                     if (pesquisaAlbum(newAlbum) == 1) {
  488.                         sendMsg("Album " + newAlbum.getNome() + ", " + printCriticas(newAlbum));
  489.                     } else {
  490.                         sendMsg("Album nao esta no sistema");
  491.                     }
  492.                     break;
  493.                 case "write_crit":
  494.                     System.out.println("Welcome to write crit");
  495.                     if (pesquisaAlbum(newAlbum) == 1) {
  496.                         writeCrit(newAlbum, newCritica);
  497.                         sendMsg("Avaliacao ao album feita com sucesso");
  498.                     } else {
  499.                         sendMsg("Album nao se encontra no sistema");
  500.                     }
  501.                     break;
  502.                 case "add_album":
  503.                     System.out.println("Welcome to add album");
  504.                     if (pesquisaAlbum(newAlbum) == 1) {
  505.                         sendMsg("Album ja se encontra no sistema");
  506.                     } else {
  507.                         if (addAlbum(newArtista, newAlbum, newMusica) == 1)
  508.                             sendMsg("Album adicionado");
  509.                         else
  510.                             sendMsg("Impossivel adicionar album");
  511.                     }
  512.                     break;
  513.                 case "search_artist":
  514.                     System.out.println("Welcome to search artist");
  515.                     if (pesquisaArtistas(newArtista.getUsername()) != null) {
  516.                         sendMsg("Artista " + newArtista.getUsername() + " esta no sistema");
  517.                     } else
  518.                         sendMsg("Artista nao esta no sistema");
  519.                     break;
  520.                 case "admins":
  521.                     System.out.println("coisa");
  522.                     printAdmins();
  523.                     break;
  524.                 case "download":
  525.  
  526.                     break;
  527.                 case "make_admin":
  528.                     System.out.println("welcome to make adminss");
  529.                     newPessoa = pesquisaPessoas(toAdmin);
  530.                     tornaAdmin(newPessoa);
  531.                     sendMsg("User " + toAdmin + " tornou-se admin");
  532.                     break;
  533.  
  534.             }
  535.         }
  536.     }
  537.  
  538.     private static void addPessoa(Pessoa p){
  539.         bdPessoas.add(p);
  540.     }
  541.  
  542.  
  543.     public static void main(String[] args) throws IOException, InterruptedException {
  544.  
  545.         //serve para tratar o shutdown, pois assim que aconteca as listas sao guardadas
  546.         Runtime.getRuntime().addShutdownHook(new Thread()
  547.         {
  548.             @Override
  549.             public void run()
  550.             {
  551.                 System.out.println("Server shutdown!");
  552.                 escreveFicheiro("bdMusicas",bdMusicas);
  553.                 escreveFicheiro("bdPessoas",bdPessoas);
  554.                 escreveFicheiro("bdArtistas",bdArtistas);
  555.                 escreveFicheiro("bdAlbuns",bdAlbuns);
  556.             }
  557.         });
  558.  
  559.  
  560.         System.out.println("Escolha o porto a iniciar ([4000], [3000], [2000])");//NOTA: ligar no 3000
  561.         while(true){
  562.             Scanner sc = new Scanner(System.in);
  563.             porto = sc.nextInt();
  564.             if(porto == 4000 || porto == 3000 || porto == 2000)
  565.                 break;
  566.             else{
  567.                 System.out.println("Porto invalido");
  568.                 continue;
  569.             }
  570.  
  571.         }
  572.  
  573.         System.out.println("Server a escuta no porto "+porto);
  574.  
  575.         //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
  576.         new Thread() { //THREAD QUE TRATA DO MULTICAST (recebe mensagens)
  577.             public void run() {
  578.                 MulticastSocket s = null;
  579.                 try {
  580.                     s = new MulticastSocket(porto);//3000
  581.                     s.joinGroup(InetAddress.getByName("224.3.2.1"));
  582.                 } catch (IOException e) {
  583.                     e.printStackTrace();
  584.                 }
  585.  
  586.                 byte[] buf = new byte[1000];
  587.                 DatagramPacket recv = new DatagramPacket(buf, buf.length);
  588.  
  589.                 try {
  590.                     while (true) {
  591.                         s.receive(recv);
  592.                         String msgNew = new String(recv.getData(), 0, recv.getLength());
  593.                         escolheOpcao(msgNew);
  594.  
  595.                     }
  596.                 } catch (IOException e) {
  597.                     e.printStackTrace();
  598.                 }
  599.  
  600.             }
  601.         }.start();
  602.  
  603.         //recebe coisas do tcp client
  604.         receiveTCP();
  605.     }
  606. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement