ioana_martin98

Untitled

Jun 7th, 2019
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.72 KB | None | 0 0
  1. package eu.ase.test;
  2.  
  3. //Mark 3:
  4.     // Create the interface ElectronicDevices with the method infoDevice() returning String, must be inserted
  5.  
  6. public interface ElectronicDevices {
  7.     public String infoDevice();
  8. }
  9. package eu.ase.test;
  10.  
  11. import java.io.Serializable;
  12.  
  13. //Mark 3:
  14. //a. Create public class Phone which must implement ElectronicDevice interface and It must be inserted 3 fields:
  15. //weight - float, diagonal - double, producer - String
  16. //b. for this class fields it is mandatory to implement getters and setters, plus the default constructor (without parameters),
  17. //there is NO constructor with parameters
  18. //c. override implementation for the infoDevice() method (from the ElectronicDevices interface) to return the producer String
  19. //d. the setters should throw Exception if the constraints are not fulfilled:
  20. //- producer different than null and producer String length greater than 1
  21. //- diagonal and weight greater than 0 each
  22. //e. Implements Serializable, Cloneable and Override the implementation for equals(), hashCode() and clone() methods
  23.  
  24.  
  25. public class Phone implements ElectronicDevices, Serializable, Cloneable {
  26.     /**
  27.      *
  28.      */
  29.     private static final long serialVersionUID = 1L;
  30.     private float weight;
  31.     private double diagonal;
  32.     private String producer;
  33.    
  34.     public Phone()
  35.     {
  36.         weight=0;
  37.         diagonal=0;
  38.         producer="";
  39.     }
  40.  
  41.     public float getWeight() {
  42.         return weight;
  43.     }
  44.  
  45.     public void setWeight(float weight) throws Exception {
  46.         if(weight>0)
  47.             this.weight = weight;
  48.         else throw new Exception();
  49.     }
  50.  
  51.     public double getDiagonal() {
  52.         return diagonal;
  53.     }
  54.  
  55.     public void setDiagonal(double diagonal) throws Exception {
  56.         if(diagonal>0)
  57.             this.diagonal = diagonal;
  58.         else throw new Exception();
  59.     }
  60.  
  61.     public String getProducer() {
  62.         return producer;
  63.     }
  64.  
  65.     public void setProducer(String producer) throws Exception {
  66.         if(producer!=null && producer.length()>1)
  67.             this.producer = producer;
  68.         else throw new Exception();
  69.     }
  70.  
  71.     @Override
  72.     public String infoDevice() {
  73.         return producer;
  74.     }
  75.  
  76.     @Override
  77.     public Object clone() throws CloneNotSupportedException {
  78.         return super.clone();
  79.     }
  80.  
  81.     @Override
  82.     public boolean equals(Object obj) {
  83.         if(obj instanceof Phone)
  84.         {
  85.             Phone p=(Phone)obj;
  86.             return this.weight==p.weight && this.diagonal==p.diagonal && this.producer.equals(p.producer);
  87.         }
  88.         else return false;
  89.     }
  90.  
  91.     @Override
  92.     public int hashCode() {
  93.         return super.hashCode();
  94.     }
  95.    
  96.    
  97.    
  98. }
  99.  
  100. package eu.ase.test;
  101.  
  102. //Mark 3:
  103. // a. create public class SmartPhone must inherit the Phone class and it adds the batteryDuration - int field
  104. // b. for this class fields it is mandatory to implement getters and setters
  105. // c. override virtual implementation for the infoDevice() method (from the ElectronicDevices interface and Phone implementation),
  106. //    to return the batteryDuration as a String
  107. // d. the setters should throw Exception if the constraints are not fulfilled:
  108. // - batteryDuration greater than 0
  109.  
  110. public class SmartPhone extends Phone{
  111.     /**
  112.      *
  113.      */
  114.     private static final long serialVersionUID = 1L;
  115.     private int batteryDuration;
  116.  
  117.     public int getBatteryDuration() {
  118.         return batteryDuration;
  119.     }
  120.  
  121.     public void setBatteryDuration(int batteryDuration) throws Exception {
  122.         if(batteryDuration>0)
  123.             this.batteryDuration = batteryDuration;
  124.         else throw new Exception();
  125.     }
  126.  
  127.     @Override
  128.     public String infoDevice() {
  129.         return ""+batteryDuration;
  130.     }
  131.    
  132.    
  133.    
  134. }
  135. package eu.ase.test;
  136.  
  137. import java.io.BufferedReader;
  138. import java.io.File;
  139. import java.io.FileInputStream;
  140. import java.io.FileNotFoundException;
  141. import java.io.FileOutputStream;
  142. import java.io.FileReader;
  143. import java.io.IOException;
  144. import java.io.ObjectInputStream;
  145. import java.io.ObjectOutputStream;
  146. import java.util.ArrayList;
  147. import java.util.List;
  148.  
  149. //Mark 4:
  150. // Create public class Utils which contains private static list field with interface as type: List<ElectronicDevices>
  151. // Insert the following methods:
  152. // a. public static List<ElectronicDevices> createPhones(int n) throws Exception - for creating an ArrayList of n elemnts
  153. //    which are containing n default Phone objects and it using the static field of the class (list)
  154. // b. public static List<ElectronicDevices> readPhones(String file)
  155. //    - for reading and parsing text files with string lines for creating Phone objects
  156. // (e.g. please see for example phonesList.txt file); first line is the weight in grams, second line is screen diagonal and third line is the producer
  157. //   hint: use RandomAccessFile and read / parse line by line (first is parsing for float - weight, second line is double - diagonal, third is String - producer)
  158. // c. public static void writeBinaryPhones(String file, List<ElectronicDevices> listP) - for writing binary the phones into the file
  159. //   hint: use FileOutputStream with FileOurputStream to serialized/save the Phone objects from the ArrayList of the phones objects
  160. // d. public static List<ElectronicDevices> readBinaryPhones(String file) - for reading binary the Phone objects from the file and creating the ArrayList
  161.  
  162. public class Utils {
  163.     private static List<ElectronicDevices> list;
  164.    
  165.     public static List<ElectronicDevices> createPhones(int n) throws Exception
  166.     {
  167.         if(n<=0) throw new Exception();
  168.         list=new ArrayList<ElectronicDevices>(n);
  169.         for(int i=0;i<n;i++)
  170.         {
  171.             list.add(new Phone());
  172.         }
  173.         return list;
  174.     }
  175.    
  176.     public static List<ElectronicDevices> readPhones(String file) throws Exception
  177.     {
  178.         if(new File(file).exists())
  179.         {
  180.             list.clear();
  181.             try {
  182.                 BufferedReader bf=new BufferedReader(new FileReader(file));
  183.                 String linie=null;
  184.                 while((linie=bf.readLine())!=null)
  185.                 {
  186.                     float weight=Float.parseFloat(linie);
  187.                     linie=bf.readLine();
  188.                     double diagonal=Double.parseDouble(linie);
  189.                     linie=bf.readLine();
  190.                     String producer=linie.toString();
  191.                    
  192.                     Phone p= new Phone();
  193.                     p.setWeight(weight);
  194.                     p.setDiagonal(diagonal);
  195.                     p.setProducer(producer);
  196.                    
  197.                     list.add(p);
  198.                 }
  199.                 bf.close();
  200.                 return list;
  201.             } catch (Exception e) {
  202.                 // TODO Auto-generated catch block
  203.                 e.printStackTrace();
  204.             }
  205.         }
  206.         throw new Exception();
  207.     }
  208.    
  209.     public static void writeBinaryPhones(String file, List<ElectronicDevices> listP) throws FileNotFoundException, IOException
  210.     {
  211.         ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
  212.         oos.writeObject(listP);
  213.         oos.close();
  214.     }
  215.    
  216.     public static List<ElectronicDevices> readBinaryPhones(String file) throws FileNotFoundException, IOException, ClassNotFoundException
  217.     {
  218.         ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
  219.         List<ElectronicDevices> lista=(List)(ois.readObject());
  220.         ois.close();
  221.         return lista;
  222.     }
  223. }
  224. package eu.ase.test;
  225.  
  226. import java.io.FileNotFoundException;
  227. import java.io.IOException;
  228. import java.util.List;
  229.  
  230. // Mark 5:
  231. //  a. create the class VectThread which implements Runnable and contains 2 fields:
  232. //  - phonesList with interface as type List<ElectronicDevices>
  233. //  - avgWeight is a real (double) number for storing the average weight of the phones list
  234. //  b. In the constructor read the file using readBinaryPhones static method from Utils
  235. //  c. provide get methods for the both fields (phoneList and avgweight) of the class  
  236. //  d. Within the override run method (with the signature in Runnable interface)
  237. //  - the developer should go through the phoneList and calculate the average of the weights from the phone list objects (Phone class - explicit cast)
  238.  
  239. public class VectThread implements Runnable {
  240.     private List<ElectronicDevices> phonesList;
  241.     private double avgWeight;
  242.    
  243.     public VectThread(String file)
  244.     {
  245.         try {
  246.             phonesList=Utils.readBinaryPhones(file);
  247.             avgWeight=0;
  248.         } catch (ClassNotFoundException | IOException e) {
  249.             // TODO Auto-generated catch block
  250.             e.printStackTrace();
  251.         }
  252.     }
  253.  
  254.     public List<ElectronicDevices> getPhonesList() {
  255.         return phonesList;
  256.     }
  257.  
  258.     public double getAvgWeight() {
  259.         return avgWeight;
  260.     }
  261.  
  262.     @Override
  263.     public void run() {
  264.         for(ElectronicDevices ed : phonesList)
  265.         {
  266.             avgWeight+=((Phone)ed).getWeight();
  267.         }
  268.         avgWeight=avgWeight/phonesList.size();
  269.     }
  270. }
  271. package eu.ase.test;
  272.  
  273. import java.io.BufferedReader;
  274. import java.io.File;
  275. import java.io.IOException;
  276. import java.io.InputStreamReader;
  277. import java.io.ObjectOutputStream;
  278. import java.net.ServerSocket;
  279. import java.net.Socket;
  280. import java.sql.SQLException;
  281.  
  282. import org.json.JSONArray;
  283.  
  284. // Subject of + 2 points <=> Mark 6 or 7 (and parts of the mark 8):
  285. //  a. Create public class TCPServerSocketMultiT which handles multi-threading TCP server socket connections
  286. //  for implementing a proprietary communication protocol (set of rules)
  287. //  b. The class contains the following private fields:
  288. //  - serverSocket as ServerSocket, port = 50001 as int, f as File and vt as VectThread ("has a" relationship)
  289. //  c. The class contains the following methods and constructor:
  290. //      c.1 - constructor which get the port as parameter and create the serverSocket:
  291. //      public TCPServerSocketMultiT(int port) throws Exception
  292. //      c.2 - getter and setter for the field port
  293. //      c.3 - public void setFileName(String newFName) method which allocate memory for the field f, if and only if,
  294. //          the String parameter is different than null, otherwise is setting null
  295. //      c.4.- public void startTCPServer() throws IOException method which is having the infinite processing loop and is implementing 3 commands from the proprietary protocol
  296. //      HINTS for startTCPServer method:
  297. //      -create multi-threading by using lambda expressions from Runnable functional interface after the blocking accept() method from serverSocket object
  298. //      -get the input stream as BufferedReader and output stream as ObjectOutputStream
  299. //      -initialize the vt field from class VectThread by passing the file absolute path from f field as parameters AND OBTAIN the list (ArrayList of Phone objects) from the file
  300. //      -parse line by line the TCP request
  301. //          - if EXIT text command is received over the socket, then break the infinite loop of the processing and send TCP FIN packet back to the TCP client (e.g. by closing socket, etc.)
  302. //          - (mark 6) if GETFILE text command is received over the socket, then reply back the serialized list encapsulated in the vt object field
  303. //          - (mark 7) if GETJSON text command is received over the socket, then reply back with the list in JSON format
  304. //          - (mark 8) if GETDB text command is received over the socket, then reply back with the list as String produced by UtilsDAO.selectData() (please also take into account, you have to initialize JDBC connection and close it with static methods from UtilsDAO);
  305. //  YOU MAY NOT create the TCP client because it is already created into JUnit test framework; for mark 8, please also see UtilsDAO class (without UtilsDAO class, mark 8 can not be achieved)
  306.  
  307. public class TCPServerSocketMultiT {
  308.     private ServerSocket serverSocket;
  309.     private int port=50001;
  310.     File f;
  311.     VectThread vt;
  312.    
  313.     public TCPServerSocketMultiT(int port) throws Exception
  314.     {
  315.         serverSocket=new ServerSocket(port);
  316.     }
  317.  
  318.     public int getPort() {
  319.         return port;
  320.     }
  321.  
  322.     public void setPort(int port) {
  323.         this.port = port;
  324.     }
  325.    
  326.     public void setFileName(String newFName)
  327.     {
  328.         if(newFName!=null)
  329.             f=new File(newFName);
  330.         else
  331.             f=null;
  332.     }
  333.    
  334.     public void startTCPServer() throws IOException
  335.     {
  336.         vt=new VectThread(f.getAbsolutePath());
  337.         while(true)
  338.         {
  339.             Socket clientSocket=serverSocket.accept();
  340.             Thread th=new Thread(()->
  341.             {
  342.                 try(BufferedReader bf=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  343.                         ObjectOutputStream oos= new ObjectOutputStream(clientSocket.getOutputStream()))
  344.                 {
  345.                     boolean proces=true;
  346.                     while(proces)
  347.                     {
  348.                         String linie=null;
  349.                         while((linie=bf.readLine())!=null)
  350.                         {
  351.                             switch (linie) {
  352.                             case "EXIT":
  353.                             {
  354.                                 serverSocket.close();
  355.                             }
  356.                                 break;
  357.                             case"GETFILE":
  358.                             {
  359.                                 oos.writeObject(vt.getPhonesList());
  360.                             }
  361.                                 break;
  362.                             case"GETJSON":
  363.                             {
  364.                                 JSONArray json= new JSONArray(vt.getPhonesList());
  365.                                 oos.writeObject(json.toString());
  366.                             }
  367.                                 break;
  368.                             case"GETDB":
  369.                             {
  370.                                 UtilsDAO.setConnection();
  371.                                 oos.writeObject(UtilsDAO.selectData());
  372.                                 System.out.println(UtilsDAO.selectData());
  373.                                 UtilsDAO.closeConnection();
  374.                             }
  375.                                 break;
  376.                             default:
  377.                                 break;
  378.                             }
  379.                         }
  380.                        
  381.                     }
  382.                 } catch (IOException | SQLException e) {
  383.                     // TODO Auto-generated catch block
  384.                     e.printStackTrace();
  385.                 } catch (ClassNotFoundException e) {
  386.                     // TODO Auto-generated catch block
  387.                     e.printStackTrace();
  388.                 }
  389.             });
  390.            
  391.             th.start();
  392.             try {
  393.                 th.join();
  394.             } catch (InterruptedException e) {
  395.                 // TODO Auto-generated catch block
  396.                 e.printStackTrace();
  397.             }
  398.         }
  399.     }
  400. }
  401. package eu.ase.test;
  402.  
  403. import java.sql.Connection;
  404. import java.sql.DriverManager;
  405. import java.sql.ResultSet;
  406. import java.sql.SQLException;
  407. import java.sql.Statement;
  408.  
  409. // Mark 8: create public class UtilsDAO with only one static field c from class Connection (SQL/JDBC)
  410. //  This class contains the following 3 static methods:
  411. //  a.  public static void setConnection() - set the connection by using org.sqlite.JDBC driver and connection string: jdbc:sqlite:test.db
  412. //  b.  public static void closeConnection() - close the SQL/JDBC connection
  413. //  c.  public static String selectData() throws SQLException - for SQL selecting all the phones from the already created SQLite DB file
  414. //      - select * from PHONES
  415. //      - PHONES table is already created with the following columns id - INT, PRODUCER - TEXT, DIAGONAL - REAL and WEIGHT - REAL
  416. //      - the String containing the view after selecting the entire table is having each table line separated with "\r\n" and each column value will be separated by ":"
  417.  
  418. public class UtilsDAO {
  419.     static Connection c;
  420.    
  421.     public static void setConnection() throws ClassNotFoundException, SQLException
  422.     {
  423.         Class.forName("org.sqlite.JDBC");
  424.         c=DriverManager.getConnection("jdbc:sqlite:test.db");
  425.     }
  426.    
  427.     public static void closeConnection()
  428.     {
  429.         try {
  430.             c.close();
  431.         } catch (SQLException e) {
  432.             // TODO Auto-generated catch block
  433.             e.printStackTrace();
  434.         }
  435.     }
  436.    
  437.     public static String selectData() throws SQLException
  438.     {
  439.         Statement statement=c.createStatement();
  440.         String sql="select * from PHONES;";
  441.         ResultSet rs=statement.executeQuery(sql);
  442.         String rez=null;
  443.         while(rs.next())
  444.         {
  445.             rez+=rs.getInt(1)+":"+rs.getString(2)+":"+rs.getDouble(3)+":"+rs.getFloat(4)+"\r\n";
  446.         }
  447.         return rez;
  448.     }
  449. }
  450. package eu.ase.test;
  451.  
  452. import java.io.IOException;
  453. import java.net.DatagramPacket;
  454. import java.net.DatagramSocket;
  455. import java.net.InetAddress;
  456. import java.net.SocketException;
  457. import java.net.UnknownHostException;
  458.  
  459. //Subject+2 points <=> Mark 9/10:
  460. //Create public class UDPClientSocket which implements a proprietary communication protocol and implements AutoCloseable (override specific method)
  461. //It has 2 fields: socket - DatagramSocket
  462. //It contains the following constructor methods:
  463. //a. public UDPClientSocket() throws SocketException - init socket WITHOUT bind port
  464. //b. public String sendAndReceiveMsg(String msg, String ipAddr, int port) throws UnknownHostException
  465. //   - send UDP packets and process them (without infinite loop) with the following rules:
  466. //      - when the sent request contains W? , then the response UDP packet from server contains as pay-load "UDPS".
  467. //      - when the sent request contains BYE , then the response UDP packet from server contains as pay-load "BYE ACK"
  468. //      - when the sent request contains any other pay-load , then the response UDP packet contains as pay-load "ACK".
  469.  
  470. public class UDPClientSocket implements AutoCloseable {
  471.     private DatagramSocket socket;
  472.    
  473.     public UDPClientSocket() throws SocketException
  474.     {
  475.         socket=new DatagramSocket();
  476.     }
  477.    
  478.     public String sendAndReceiveMsg(String msg, String ipAddr, int port) throws UnknownHostException, IOException
  479.     {
  480.         String raspuns=null;
  481.         switch (msg) {
  482.         case "W?":
  483.         {
  484.             raspuns="UDSP";
  485.             socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
  486.         }
  487.             break;
  488.         case"BYE":
  489.         {
  490.             raspuns="BYE ACK";
  491.             socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
  492.         }
  493.             break;
  494.         default:
  495.         {
  496.             raspuns="ACK";
  497.             socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
  498.         }
  499.             break;
  500.         }
  501.         return raspuns;
  502.     }
  503.  
  504.     @Override
  505.     public void close() throws Exception {
  506.         // TODO Auto-generated method stub
  507.         socket.close();
  508.     }
  509. }
  510. package eu.ase.test;
  511.  
  512. import java.io.IOException;
  513. import java.net.DatagramPacket;
  514. import java.net.DatagramSocket;
  515. import java.net.SocketAddress;
  516. import java.net.SocketException;
  517.  
  518. //Subject+2 points <=> Mark 9/10:
  519. // Create public class UDPServerSocket which implements a proprietary communication protocol and implements AutoCloseable (override specific method)
  520. // It has 2 fields: socket - DatagramSocket and bindPort - int
  521. // It contains the following constructor methods:
  522. // a. public UDPServerSocket() throws SocketException - init bindPort on 60001
  523. // b. public int getBindPort() - returns the bindPord field
  524. // c. public void processRequest() throws IOException - receive UDP packets and process them (without infinite loop) with the following rules:
  525. //      - if the request contains W? , then the reply UDP packet contains as pay-load "UDPS".
  526. //      - if the request contains BYE , then the reply UDP packet contains as pay-load "BYE ACK" and close the resources (e.g. socket)
  527. //      - if the request contains any other pay-load , then the reply UDP packet contains as pay-load "ACK".
  528.  
  529. public class UDPServerSocket implements AutoCloseable{
  530.     private DatagramSocket socket;
  531.     private int bindPort;
  532.  
  533.     public UDPServerSocket() throws SocketException
  534.     {
  535.         bindPort=60001;
  536.         socket=new DatagramSocket(bindPort);
  537.     }
  538.    
  539.     public int getBindPort()
  540.     {
  541.         return bindPort;
  542.     }
  543.    
  544.     public void processRequest() throws IOException
  545.     {
  546.         DatagramPacket packet=new DatagramPacket(new byte[256], 256);
  547.         socket.receive(packet);
  548.         String req=new String(packet.getData());
  549.         switch (req) {
  550.         case "W?":
  551.         {
  552.             socket.send(new DatagramPacket("UDPS".getBytes(), "UDPS".length(), packet.getAddress(), packet.getPort()));
  553.         }
  554.             break;
  555.         case "BYE":
  556.         {
  557.             socket.send(new DatagramPacket("BYE ACK".getBytes(), "BYE ACK".length(), packet.getAddress(), packet.getPort()));
  558.             socket.close();
  559.         }
  560.             break;
  561.         default:
  562.         {
  563.             socket.send(new DatagramPacket("ACK".getBytes(), "ACK".length(), packet.getAddress(), packet.getPort()));
  564.         }
  565.             break;
  566.         }
  567.     }
  568.  
  569.     @Override
  570.     public void close() throws Exception {
  571.         socket.close();    
  572.     }
  573. }
Advertisement
Add Comment
Please, Sign In to add comment