Advertisement
Guest User

Untitled

a guest
Feb 4th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.96 KB | None | 0 0
  1.  
  2. // *********************************************************************
  3. // *********************** ESERCIZIO CIMINO ****************************
  4. // *********************************************************************
  5.  
  6.  
  7. // *********************************************************************
  8. // *********************************************************************
  9.  
  10. //XXXXXXXXXXXXXXXXXXXXXXX TIPOLOGIA SERVER ANELLO XXXXXXXXXXXXXXXXXXXXXX
  11.  
  12.  
  13.  
  14. // *********************FUNZIONE INVIA (SOCKET)*************************
  15.  
  16. // CASO NON SERIALIZABLE (HO IL METODO ToString() E il cotruttore X(String Xml)
  17.  
  18. public static void invia(int portaInvio, Domanda c){
  19.         try( Socket s = new Socket( "localhost" , portaInvio);
  20.             DataOutputStream dos = new DataOutputStream (s.getOutputStream());
  21.         ){  
  22.             dos.writeUTF(c.toString());
  23.         }catch(IOException e){ e.printStackTrace(); }
  24.         visualizzaSulLog("Invia", c.toString());
  25.     }
  26.  
  27.  
  28. // CASO SERIALIZABLE
  29.  
  30.     public static void inviaProposta(int porta, Proposta pr){
  31.         try ( Socket s = new Socket( "localhost" , porta);
  32.         ObjectOutputStream oout = new ObjectOutputStream (s.getOutputStream());
  33.         ) { oout.writeObject( pr );
  34.         } catch (IOException e) { e.printStackTrace(); }
  35.     }
  36.  
  37. // *********************FUNZIONE RICEVI (SOCKET)***************************
  38.  
  39. // CASO NON SERIALIZABLE
  40.  
  41.     public static Domanda ricevi(){
  42.         Domanda d = null;
  43.         try( ServerSocket servs = new ServerSocket(portaRicezione);
  44.              Socket s = servs.accept();
  45.              DataInputStream dis = new DataInputStream(s.getInputStream());
  46.            ){
  47.             d = new Domanda(dis.readUTF()); //inizializzazione fatta con il costruttore
  48.             visualizzaSulLog("Ricevi",d.toString());
  49.         } catch(IOException e){ e.printStackTrace(); }
  50.         return d;    
  51.     }
  52.  
  53.  
  54. // CASO SERIALIZABLE
  55.  
  56.     public static Proposta riceviProposta(int porta){
  57.         Proposta result = null;
  58.         try ( ServerSocket servs = new ServerSocket(porta); // (02)
  59.         Socket s = servs.accept(); // (03)
  60.         ) { ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
  61.             result = ( Proposta ) oin.readObject(); //Notare il convertitore esplicito
  62.         } catch (IOException e) {e.printStackTrace();}
  63.         return result;
  64.     }
  65.  
  66.  
  67. // *********************FUNZIONE STAMPA SU LOG***************************
  68.  
  69.         //E' UN INSERIMENTO IN UNA TABELLA LOG CON PREPARED STATEMENT
  70.  
  71.         public static void visualizzaSulLog(String operazione, String risultato){
  72.         try ( Connection co = DriverManager.getConnection("jdbc:mysql://localhost:3306/banca", "root","");
  73.         PreparedStatement ps = co.prepareStatement("INSERT INTO opinionista.log VALUES (?, ?, ?)"); //10
  74.         ){
  75.             ps.setInt(1,portaRicezione);
  76.             ps.setString(2,operazione);
  77.             ps.setString(3,risultato);
  78.             ps.executeUpdate();
  79.         }catch(SQLException e) { System.err.println(e.getMessage()); }
  80.     }
  81.  
  82.  
  83. // *********************************************************************
  84. // *********************************************************************
  85.  
  86. // XXXXXXXXXXXXXXXXXXXXXXX TIPOLOGIA TABLEVIEW XXXXXXXXXXXXXXXXXXXXXXXXX
  87.  
  88. // CLASSE BEAN
  89.  
  90.     // * USARE SimpleStringProperty
  91.     // * nel costruttore new SimpleStringProperty(String s) (ESEMPIO)
  92.     // * Inserire metodi get()
  93.  
  94. // CLASSE TABELLA (ESTENDE TABLEVIEW)
  95.  
  96.  
  97.     // A seguire tutti i passaggi da fare nel costruttore
  98.     // * Creare le colonne
  99.  
  100.     TableColumn emailCol = new TableColumn("EMAIL");
  101.     TableColumn depositoCol = new TableColumn("DEPOSITO");
  102.  
  103.     // * Associare ad ogni colonna la sua rispettiva colonna del dbms
  104.  
  105.     emailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
  106.     depositoCol.setCellValueFactory(new PropertyValueFactory<>("deposito"));
  107.  
  108.     // * Inizializza la observableList
  109.  
  110.     listaOsservabileClienti = FXCollections.observableArrayList();
  111.  
  112.     // * Impostala come lista per la tableView
  113.  
  114.     setItems(listaOsservabileClienti);
  115.  
  116.     // * Aggiungi le colonne alla tabella
  117.  
  118.     getColumns().addAll(emailCol, depositoCol);
  119.  
  120.  
  121. //Classe GestoreDBMS
  122.  
  123.     //Per ogni metodo devo stabilire una connessione e fare uno statement
  124.     //Può essere fatta in un metodo direttamente o nella classe stessa tramite un
  125.     //blocco static. Nel secondo caso non devo farla di nuovo nei metodi
  126.  
  127.     try(
  128.     Connection co = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root","");
  129.     PreparedStatement ps = co.prepareStatement("SELECT email,deposito FROM depositoclienti WHERE deposito > ? ");
  130.     ) {
  131.         //Blocco interno
  132.     }
  133.     catch(SQLException e){ System.err.println(e.getMessage());
  134.      }
  135.  
  136.     // Le prossime istruzioni sono da inserire nel blocco interno
  137.     // settare eventuali parametri del PreparedStatement
  138.  
  139.     ps.setInt(1,depositoMinimo);
  140.  
  141.     // Se ho bisogno di prendere il result set della query uso
  142.  
  143.     ResultSet rs = ps.executeQuery();
  144.        while (rs.next())
  145.        listaClienti.add(new Cliente(rs.getString("email"), rs.getInt("deposito")));
  146.  
  147.     // Altrimenti eseguo solo la query
  148.  
  149.     ps.executeQuery();  // query di selezione
  150.     ps.executeUpdate(); //in caso di inserimenti/update/rimozioni
  151.  
  152. // Classe Main (estende Application)
  153.  
  154.     //I prossimi passaggi sono da inserire nel metodo start()
  155.  
  156.     //Inserire tutto in una vbox, sia la tableview che eventuali label
  157.     //o inputText
  158.  
  159.     VBox vbox = new VBox();
  160.     vbox.getChildren().addAll(tabellaVisuale,campoDepositoMinimo,labelDepositoMinimo);
  161.  
  162.     //Inserire eventuali eventi in questo modo
  163.  
  164.     bottoneSettaDeposito.setOnAction((ActionEvent ev) -> {
  165.             depositoMinimo = Integer.parseInt(campoDepositoMinimo.getText());
  166.             tabellaVisuale.aggiornaListaClienti( DataBaseDepositiClienti.CaricaClientiConDepositoMinimo(depositoMinimo));
  167.     });
  168.  
  169.     //Setting Stage
  170.  
  171.     Scene scene = new Scene(new Group(vbox));
  172.        
  173.         stage.setTitle("Depositi Bancari");
  174.         stage.setScene(scene);
  175.         stage.show();
  176.  
  177. // *********************************************************************
  178. // *********************************************************************
  179.  
  180. // XXXXXXXXXXXXXXXXXXXXXXX TIPOLOGIA PCLIST XXXXXXXXXXXXXXXXXXXXXXXXX
  181.  
  182.    //Classe PCStatement
  183.  
  184.     public class PCStatement {
  185.     public final int senderPort;
  186.     public final String statement;
  187.     public final double item;
  188.    
  189.     public PCStatement(int sp, String st, double it){
  190.         senderPort = sp;
  191.         statement = st;
  192.         item = it;
  193.     }
  194. }
  195.  
  196.  
  197.     //Classe PCList (Contiene il main)
  198.  
  199. public class PCList {
  200.    
  201.     private static int receivePort;
  202.     private static int sendPort;
  203.  
  204.     //Configura le variabili di PCList (tramite gli args del main)
  205.    
  206.     public static void configure(int rp, int sp){
  207.         receivePort = rp;
  208.         sendPort = sp;
  209.     }
  210.  
  211.     //Funzione invio classica (non serializable)
  212.    
  213.     public static void send(PCStatement o){
  214.         try(
  215.            Socket s = new Socket("localhost",sendPort);
  216.            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
  217.         ){
  218.             dos.writeUTF( (new XStream()).toXML(o));
  219.         }catch(IOException e) { e.printStackTrace(); }
  220.         System.out.println("- invio a" + sendPort);
  221.     }
  222.  
  223.     //Funzione ricevi classica (non serializable)
  224.    
  225.     public static PCStatement receive(){
  226.         PCStatement p = null;
  227.         try(
  228.           ServerSocket servs = new ServerSocket(receivePort);
  229.           Socket s = servs.accept();
  230.           DataInputStream dis = new DataInputStream(s.getInputStream());
  231.         ){
  232.           p = (PCStatement)  (new XStream()).fromXML(dis.readUTF());
  233.         }catch(IOException e) { e.printStackTrace();}
  234.         System.out.println("- ricevo");
  235.         return p;
  236.     }
  237.  
  238.     // Preleva una stringa xml dal db (di un record) e la converte in arraylist
  239.     // Devo convertire la stringa in xml in un arraylist tramite XStream
  240.     // Notare il convertitore esplicito
  241.    
  242.     public static ArrayList read(){
  243.         try(
  244.            Connection co = DriverManager.getConnection("jdbc:mysql://localhost:3306/pclist","root", "");
  245.            PreparedStatement ps = co.prepareStatement("SELECT xmlarraylist FROM pclist WHERE receiveport = ? ");    
  246.         ){
  247.             ps.setInt(1, receivePort);
  248.             ResultSet rs = ps.executeQuery();
  249.             if(rs.next()){
  250.                 return (ArrayList) (new XStream()).fromXML(rs.getString("xmlarraylist"));
  251.             }
  252.         }catch(SQLException e){ System.err.println(e.getMessage()); }
  253.         return null;
  254.     }
  255.  
  256.     //Aggiorna un record stringa xml del database con un arraylist
  257.     //L'arraylist va convertita in una stringa xml tramite XStream
  258.    
  259.     public static void write(ArrayList al){
  260.         try(
  261.            Connection co = DriverManager.getConnection("jdbc:mysql://localhost:3306/pclist","root", "");
  262.            PreparedStatement ps = co.prepareStatement("UPDATE pclist SET xmlarraylist = ? WHERE receiveport = ? ");
  263.         ){
  264.          String x = (new XStream()).toXML(al);
  265.          ps.setString(1, x); ps.setInt(2, receivePort);
  266.          ps.executeUpdate();
  267.         }catch(SQLException e){ System.err.println(e.getMessage()); }
  268.     }
  269.  
  270.     //Funzione Create come da testo
  271.     //ricevo solo nel caso in cui ritorno alla "radice"
  272.    
  273.     public static void create(PCStatement o){
  274.         write(new ArrayList<>());
  275.         System.out.println( (new XStream()).toXML(o) + "\n Creato \n" + read());
  276.         send(o);
  277.         if(o.senderPort == receivePort){ receive(); }
  278.     }
  279.    
  280.     //Funzione Create come da testo
  281.     //Tutte le volte che altero in qualche modo la mia arraylist devo fare write()
  282.     //Invio e ricevo in caso non sono la lista minima
  283.  
  284.     public static void add(PCStatement o){
  285.         ArrayList al = read();
  286.         int dimensioneDesiderata = 0;
  287.         while(al.size() > dimensioneDesiderata){
  288.             send(o);
  289.             o = receive();
  290.             dimensioneDesiderata++;
  291.         }
  292.         al.add(o.item);
  293.         write(al);
  294.         System.out.println( (new XStream()).toXML(o) + " Aggiunto" + read());
  295.     }
  296.    
  297.  
  298.     //Rimuovo un elemento dalla lista
  299.     //Se non lo trovo invio a quello dopo, ricevo solo se ritorno alla "radice"
  300.     //Tutte le volte che aggiorno l'arraylist devo fare la write;
  301.  
  302.     public static void remove(PCStatement o){
  303.         ArrayList al = read();
  304.         if(!al.remove(o.item)){
  305.             send(o);
  306.             if(o.senderPort == receivePort) receive();
  307.         } else{
  308.           write(al);
  309.           System.out.println( (new XStream()).toXML(o) + " \n Rimosso \n" + read());  
  310.         }
  311.        
  312.     }
  313.  
  314.     //Funzione Main
  315.     //Controllo se ho uno statement e nel caso lo creo (args.length > 2)
  316.     //altrimenti lo riceverò da qualcun'altro.
  317.     //In base alla stringa "statement" vedo che funzione svolgere
  318.  
  319.     public static void main(String[] args) {
  320.         PCStatement p;
  321.         configure(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
  322.         if(args.length > 2) p = new PCStatement(Integer.parseInt(args[0]),args[2], Double.parseDouble(args[3]));
  323.         else p = receive();
  324.         switch (p.statement){
  325.             case "create": create(p); break;
  326.             case "add": add(p); break;
  327.             case "remove": remove(p); break;
  328.         }
  329.     }
  330.    
  331. }
  332.  
  333. // *********************************************************************
  334. // *********************** ESERCIZIO VECCHIO ***************************
  335. // *********************************************************************
  336.  
  337.  
  338. // *********************************************************************
  339. // *********************************************************************
  340.  
  341.  
  342. //Creazione classe per le eccezioni;
  343.  
  344.   public class ElementoNonTrovatoException extends Exception {
  345.  
  346.   public ElementoNonTrovatoException() {
  347.     super();
  348.   }
  349.  
  350.   public ElementoNonTrovatoException(String m){
  351.     super(m);
  352.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement