Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Cliente
- package pkg;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class Client {
- public static void main(String[] args) {
- try {
- BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
- Socket c = new Socket ("localhost", 1026);
- BufferedReader in = new BufferedReader (new InputStreamReader (c.getInputStream ()));
- PrintWriter out = new PrintWriter (c.getOutputStream (), true);
- System.out.println("Conecção ao servidor efetuada.\n"
- + "Bem-vindo!\n"
- + "----------------------------------------------------------------------------\n"
- + "Escolha uma opção:\n1) Registar\n2) Efetuar Login\n3) Sair\n");
- String s,response;
- response="";
- while (!response.equals("Saiu do sistema")) {
- s = keyboard.readLine ();
- out.println (s);
- response = in.readLine();
- System.out.println (response);
- }
- }
- catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- }
- //Servidor
- package pkg;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Server implements Runnable{
- private SistemaLeiloes sistema;
- public Server(SistemaLeiloes sys){
- this.sistema=sys;
- }
- public Server (){
- this.sistema=new SistemaLeiloes();
- User userteste = new User ();
- this.sistema.addUser(userteste);
- }
- public void run(){
- try {
- ServerSocket s = new ServerSocket(1026);
- Socket client;
- System.out.println("Server is operational.");
- while (true) {
- client = s.accept ();
- System.out.println("Cliente ligado.");
- Thread t = new Thread((Runnable) new Interface(client,sistema));
- t.start();
- }
- } catch (IOException ex) {
- System.out.println(ex.getMessage());
- }
- }
- public static void main(String[] args) {
- Server server = new Server();
- server.run();
- }
- }
- //Interface
- package pkg;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class Interface implements Runnable{
- private Socket client;
- private BufferedReader in;
- private PrintWriter out;
- private SistemaLeiloes sistema;
- public Interface(Socket client, SistemaLeiloes sistema) throws IOException{
- this.client=client;
- this.in= new BufferedReader(new InputStreamReader(client.getInputStream()));
- this.out= new PrintWriter(client.getOutputStream(),true);
- this.sistema=sistema;
- }
- @SuppressWarnings("empty-statement")
- public boolean handle() throws IOException, InterruptedException, InvalidId, LicitacaoInvalida, NotAuthorized{
- boolean flag=true;
- User us;
- us = null;
- switch(in.readLine()){
- case "1": String op, user, pass, nome;
- out.println("Introduza o seu username:");
- user=in.readLine();
- out.println("Introduza a sua password:");
- pass=in.readLine();
- out.println("Introduza a sua nome:");
- nome=in.readLine();
- out.println("Utilizador registado! Selecione nova opção.");
- sistema.addUser(new User(user,pass,nome));
- break;
- case "2": String u, p, orig, dest;
- out.println("Introduza o seu username:");
- u=in.readLine();
- out.println("Introduza a sua password:");
- p=in.readLine();
- if(sistema.getUtilizadores().containsKey(u)){
- if(sistema.login(u, p)){
- us =sistema.getUser(u);
- out.println("Login efetuado! Bem-vindo " + us.getNome());
- while(loginMenu(us));
- }
- }
- else out.println("Erro ao efetuar login! Selecione nova opção.");
- break;
- case "3": flag=false;
- if(us!=null)
- sistema.logout(us.getUsername());
- out.println("Saiu do sistema");
- break;
- default: out.println("Comando errado");
- }
- return flag;
- }
- public boolean loginMenu(User u) throws IOException, InvalidId, LicitacaoInvalida, NotAuthorized{
- boolean flag=true;
- //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 ");
- out.println("Login Menu:\n"
- +"1-Criar leilão\n"
- +"2-Listar todos os leilões\n"
- +"3-Listar leilões participados\n"
- +"4-Listar leilões criados\n"
- +"5-Listar leilões ganhos\n"
- +"6-Fazer licitação\n"
- +"7-Encerrar leilão\n"
- +"0-Logout ");
- switch(in.readLine()){
- case "1": String nome,obs;
- float preco;
- int idLeilaoCriado;
- out.println("Inserir nome do objecto a leiloar:");
- nome=in.readLine();
- out.println("Inserir preco base do leilao:");
- preco= Float.parseFloat(in.readLine());
- // out.println("Inserir observacao do objecto (opcional)");
- // obs=in.readLine();
- Leilao res=sistema.criarLeilao(u.getNome(),nome,preco,"");
- new Thread((Runnable) res).start();
- break;
- case "2":
- ArrayList<String> r = getIds(sistema.listarLeiloes(),true,u);
- imprimeLista(r);
- break;
- case "3":
- imprimeLista(getIds(u.getLeiloesEmCurso(),false,u));
- break;
- case "4":
- imprimeLista(getIds(u.getLeiloesCriados(),false,u));
- break;
- case "5":
- imprimeLista(getIds(u.getLeiloesGanhos(),false,u));
- break;
- case "6":
- Integer idLeilaoALicitar;
- float bid;
- out.println("Insira o id do leilao:");
- idLeilaoALicitar=Integer.parseInt(in.readLine());
- out.println("Insira o bid do leilao:");
- bid=Float.parseFloat(in.readLine());
- sistema.licitar(u.getUsername(), idLeilaoALicitar, bid);
- new Thread((Runnable) sistema.getLeiloes().get(idLeilaoALicitar)).start();
- break;
- case "7":
- int idLeilaoAEncerrar;
- String vencedor;
- out.println("Insira o id do leilao:");
- idLeilaoAEncerrar = Integer.parseInt(in.readLine());
- sistema.fecharLeilao(idLeilaoAEncerrar,u.getUsername());
- sistema.getLeiloes().get(idLeilaoAEncerrar).notifyAll();
- break;
- case "0":
- flag=false;
- break;
- default: out.println("Comando errado");
- in.readLine();
- }
- return flag;
- }
- public ArrayList<String> getIds(ArrayList<Integer> l,boolean all, User u){
- ArrayList<String> res = new ArrayList<>();
- StringBuilder s = new StringBuilder();
- if(all){
- l.forEach(z->res.add(relacao(z, u, sistema.getLeiloes().get(z).clone())));
- }
- else{
- l.forEach(z->res.add(sistema.getLeiloes().get(z).clone().toString()));
- }
- return res;
- }
- private String relacao(Integer id, User u, Leilao l){
- StringBuilder sb = new StringBuilder();
- sb.append(l.toString());
- if (u.criouLeilao(id)) {
- sb.append(" *");
- }
- else if (l.getTopBider().equals(u.getUsername())){
- sb.append(" +");
- }
- else if(!(l.isOpen())){
- sb.append(" x");
- }
- else if (u.estaAParticipar(id)){
- sb.append(" !");
- }
- return sb.toString();
- }
- public void imprimeLista(ArrayList<String> lista) throws IOException{
- int i,j,pags,lpag,op,exitf=1;
- pags=lista.size()/10;
- lpag=lista.size()%10;
- if(lpag!=0) pags++;
- if(pags==0){
- out.print('\u000C');
- out.println("Sem resultados");
- }
- for(i=0;i<pags && exitf!=0;){
- out.print('\u000C');
- out.println("Pagina " + (i+1) + "de " + pags);
- //out.println("Tempo: " + tempo);
- for(j=i*10;j<i*10+10 && j<lista.size();j++){
- out.println(lista.get(j));
- }
- System.out.println("1 - Proxima pagina. \t 2 - Pagina anterior. \t 0 - Sair");
- op=Integer.parseInt(in.readLine());
- switch(op){
- case 0: exitf=0;
- break;
- case 1: if(i<pags){
- i++;
- }
- break;
- case 2: if(i>0){
- i--;
- }
- break;
- }
- }
- }
- @SuppressWarnings("empty-statement")
- @Override
- public void run() {
- try {
- while(handle());
- } catch (IOException | InterruptedException | InvalidId | LicitacaoInvalida | NotAuthorized ex) {
- Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
- }
- try {
- this.in.close();
- } catch (IOException ex) {
- Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
- }
- this.out.close();
- }
- }
- //SistemaLeiloes
- package pkg;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class SistemaLeiloes{
- private HashMap<Integer, Leilao> leiloes;
- private HashMap<String, User> users;
- private Lock mutex;
- public SistemaLeiloes(){
- leiloes = new HashMap<>();
- users = new HashMap<>();
- mutex= new ReentrantLock();
- }
- public void licitar (String username, Integer idLeilao, float bid) throws InvalidId, LicitacaoInvalida{
- Leilao leilao= leiloes.get(idLeilao);
- if (leilao==null) throw new InvalidId();
- if (!(leilao.isOpen() && (leilao.getPrecoLeilao()<bid)) && leilao.getTopBider().equals(username)){
- throw new LicitacaoInvalida();
- }
- mutex.lock();
- try{
- if (leilao.isOpen() && (leilao.getPrecoLeilao()<bid) && !(leilao.getTopBider().equals(username))){
- leilao.setTopBider(username);
- leilao.setPrecoLeilao(bid);
- leilao.setTopBider(username);
- User u = users.get(username);
- if(!(u.estaAParticipar(idLeilao))){
- u.entrarLeilao(idLeilao);
- }
- }
- }
- finally{
- mutex.unlock();
- }
- }
- public Leilao criarLeilao(String user, String obj, float preco, String obs){
- mutex.lock();
- try{
- Leilao novo = new Leilao(obj,preco,preco,true,"",obs);
- int id = leiloes.size();
- leiloes.put(id,novo);
- users.get(user).createLeilao(id);
- return novo;
- }
- finally{
- mutex.unlock();
- }
- }
- public void fecharLeilao(int id, String user) throws InvalidId, NotAuthorized{
- if(!(this.leiloes.containsKey(id))){
- throw new InvalidId();
- }
- if(!(users.get(user).criouLeilao(id))) throw new NotAuthorized();
- mutex.lock();
- try{
- Leilao l = this.leiloes.get(id);
- l.setOpen(false);
- }
- finally{
- mutex.unlock();
- }
- }
- public HashMap<Integer, Leilao> getLeiloes() {
- return leiloes;
- }
- public HashMap<String, User> getUtilizadores() {
- return users;
- }
- public void setUtilizadores(HashMap<String, User> utilizadores) {
- this.users = utilizadores;
- }
- public void addUser(User u){
- mutex.lock();
- try{
- this.users.put(u.getUsername(),u.clone());
- }finally{
- mutex.unlock();
- }
- }
- public boolean login(String username, String password){
- mutex.lock();
- try{
- boolean res=false;
- if(this.users.containsKey(username)){
- if(this.users.get(username).getPassword().equals(password)){
- this.users.get(username).setLogged(true);
- res= true;
- }
- }
- return res;
- }finally{
- mutex.unlock();
- }
- }
- public void logout(String username){
- mutex.lock();
- try{
- this.users.get(username).setLogged(false);
- }
- finally{
- mutex.unlock();
- }
- }
- public User getUser(String username){
- return this.users.get(username);
- }
- public ArrayList<Integer> listarLeiloes(){
- ArrayList<Integer> res = new ArrayList<>();
- leiloes.forEach((k,v)->res.add(k));
- return res;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement