Advertisement
Guest User

Untitled

a guest
Dec 31st, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.83 KB | None | 0 0
  1. //Cliente
  2. package pkg;
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.io.PrintWriter;
  8. import java.net.Socket;
  9.  
  10. public class Client {
  11.     public static void main(String[] args) {
  12.         try {
  13.           BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
  14.           Socket c = new Socket ("localhost", 1026);
  15.           BufferedReader in = new BufferedReader (new InputStreamReader (c.getInputStream ()));
  16.           PrintWriter out = new PrintWriter (c.getOutputStream (), true);
  17.           System.out.println("Conecção ao servidor efetuada.\n"
  18.                 + "Bem-vindo!\n"
  19.                 + "----------------------------------------------------------------------------\n"
  20.                 + "Escolha uma opção:\n1) Registar\n2) Efetuar Login\n3) Sair\n");
  21.           String s,response;
  22.           response="";
  23.           while (!response.equals("Saiu do sistema")) {
  24.                s = keyboard.readLine ();
  25.                out.println (s);
  26.                response = in.readLine();
  27.                System.out.println (response);
  28.                
  29.           }
  30.         }
  31.         catch (IOException e) {
  32.             System.out.println(e.getMessage());
  33.         }
  34.     }
  35. }
  36. //Servidor
  37. package pkg;
  38.  
  39. import java.io.IOException;
  40. import java.net.ServerSocket;
  41. import java.net.Socket;
  42.  
  43. public class Server implements Runnable{
  44.     private SistemaLeiloes sistema;
  45.  
  46.    
  47.     public Server(SistemaLeiloes sys){
  48.         this.sistema=sys;
  49.     }
  50.     public Server (){
  51.         this.sistema=new SistemaLeiloes();
  52.         User userteste = new User ();
  53.         this.sistema.addUser(userteste);
  54.        
  55.     }
  56.    
  57.      public void run(){
  58.         try {
  59.             ServerSocket s = new ServerSocket(1026);
  60.             Socket client;
  61.             System.out.println("Server is operational.");
  62.             while (true) {
  63.                 client = s.accept ();
  64.                 System.out.println("Cliente ligado.");
  65.                 Thread t = new Thread((Runnable) new Interface(client,sistema));
  66.                 t.start();
  67.             }
  68.         } catch (IOException ex) {
  69.             System.out.println(ex.getMessage());
  70.         }
  71.        
  72.     }
  73.     public static void main(String[] args) {
  74.             Server server = new Server();
  75.             server.run();
  76.  
  77.     }
  78.    
  79. }
  80.  
  81. //Interface
  82. package pkg;
  83.  
  84. import java.io.BufferedReader;
  85. import java.io.IOException;
  86. import java.io.InputStreamReader;
  87. import java.io.PrintWriter;
  88. import java.net.Socket;
  89. import java.util.ArrayList;
  90. import java.util.logging.Level;
  91. import java.util.logging.Logger;
  92.  
  93.  
  94. public class Interface implements Runnable{
  95.     private Socket client;
  96.     private BufferedReader in;
  97.     private PrintWriter out;
  98.     private SistemaLeiloes sistema;
  99.    
  100.    
  101.    
  102.    
  103.    
  104.     public Interface(Socket client, SistemaLeiloes sistema) throws IOException{
  105.         this.client=client;
  106.         this.in= new BufferedReader(new InputStreamReader(client.getInputStream()));
  107.         this.out= new PrintWriter(client.getOutputStream(),true);
  108.         this.sistema=sistema;
  109.     }
  110.      
  111.      
  112.      
  113.     @SuppressWarnings("empty-statement")
  114.      public boolean handle() throws IOException, InterruptedException, InvalidId, LicitacaoInvalida, NotAuthorized{
  115.         boolean flag=true;
  116.         User us;
  117.         us = null;
  118.         switch(in.readLine()){
  119.             case "1": String op, user, pass, nome;
  120.                              out.println("Introduza o seu username:");
  121.                              user=in.readLine();
  122.                              out.println("Introduza a sua password:");
  123.                              pass=in.readLine();
  124.                              out.println("Introduza a sua nome:");
  125.                              nome=in.readLine();
  126.                              out.println("Utilizador registado! Selecione nova opção.");
  127.                              sistema.addUser(new User(user,pass,nome));
  128.                              
  129.                              break;
  130.            
  131.             case "2":  String u, p, orig, dest;
  132.                            out.println("Introduza o seu username:");
  133.                            u=in.readLine();
  134.                            out.println("Introduza a sua password:");
  135.                            p=in.readLine();
  136.                            if(sistema.getUtilizadores().containsKey(u)){
  137.                              if(sistema.login(u, p)){
  138.                               us =sistema.getUser(u);
  139.                                out.println("Login efetuado! Bem-vindo " + us.getNome());
  140.                                while(loginMenu(us));
  141.                              }
  142.                            }
  143.                            else out.println("Erro ao efetuar login! Selecione nova opção.");
  144.                            
  145.                            break;
  146.            
  147.             case "3": flag=false;
  148.                          if(us!=null)
  149.                                  sistema.logout(us.getUsername());
  150.                          out.println("Saiu do sistema");
  151.                          break;
  152.                          
  153.             default: out.println("Comando errado");
  154.         }
  155.         return flag;
  156.      }
  157.  
  158.  
  159.  
  160.     public boolean loginMenu(User u) throws IOException, InvalidId, LicitacaoInvalida, NotAuthorized{
  161.         boolean flag=true;
  162.            
  163.        //out.println("Login Menu:,1-Criar leilão,2-Listar todos os leilões,3-Listar leilões participados,4-Listar leilões criados,5-Listar leilões ganhos,6-Fazer licitação,7-Encerrar leilão,0-Logout ");
  164.        out.println("Login Menu:\n"
  165.                 +"1-Criar leilão\n"
  166.                 +"2-Listar todos os leilões\n"
  167.                 +"3-Listar leilões participados\n"
  168.                 +"4-Listar leilões criados\n"
  169.                 +"5-Listar leilões ganhos\n"
  170.                 +"6-Fazer licitação\n"
  171.                 +"7-Encerrar leilão\n"
  172.                 +"0-Logout ");
  173.        
  174.      
  175.         switch(in.readLine()){  
  176.            
  177.             case "1":   String nome,obs;
  178.                         float preco;
  179.                         int idLeilaoCriado;
  180.                         out.println("Inserir nome do objecto a leiloar:");
  181.                         nome=in.readLine();
  182.                         out.println("Inserir preco base do leilao:");
  183.                         preco= Float.parseFloat(in.readLine());
  184.                        // out.println("Inserir observacao do objecto (opcional)");
  185.                        // obs=in.readLine();
  186.                         Leilao res=sistema.criarLeilao(u.getNome(),nome,preco,"");
  187.                         new Thread((Runnable) res).start();
  188.                         break;
  189.             case "2":
  190.                         ArrayList<String> r = getIds(sistema.listarLeiloes(),true,u);
  191.                         imprimeLista(r);
  192.                         break;
  193.             case "3":
  194.                         imprimeLista(getIds(u.getLeiloesEmCurso(),false,u));
  195.                         break;
  196.             case "4":  
  197.                         imprimeLista(getIds(u.getLeiloesCriados(),false,u));
  198.                         break;
  199.             case "5":
  200.                         imprimeLista(getIds(u.getLeiloesGanhos(),false,u));
  201.                         break;
  202.             case "6":  
  203.                         Integer idLeilaoALicitar;
  204.                         float bid;
  205.                         out.println("Insira o id do leilao:");
  206.                         idLeilaoALicitar=Integer.parseInt(in.readLine());
  207.                         out.println("Insira o bid do leilao:");
  208.                         bid=Float.parseFloat(in.readLine());
  209.                         sistema.licitar(u.getUsername(), idLeilaoALicitar, bid);
  210.                         new Thread((Runnable) sistema.getLeiloes().get(idLeilaoALicitar)).start();
  211.                         break;
  212.             case "7":  
  213.                         int idLeilaoAEncerrar;
  214.                         String vencedor;
  215.                         out.println("Insira o id do leilao:");
  216.                         idLeilaoAEncerrar = Integer.parseInt(in.readLine());
  217.                         sistema.fecharLeilao(idLeilaoAEncerrar,u.getUsername());
  218.                         sistema.getLeiloes().get(idLeilaoAEncerrar).notifyAll();
  219.                         break;
  220.             case "0":  
  221.                         flag=false;
  222.                         break;
  223.             default:    out.println("Comando errado");
  224.                         in.readLine();
  225.             }
  226.         return flag;
  227.         }
  228.  
  229.  
  230.         public ArrayList<String> getIds(ArrayList<Integer> l,boolean all, User u){
  231.             ArrayList<String> res = new ArrayList<>();
  232.             StringBuilder s = new StringBuilder();
  233.             if(all){
  234.                 l.forEach(z->res.add(relacao(z, u, sistema.getLeiloes().get(z).clone())));
  235.             }
  236.             else{
  237.                 l.forEach(z->res.add(sistema.getLeiloes().get(z).clone().toString()));
  238.             }
  239.             return res;
  240.         }
  241.  
  242.         private String relacao(Integer id, User u, Leilao l){
  243.             StringBuilder sb = new StringBuilder();
  244.             sb.append(l.toString());
  245.             if (u.criouLeilao(id)) {
  246.                 sb.append(" *");
  247.             }
  248.             else if (l.getTopBider().equals(u.getUsername())){
  249.                 sb.append(" +");
  250.             }
  251.             else if(!(l.isOpen())){
  252.                 sb.append(" x");
  253.             }
  254.             else if (u.estaAParticipar(id)){
  255.                 sb.append(" !");
  256.             }
  257.             return sb.toString();
  258.         }
  259.  
  260.         public void imprimeLista(ArrayList<String> lista) throws IOException{
  261.             int i,j,pags,lpag,op,exitf=1;
  262.             pags=lista.size()/10;
  263.             lpag=lista.size()%10;
  264.             if(lpag!=0) pags++;
  265.             if(pags==0){
  266.                 out.print('\u000C');
  267.                 out.println("Sem resultados");
  268.             }
  269.             for(i=0;i<pags && exitf!=0;){
  270.                 out.print('\u000C');
  271.                 out.println("Pagina " + (i+1) + "de " + pags);
  272.                 //out.println("Tempo:  " + tempo);
  273.                 for(j=i*10;j<i*10+10 && j<lista.size();j++){
  274.                     out.println(lista.get(j));
  275.                 }
  276.                 System.out.println("1 - Proxima pagina. \t 2 - Pagina anterior. \t 0 - Sair");
  277.                 op=Integer.parseInt(in.readLine());
  278.                 switch(op){
  279.                     case 0: exitf=0;
  280.                             break;
  281.                     case 1: if(i<pags){
  282.                             i++;
  283.                             }
  284.                             break;
  285.                     case 2: if(i>0){
  286.                             i--;
  287.                             }
  288.                             break;
  289.                     }
  290.             }  
  291.         }
  292.    
  293.  
  294.  
  295.  
  296.     @SuppressWarnings("empty-statement")
  297.     @Override
  298.     public void run() {
  299.         try {
  300.             while(handle());
  301.         } catch (IOException | InterruptedException | InvalidId | LicitacaoInvalida | NotAuthorized ex) {
  302.             Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
  303.         }
  304.         try {
  305.             this.in.close();
  306.         } catch (IOException ex) {
  307.             Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
  308.         }
  309.         this.out.close();
  310.     }
  311. }
  312.    
  313. //SistemaLeiloes
  314. package pkg;
  315.  
  316. import java.util.ArrayList;
  317. import java.util.HashMap;
  318. import java.util.concurrent.locks.Lock;
  319. import java.util.concurrent.locks.ReentrantLock;
  320.  
  321.  
  322.  
  323.  
  324. public class SistemaLeiloes{
  325.     private HashMap<Integer, Leilao> leiloes;
  326.     private HashMap<String, User> users;
  327.     private Lock mutex;
  328.  
  329.  
  330.  
  331.     public SistemaLeiloes(){
  332.         leiloes = new HashMap<>();
  333.         users = new HashMap<>();
  334.                 mutex= new ReentrantLock();
  335.     }
  336.  
  337.  
  338.     public void licitar (String username, Integer idLeilao, float bid) throws InvalidId, LicitacaoInvalida{
  339.         Leilao leilao= leiloes.get(idLeilao);
  340.         if (leilao==null) throw new InvalidId();
  341.         if (!(leilao.isOpen() && (leilao.getPrecoLeilao()<bid)) && leilao.getTopBider().equals(username)){
  342.             throw new LicitacaoInvalida();
  343.         }
  344.         mutex.lock();
  345.         try{      
  346.             if (leilao.isOpen() && (leilao.getPrecoLeilao()<bid) && !(leilao.getTopBider().equals(username))){
  347.                 leilao.setTopBider(username);
  348.                 leilao.setPrecoLeilao(bid);
  349.                 leilao.setTopBider(username);
  350.                 User u = users.get(username);
  351.                 if(!(u.estaAParticipar(idLeilao))){
  352.                     u.entrarLeilao(idLeilao);
  353.                 }              
  354.             }
  355.         }
  356.         finally{
  357.         mutex.unlock();
  358.         }      
  359.     }
  360.  
  361.     public Leilao criarLeilao(String user, String obj, float preco, String obs){
  362.         mutex.lock();
  363.         try{
  364.             Leilao novo = new Leilao(obj,preco,preco,true,"",obs);
  365.             int id = leiloes.size();
  366.             leiloes.put(id,novo);
  367.             users.get(user).createLeilao(id);
  368.                 return novo;
  369.         }
  370.         finally{
  371.             mutex.unlock();
  372.         }
  373.     }
  374.  
  375.  
  376.     public void fecharLeilao(int id, String user) throws InvalidId, NotAuthorized{
  377.         if(!(this.leiloes.containsKey(id))){
  378.             throw new InvalidId();
  379.         }
  380.         if(!(users.get(user).criouLeilao(id))) throw new NotAuthorized();
  381.         mutex.lock();
  382.         try{
  383.             Leilao l = this.leiloes.get(id);
  384.             l.setOpen(false);
  385.         }
  386.         finally{
  387.         mutex.unlock();
  388.         }
  389.  
  390.     }
  391.     public HashMap<Integer, Leilao> getLeiloes() {
  392.         return leiloes;
  393.     }
  394.  
  395.     public HashMap<String, User> getUtilizadores() {
  396.         return users;
  397.     }
  398.  
  399.     public void setUtilizadores(HashMap<String, User> utilizadores) {
  400.         this.users = utilizadores;
  401.     }
  402.    
  403.     public void addUser(User u){
  404.         mutex.lock();
  405.         try{
  406.             this.users.put(u.getUsername(),u.clone());
  407.         }finally{
  408.             mutex.unlock();
  409.         }
  410.     }
  411.    
  412.    
  413.     public boolean login(String username, String password){
  414.         mutex.lock();
  415.         try{
  416.             boolean res=false;
  417.             if(this.users.containsKey(username)){
  418.                 if(this.users.get(username).getPassword().equals(password)){
  419.                     this.users.get(username).setLogged(true);
  420.                     res= true;
  421.                 }
  422.             }
  423.             return res;
  424.         }finally{
  425.             mutex.unlock();
  426.         }
  427.     }
  428.    
  429.     public void logout(String username){
  430.         mutex.lock();
  431.         try{
  432.         this.users.get(username).setLogged(false);
  433.         }
  434.         finally{
  435.             mutex.unlock();
  436.         }
  437.     }
  438.    
  439.     public User getUser(String username){
  440.         return this.users.get(username);
  441.     }
  442.  
  443.    
  444.     public ArrayList<Integer> listarLeiloes(){
  445.         ArrayList<Integer> res = new ArrayList<>();
  446.         leiloes.forEach((k,v)->res.add(k));
  447.         return res;
  448.     }
  449.  
  450.  
  451.  
  452.  
  453. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement