Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.98 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.rmi.RemoteException;
  4. import java.util.ArrayList;
  5. import java.util.Scanner;
  6.  
  7. public class MulticastServer extends Thread {
  8.     private static ArrayList<Pessoa> bdPessoas = new ArrayList<>();
  9.     private static ArrayList<Musica> bdMusicas = new ArrayList<>();
  10.     private static ArrayList<Album> bdAlbuns = new ArrayList<>();
  11.     private static ArrayList<Artista> bdArtistas = new ArrayList<>();
  12.     private String MULTICAST_ADDRESS = "224.3.2.1";
  13.     private int PORT = 4321;
  14.     private long SLEEP_TIME = 5000;
  15.     private static int porto;
  16.     //escrever nos ficheiros
  17.     public static void escreveFicheiro(String fich, Object obj){
  18.         ObjectOutputStream ooS = null;
  19.         try{
  20.             FileOutputStream foS = new FileOutputStream(fich);
  21.             ooS = new ObjectOutputStream(foS);
  22.             ooS.writeObject(obj);
  23.             ooS.flush();
  24.         }catch (IOException e) {
  25.             System.out.println("Erro a abrir o ficheiro " + fich);
  26.         }finally {
  27.             if(ooS  != null){
  28.                 try {
  29.                     ooS.close();
  30.                 } catch (IOException e) {
  31.                     System.out.println("Erro a fechar o ficheiro " + fich);
  32.                 }
  33.             }
  34.         }
  35.     }
  36.  
  37.  
  38.     //funcao que serve para pesquisar musicas por nome de musica
  39.     public Musica pesquisaMusicas(Musica musica){
  40.         for(Musica m : bdMusicas){
  41.             if(m.getNome().equals(musica.getNome())){
  42.                 return musica;
  43.             }
  44.         }
  45.         System.out.println("Musica nao se encontra no sistema!");
  46.         return null;
  47.     }
  48.     //pesquisar musicas por album
  49.     public Album pesquisaMusicaAlb(String nome){
  50.         for(Album a : bdAlbuns){
  51.             if(a.getNome().equals(nome)){
  52.                 return a;
  53.             }
  54.         }
  55.         System.out.println("Album nao esta no sistema!");
  56.         return null;
  57.     }
  58.  
  59.     public static int checkLogin(String username, String pass){
  60.         for(Pessoa p : bdPessoas){
  61.             if(p.getUsername().equals(username) && p.getPassword().equals(pass)){
  62.                 return 1;
  63.             }
  64.         }
  65.         return 0;
  66.     }
  67.  
  68.     public static Pessoa pesquisaPessoas(String username){
  69.         for (Pessoa p : bdPessoas){
  70.             if(p.getUsername().equals(username)){
  71.                 return p;
  72.             }
  73.         }
  74.         System.out.println("Pessoa nao esta no sistema!");
  75.         return null;
  76.     }
  77.  
  78.     public static boolean signUp(Pessoa p){
  79.         if(pesquisaPessoas(p.getUsername())==null){
  80.             bdPessoas.add(p);
  81.             return true;
  82.         }
  83.         else
  84.             return false;
  85.     }
  86.  
  87.     public static Artista pesquisaArtistas(String nome){
  88.         for (Artista a: bdArtistas){
  89.             if(a.getNome().equals(nome)){
  90.                 return a;
  91.             }
  92.         }
  93.         return null;
  94.     }
  95.     public static Boolean addArtist(Artista a){
  96.         if(pesquisaArtistas(a.getUsername())==null){
  97.             bdArtistas.add(a);
  98.             return true;
  99.         }
  100.         else
  101.             return false;
  102.  
  103.     }
  104.  
  105.     public static void sendResposta(String msg) throws IOException {
  106.         byte[] buf = new byte[1000];
  107.         DatagramPacket recv = new DatagramPacket(buf, buf.length);
  108.  
  109.         DatagramSocket s = null;
  110.         try {
  111.             s = new DatagramSocket(4000);
  112.         } catch (SocketException e) {
  113.             e.printStackTrace();
  114.         }
  115.         DatagramPacket reply = new DatagramPacket(recv.getData(),
  116.                 recv.getLength(), recv.getAddress(), recv.getPort());
  117.         s.send(reply);
  118.     }
  119.  
  120.     public static void escolheOpcao(String comando) throws IOException {
  121.  
  122.         String user = new String();
  123.         String password = new String();
  124.         String tipo = new String();
  125.         Pessoa newPessoa = new Pessoa();
  126.         Artista newArtista=new Artista();
  127.         try {
  128.             if (comando != null && comando != "\n" && comando != "") {
  129.                 String parts[] = comando.split(" ; ");
  130.                 String funcao[] = parts[0].split(" / ");
  131.                 tipo = funcao[1];
  132.                 if (funcao[1].equals("login") && funcao != null) {
  133.                     String username[] = parts[1].split(" / ");
  134.                     user = username[1].trim();
  135.                     String[] passwordArray = parts[2].split("/");
  136.                     password = passwordArray[1].trim();
  137.                 }
  138.                 if (funcao[1].equals("sign up") && funcao != null) {
  139.                     //type / sign up ; item_count / 2 ; name / gui ; username / gui ; password / ola ; mail / g@hot.com
  140.                     String[] infoArray = new String[4];
  141.                     String[] f;
  142.                     int count=0;
  143.                     for (int i=2; i<parts.length; i++){
  144.                         f=parts[i].split(" / ");
  145.                         infoArray[count] =f[1].trim();
  146.                         count++;
  147.                     }
  148.                     newPessoa.setNome(infoArray[0]);
  149.                     newPessoa.setUsername(infoArray[1]);
  150.                     newPessoa.setPassword(infoArray[2]);
  151.                     newPessoa.setMail(infoArray[3]);
  152.                 }
  153.                 if (funcao[1].equals("add artist") && funcao != null) {
  154.                     //type / add artist ; item_count / 4 ; name / gui ; username / gui ; password / ola ; mail / g@hot.com
  155.                     String[] infoArtist = new String[4];
  156.                     String[] f;
  157.                     int count=0;
  158.                     for (int i=2; i<parts.length; i++){
  159.                         f=parts[i].split(" / ");
  160.                         infoArtist[count] =f[1].trim();
  161.                         count++;
  162.                     }
  163.                     newArtista.setNome(infoArtist[0]);
  164.                     newArtista.setUsername(infoArtist[1]);
  165.                     newArtista.setPassword(infoArtist[2]);
  166.                     newArtista.setMail(infoArtist[3]);
  167.  
  168.                 }
  169.                 if (funcao[1].equals("remove artist") && funcao != null) {
  170.                     //type / remove artist ; item_count / 2 ; name / gui ; username / gui ; password / ola ;
  171.  
  172.                 }
  173.             }
  174.         }catch (ArrayIndexOutOfBoundsException exception){}
  175.  
  176.         switch (tipo){
  177.             case "login":
  178.                 if (checkLogin(user, password) == 1){
  179.                     pesquisaPessoas(user).setLog(true);
  180.                 }
  181.                 //envia resposta
  182.                 //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  183.                 break;
  184.             case "sign up":
  185.                 System.out.println("welcome to sign up");
  186.                 if(signUp(newPessoa)==true){
  187.                     System.out.println("registado com sucesso");
  188.                 } else
  189.                     System.out.println("nao foi possivel registar");
  190.                 //envia resposta
  191.                 //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  192.                 break;
  193.             case "add artist":
  194.                 System.out.println("welcome to add artist");
  195.                 if (addArtist(newArtista)==true){
  196.                     System.out.println("Artista registado com sucesso");
  197.                 } else
  198.                     System.out.println("nao foi possivel registar");
  199.                 //envia resposta
  200.                 //sendResposta("type / status ; logged / on ; msg / Welcome to DropMusic");
  201.                 break;
  202.  
  203.  
  204.  
  205.         }
  206.     }
  207.  
  208.     public static void main(String[] args) {
  209.         MulticastServer server = new MulticastServer();
  210.         //server.start();
  211.  
  212.  
  213.         System.out.println("Escolha o porto a iniciar ([4000], [3000], [2000])");
  214.         while(true){
  215.             Scanner sc = new Scanner(System.in);
  216.             porto = sc.nextInt();
  217.             if(porto == 4000 || porto == 3000 || porto == 2000)
  218.                 break;
  219.             else{
  220.                 System.out.println("Porto invalido");
  221.                 continue;
  222.             }
  223.  
  224.         }
  225.  
  226.         //thread que recebe mensagens do rmi
  227.         new Thread() { //THREAD QUE TRATA DO MULTICAST (recebe mensagens)
  228.             public void run() {
  229.                 MulticastSocket s = null;
  230.                 try {
  231.                     s = new MulticastSocket(porto);
  232.                     s.joinGroup(InetAddress.getByName("224.3.2.1"));
  233.                 } catch (IOException e) {
  234.                     e.printStackTrace();
  235.                 }
  236.  
  237.                 byte[] buf = new byte[1000];
  238.                 DatagramPacket recv = new DatagramPacket(buf, buf.length);
  239.  
  240.                 try {
  241.                     while (true) {
  242.                         s.receive(recv);
  243.                         String msgNew = new String(recv.getData(), 0, recv.getLength());
  244.                         escolheOpcao(msgNew);
  245.                     }
  246.                 } catch (IOException e) {
  247.                     e.printStackTrace();
  248.                 }
  249.  
  250.             }
  251.         }.start();
  252.  
  253.     }
  254.  
  255.     public MulticastServer() {
  256.         super("Server " + (long) (Math.random() * 1000));
  257.     }
  258.  
  259.     public void run() {
  260.         MulticastSocket socket = null;
  261.         long counter = 0;
  262.         System.out.println(this.getName() + " running...");
  263.         try {
  264.             socket = new MulticastSocket();  // create socket without binding it (only for sending)
  265.             while (true) {
  266.                 String message = this.getName() + " packet " + counter++;
  267.                 byte[] buffer = message.getBytes();
  268.  
  269.                 InetAddress group = InetAddress.getByName(MULTICAST_ADDRESS);
  270.                 DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, PORT);
  271.                 socket.send(packet);
  272.  
  273.                 try { sleep((long) (Math.random() * SLEEP_TIME)); } catch (InterruptedException e) { }
  274.             }
  275.         } catch (IOException e) {
  276.             e.printStackTrace();
  277.         } finally {
  278.             socket.close();
  279.         }
  280.     }
  281. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement