Ordini1
Zipped source code [ServerPckg.zip]
Global.java
import java.io.*; import java.net.*; import java.util.*; /* * Il server Globale, è l'unico a comunicare direttamente * con il client. * Riceve le commisioni e le smista al server opportuno, * in base ad un dizionario. */ public class Global extends Server{ private Hashtable<String, Integer> portTable=null; private Cart cart=new Cart(); public Global(){ super(2899); createHT(); } /* * per questo server, la Hashtable, contiene le chiavi possibli * associate alla porta del server a cui dovrà riferirsi */ private void createHT(){ portTable=new Hashtable<String, Integer>(); portTable.put("margherita",2900); portTable.put("capricciosa",2900); portTable.put("birra",2900); portTable.put("coca",2900); portTable.put("pannolini",2901); } class Cart{ Cart(){ count=0; tot=0;} private String[] obj=new String[100]; private Double[] price=new Double[100]; private int[] quantity=new int[100]; public int count; public int tot; public int getTot() { return tot; } public String getObj(int i) { return obj[i]; } public Double getPrice(int i) { return price[i]; } public int getQuantity(int i) { return quantity[i]; } public void add(String o,Double p,int q) { this.obj[count] = o; this.price[count] = p; this.quantity[count] = q; count++; tot+=p; } } /* * Questo server accetta 4 tipi di stringhe: * STRINGA DI RICHIESTA PRODOTTO * <quantità> <nome> * STRINGA DI FINE ELENCO RICHIESTE * "conto" * STRINGA DI CONFERMA ORDINE * "confermo" * STRINGA DI ANNULLAMENTO ORDINE * "annulla" */ private static final int CODE_CONTO=94844797;//HashCode calcolato mediate il metodo della classa String private static final int CODE_CONFERMO=-580247515; private static final int CODE_ANNULLA=-852069459; protected String execute(String str){ //confronta la stringa con le 3 stringhe di comando switch (str.toLowerCase().hashCode()) { case CODE_CONTO: try { return conto(); } catch (IOException e1) { e1.printStackTrace(); } case CODE_CONFERMO: return "Provvederemo al più presto"; case CODE_ANNULLA: cart=new Cart(); return "Richieste annullate"; } if(validate(str)){ Double i=null; try { i = getPrice(str); } catch (UnknownHostException e) { //e.printStackTrace(); } catch (IOException e) {// e.printStackTrace(); } if(i!=null&&i>0) cart.add(elem(str), i, value(str)); else return str+" non disponibile"; return str+" confermata. COSTO: "+i+"€"; } else return "La richiesta "+str+" non è valida!"; } private String conto() throws IOException { if(cart.count>0){ sendMsg("<Prodotto><Quantità><Prezzo>"); for(int i=0;i<cart.count;i++){ sendMsg("> "+ cart.getObj(i)+" "+ cart.getQuantity(i)+" "+ cart.getPrice(i)+"€"); } sendMsg("TOTALE: "+cart.getTot()+"€"); return "Confermare l'ordine?(conferma/annulla)"; } return "Richiesta non valida"; } private Double getPrice(String str) throws UnknownHostException, IOException { int q=value(str); Socket S=new Socket("localhost",portTable.get(elem(str))); BufferedReader fromS=new BufferedReader(new InputStreamReader(S.getInputStream())); PrintWriter toS=new PrintWriter(S.getOutputStream(),true); toS.println(str); str=null; while((str=fromS.readLine())==null); Double a=null; return a.parseDouble(str)*q; } /* * per questo server, la stringa nn è valida, se non è una di quelle possibili * da associare ad una porta(vede dizionario) */ protected boolean validate(String str){ try{ boolean suitable=(portTable.get(elem(str))!=null);//è una parola valida return suitable && value(str)>0;//ha una quantità valida } catch(Exception e){ return false; } } }
HostClient.java
import java.io.*; import java.net.*; public class HostClient { static BufferedReader in; static PrintStream out; /** * @param args * @throws IOException * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException, IOException { /*vengono istanziati gli oggetti delle classi, * che simulano i tre server */ Global gServ=new Global(); Pizza pServ=new Pizza(); Shop sServ=new Shop(); gServ.start(); pServ.start(); sServ.start(); /* * Per creare una applicazione client leggera, * dato che da traccia è specificato che girerà su * PDA, il client non fà altro che: * 1 - Acquisire una stringa da input * 2 - Aprire una connessione con il server Globale * 3 - Inviare la stringa * 4 - Attendere una risposta * 5 - Ripetere le operazioni per eventuali altre comunicazioni tra client e server */ //Input da utente in=getInput(); //Output verso utente out=getOutput(); out.println("Inserisci le richieste."); out.println("Formato: <quantità> <prodotto>"); out.println("scrivi ''conto'' per terminare le richieste"); out.println("scrivi ''esci'' per uscire dal programma"); String str; do{ //1 str=in.readLine(); if(str.toLowerCase().equals("esci"))System.exit(0); //2 //Socket per la connessione con il serverG Socket s=new Socket("localhost",2899); //output da Socket PrintWriter toS=new PrintWriter(s.getOutputStream(),true); //3 toS.println(str.toLowerCase()); //4 //Input da Socket BufferedReader fromS=new BufferedReader(new InputStreamReader(s.getInputStream())); answers(fromS,out); }while(true); }//main /* * I metodi seguenti saranno utili per implementazioni future. * es. Adoperare un input vocale più che la console di testo * "Dirottare" l'output su altri canali quali file di log, ecc.. */ private static BufferedReader getInput(){ return new BufferedReader(new InputStreamReader(System.in)); } private static PrintStream getOutput() { return System.out; } /* * Questo metodo attende le risposte, * sottoforma di stringa/e, dal Server. */ public static void answers(BufferedReader in,PrintStream out) throws IOException{ String str=null; while((str=in.readLine())==null);//sino a quando non riceve una risposta do out.println(str); while(!(str=in.readLine()).equals("$END$"));//sino a quando ci sono risposte } }
Pizza.java
import java.util.Hashtable; public class Pizza extends Server{ private Hashtable<String, Double> prices=null; public Pizza(){ super(2900); createHT(); } @Override protected String execute(String str) { if(validate(str)) return prices.get(elem(str)).toString(); return "-1"; } @Override /* * Su questo Server, la funzione valdate, * dovrebbe simulare l'effettiva presenza dei materiali primi * e della disponibilità del pizzaiolo ad effettare la pizza. */ protected boolean validate(String str) { //codice da implementare return true; } private void createHT(){ prices=new Hashtable<String, Double>(); prices.put("margherita",3.0); prices.put("capricciosa",-1.0);//= non disponibile prices.put("birra",2.5); prices.put("coca",1.5); } }
Server.java
import java.io.*; import java.net.*; public abstract class Server extends Thread{ private int port; protected ServerSocket serverS=null; protected Socket S=null; public Server(int p){ try { port=p; serverS=new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } } public void run(){ while(true){ try { String str; //Server in ascolto sulla porta S=serverS.accept(); //System.out.println("Server su porta "+port+": mi è arrivata una richiesta"); //Stringa in arrivo... BufferedReader fromS=new BufferedReader(new InputStreamReader(S.getInputStream())); str=fromS.readLine(); //Elaborazione stringa str=execute(str); //Comunica risultati sendMsg(str); sendMsg("$END$"); //System.out.println("Server su porta "+port+": ho risposto"); } catch (IOException e) { e.printStackTrace(); } } } protected void sendMsg(String str) throws IOException { PrintWriter toS=new PrintWriter(S.getOutputStream(),true); toS.println(str); } protected abstract String execute(String str); protected abstract boolean validate(String str); public String elem(String s){ return s.substring(s.indexOf(' ',0)+1); } public int value(String s){ return Integer.valueOf(s.substring(0, s.indexOf(' ',0))); } }
Shop.java
import java.util.*; public class Shop extends Server{ public Shop(){ super(2901); createHT(); } private Hashtable<String, Integer> store=null; private Hashtable<String, Double> prices=null; @Override /* * invia il prezzo da pagare */ protected String execute(String str) { if(validate(str)) return prices.get(elem(str)).toString(); return "-1"; } @Override /* * ne verifica la disponibilità in magazzino */ protected boolean validate(String str) { return store.get(elem(str))>0; } private void createHT(){ store=new Hashtable<String, Integer>(); prices=new Hashtable<String, Double>(); prices.put("pannolini",4.0); store.put("pannolini",30); prices.put("tovaglioli",1.0); store.put("tovaglioli",-1);//= non disponibile prices.put("bicchieri",2.5); store.put("bicchieri",24); prices.put("detersivo",1.5); store.put("detersivo",50); } }