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.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class MulticastServer extends Thread {
- private static ArrayList<Pessoa> bdPessoas = new ArrayList<>();
- private static ArrayList<Musica> bdMusicas = new ArrayList<>();
- private static ArrayList<Album> bdAlbuns = new ArrayList<>();
- private static ArrayList<Artista> bdArtistas = new ArrayList<>();
- private String MULTICAST_ADDRESS = "224.3.2.1";
- private int PORT = 4321;
- private long SLEEP_TIME = 5000;
- 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>();
- //funcao que serve para pesquisar musicas por nome de musica
- public static Musica pesquisaMusicas(Musica musica){
- for(Musica m : bdMusicas){
- if(m.getNome().equals(musica.getNome())){
- return musica;
- }
- }
- System.out.println("Musica nao se encontra no sistema!");
- return null;
- }
- //pesquisar musicas por album
- public Album pesquisaMusicaAlb(String nome){
- for(Album a : bdAlbuns){
- if(a.getNome().equals(nome)){
- return a;
- }
- }
- System.out.println("Album nao esta no sistema!");
- return null;
- }
- public static int pesquisaAlbum(Album a){
- for(Album al : bdAlbuns){
- if(al.getNome().equals(a.getNome())){
- return 1;
- }
- }
- return 0;
- }
- public static void writeCrit(Album al, Critica c){
- for(Album a : bdAlbuns){
- if(a.getNome().equals(al.getNome())){
- a.addCritica(c);
- return;
- }
- }
- }
- public static String printCriticas(Album al){
- for(Album a : bdAlbuns){
- if(a.getNome().equals(al.getNome())){
- return a.printCriticas();
- }
- }
- return "Album nao esta no sistema";
- }
- public static int checkLogin(String username, String pass){
- for(Pessoa p : bdPessoas){
- if(p.getUsername().equals(username) && p.getPassword().equals(pass)){
- return 1;
- }
- }
- return 0;
- }
- public static Pessoa pesquisaPessoas(String username){
- for (Pessoa p : bdPessoas){
- if(p.getUsername().equals(username)){
- return p;
- }
- }
- System.out.println("Pessoa nao esta no sistema!");
- return null;
- }
- public static boolean signUp(Pessoa p){
- if(pesquisaPessoas(p.getUsername())==null){
- bdPessoas.add(p);
- return true;
- }
- else
- return false;
- }
- public static void tornaAdmin(Pessoa p){
- for (Pessoa pe : bdPessoas){
- if(pe.getUsername().equals(p.getUsername())){
- pe.setAdmin(true);
- return;
- }
- }
- }
- public static Artista pesquisaArtistas(String username){
- for (Artista a: bdArtistas){
- if(a.getUsername().equals(username)){
- return a;
- }
- }
- return null;
- }
- public static Boolean addArtist(Artista a){
- if(pesquisaArtistas(a.getUsername())==null){
- bdArtistas.add(a);
- return true;
- }
- else
- return false;
- }
- public static int addAlbum(Artista a, Album al, Musica m){
- if(pesquisaMusicas(m) != null && pesquisaArtistas(a.getUsername()) != null){
- al.setArtista(a);
- al.setMusica(m);
- bdAlbuns.add(al);
- return 1;
- }
- return 0;
- }
- //remove artista
- public static Boolean removeArtist(Artista a){
- if(pesquisaArtistas(a.getUsername()) != null){
- bdArtistas.remove(a);
- return true;
- }
- else
- return false;
- }
- public static int addMusica(Musica m){
- if(pesquisaMusicas(m) == null){
- bdMusicas.add(m);
- return 1;
- }
- System.out.println("Nao foi possivel adicionar musica");
- return 0;
- }
- public static int removeMusica(Musica m){
- if(pesquisaMusicas(m) != null){
- bdMusicas.remove(m);
- return 1;
- }
- return 0;
- }
- public static void printAdmins(){
- for(Pessoa p:bdPessoas){
- if(p.isAdmin())
- System.out.println("Admin: "+p.getMail());
- }
- return;
- }
- //escrever nos fichehiros
- public static void escreveFicheiro(String fich, Object obj){
- ObjectOutputStream ooS = null;
- try{
- FileOutputStream foS = new FileOutputStream(fich);
- ooS = new ObjectOutputStream(foS);
- ooS.writeObject(obj);
- ooS.flush();
- }catch (IOException e) {
- System.out.println("Erro a abrir o ficheiro " + fich);
- }finally {
- if(ooS != null){
- try {
- ooS.close();
- } catch (IOException e) {
- System.out.println("Erro a fechar o ficheiro " + fich);
- }
- }
- }
- }
- 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, bdMusicas);//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
- 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("224.3.2.1");
- int serverPort = 4000;
- DatagramPacket request = new DatagramPacket(m,m.length,aHost,serverPort);
- 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
- public static void escolheOpcao(String comando) throws IOException {
- 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();
- }
- 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]);
- }
- 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 ; username / 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.setUsername(infoArtist[0]);
- }
- if (funcao[1].equals("add_music") && funcao != null){
- //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
- String[] infoMusica = new String[7];
- 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("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
- String[] infoAlbum = new String[4];
- 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]);
- newMusica.setNome(infoAlbum[1]);
- newAlbum.setDesc(infoAlbum[2]);
- newArtista.setUsername(infoAlbum[3]);
- }
- 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]);
- newCritica.setJust(infoAlbum[1]);
- newCritica.setPontuacao(Integer.parseInt(infoAlbum[2]));
- }
- 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")){
- System.out.println("Welcome to sign up");
- if (signUp(newPessoa) == true) {
- nRegistos++;
- if (nRegistos == 1) {//torna a primeira pessoa a registar se admin
- tornaAdmin(newPessoa);
- }
- sendMsg("Registado com sucesso");
- } else
- sendMsg("Nao foi possivel registar");
- }
- if (tipo.equals("login")){
- if (checkLogin(user, password) == 1){
- loginfeito=true;
- 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 "add artist":
- System.out.println("Welcome to add artist");
- if (addArtist(newArtista) == true) {
- 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");
- if (removeArtist(newArtista) == true) {
- 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 (addMusica(newMusica) == 1) {
- 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) {
- 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) {
- 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) {
- sendMsg("Album " + newAlbum.getNome() + ", " + printCriticas(newAlbum));
- } else {
- sendMsg("Album nao esta no sistema");
- }
- break;
- case "write_crit":
- System.out.println("Welcome to write crit");
- if (pesquisaAlbum(newAlbum) == 1) {
- writeCrit(newAlbum, newCritica);
- 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 (pesquisaAlbum(newAlbum) == 1) {
- sendMsg("Album ja se encontra no sistema");
- } else {
- if (addAlbum(newArtista, newAlbum, newMusica) == 1)
- sendMsg("Album adicionado");
- else
- sendMsg("Impossivel adicionar album");
- }
- break;
- case "search_artist":
- System.out.println("Welcome to search artist");
- if (pesquisaArtistas(newArtista.getUsername()) != null) {
- sendMsg("Artista " + newArtista.getUsername() + " esta no sistema");
- } else
- sendMsg("Artista nao esta no sistema");
- break;
- case "admins":
- System.out.println("coisa");
- printAdmins();
- break;
- case "download":
- break;
- case "make_admin":
- System.out.println("welcome to make adminss");
- newPessoa = pesquisaPessoas(toAdmin);
- tornaAdmin(newPessoa);
- sendMsg("User " + toAdmin + " tornou-se admin");
- break;
- }
- }
- }
- private static void addPessoa(Pessoa p){
- bdPessoas.add(p);
- }
- public static void main(String[] args) throws IOException, InterruptedException {
- //serve para tratar o shutdown, pois assim que aconteca as listas sao guardadas
- Runtime.getRuntime().addShutdownHook(new Thread()
- {
- @Override
- public void run()
- {
- System.out.println("Server shutdown!");
- escreveFicheiro("bdMusicas",bdMusicas);
- escreveFicheiro("bdPessoas",bdPessoas);
- escreveFicheiro("bdArtistas",bdArtistas);
- escreveFicheiro("bdAlbuns",bdAlbuns);
- }
- });
- 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;
- }
- }
- 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("224.3.2.1"));
- } 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 e) {
- e.printStackTrace();
- }
- }
- }.start();
- //recebe coisas do tcp client
- receiveTCP();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement