Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package eu.ase.test;
- //Mark 3:
- // Create the interface ElectronicDevices with the method infoDevice() returning String, must be inserted
- public interface ElectronicDevices {
- public String infoDevice();
- }
- package eu.ase.test;
- import java.io.Serializable;
- //Mark 3:
- //a. Create public class Phone which must implement ElectronicDevice interface and It must be inserted 3 fields:
- //weight - float, diagonal - double, producer - String
- //b. for this class fields it is mandatory to implement getters and setters, plus the default constructor (without parameters),
- //there is NO constructor with parameters
- //c. override implementation for the infoDevice() method (from the ElectronicDevices interface) to return the producer String
- //d. the setters should throw Exception if the constraints are not fulfilled:
- //- producer different than null and producer String length greater than 1
- //- diagonal and weight greater than 0 each
- //e. Implements Serializable, Cloneable and Override the implementation for equals(), hashCode() and clone() methods
- public class Phone implements ElectronicDevices, Serializable, Cloneable {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private float weight;
- private double diagonal;
- private String producer;
- public Phone()
- {
- weight=0;
- diagonal=0;
- producer="";
- }
- public float getWeight() {
- return weight;
- }
- public void setWeight(float weight) throws Exception {
- if(weight>0)
- this.weight = weight;
- else throw new Exception();
- }
- public double getDiagonal() {
- return diagonal;
- }
- public void setDiagonal(double diagonal) throws Exception {
- if(diagonal>0)
- this.diagonal = diagonal;
- else throw new Exception();
- }
- public String getProducer() {
- return producer;
- }
- public void setProducer(String producer) throws Exception {
- if(producer!=null && producer.length()>1)
- this.producer = producer;
- else throw new Exception();
- }
- @Override
- public String infoDevice() {
- return producer;
- }
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- @Override
- public boolean equals(Object obj) {
- if(obj instanceof Phone)
- {
- Phone p=(Phone)obj;
- return this.weight==p.weight && this.diagonal==p.diagonal && this.producer.equals(p.producer);
- }
- else return false;
- }
- @Override
- public int hashCode() {
- return super.hashCode();
- }
- }
- package eu.ase.test;
- //Mark 3:
- // a. create public class SmartPhone must inherit the Phone class and it adds the batteryDuration - int field
- // b. for this class fields it is mandatory to implement getters and setters
- // c. override virtual implementation for the infoDevice() method (from the ElectronicDevices interface and Phone implementation),
- // to return the batteryDuration as a String
- // d. the setters should throw Exception if the constraints are not fulfilled:
- // - batteryDuration greater than 0
- public class SmartPhone extends Phone{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private int batteryDuration;
- public int getBatteryDuration() {
- return batteryDuration;
- }
- public void setBatteryDuration(int batteryDuration) throws Exception {
- if(batteryDuration>0)
- this.batteryDuration = batteryDuration;
- else throw new Exception();
- }
- @Override
- public String infoDevice() {
- return ""+batteryDuration;
- }
- }
- package eu.ase.test;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.util.ArrayList;
- import java.util.List;
- //Mark 4:
- // Create public class Utils which contains private static list field with interface as type: List<ElectronicDevices>
- // Insert the following methods:
- // a. public static List<ElectronicDevices> createPhones(int n) throws Exception - for creating an ArrayList of n elemnts
- // which are containing n default Phone objects and it using the static field of the class (list)
- // b. public static List<ElectronicDevices> readPhones(String file)
- // - for reading and parsing text files with string lines for creating Phone objects
- // (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
- // hint: use RandomAccessFile and read / parse line by line (first is parsing for float - weight, second line is double - diagonal, third is String - producer)
- // c. public static void writeBinaryPhones(String file, List<ElectronicDevices> listP) - for writing binary the phones into the file
- // hint: use FileOutputStream with FileOurputStream to serialized/save the Phone objects from the ArrayList of the phones objects
- // d. public static List<ElectronicDevices> readBinaryPhones(String file) - for reading binary the Phone objects from the file and creating the ArrayList
- public class Utils {
- private static List<ElectronicDevices> list;
- public static List<ElectronicDevices> createPhones(int n) throws Exception
- {
- if(n<=0) throw new Exception();
- list=new ArrayList<ElectronicDevices>(n);
- for(int i=0;i<n;i++)
- {
- list.add(new Phone());
- }
- return list;
- }
- public static List<ElectronicDevices> readPhones(String file) throws Exception
- {
- if(new File(file).exists())
- {
- list.clear();
- try {
- BufferedReader bf=new BufferedReader(new FileReader(file));
- String linie=null;
- while((linie=bf.readLine())!=null)
- {
- float weight=Float.parseFloat(linie);
- linie=bf.readLine();
- double diagonal=Double.parseDouble(linie);
- linie=bf.readLine();
- String producer=linie.toString();
- Phone p= new Phone();
- p.setWeight(weight);
- p.setDiagonal(diagonal);
- p.setProducer(producer);
- list.add(p);
- }
- bf.close();
- return list;
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- throw new Exception();
- }
- public static void writeBinaryPhones(String file, List<ElectronicDevices> listP) throws FileNotFoundException, IOException
- {
- ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
- oos.writeObject(listP);
- oos.close();
- }
- public static List<ElectronicDevices> readBinaryPhones(String file) throws FileNotFoundException, IOException, ClassNotFoundException
- {
- ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
- List<ElectronicDevices> lista=(List)(ois.readObject());
- ois.close();
- return lista;
- }
- }
- package eu.ase.test;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.List;
- // Mark 5:
- // a. create the class VectThread which implements Runnable and contains 2 fields:
- // - phonesList with interface as type List<ElectronicDevices>
- // - avgWeight is a real (double) number for storing the average weight of the phones list
- // b. In the constructor read the file using readBinaryPhones static method from Utils
- // c. provide get methods for the both fields (phoneList and avgweight) of the class
- // d. Within the override run method (with the signature in Runnable interface)
- // - the developer should go through the phoneList and calculate the average of the weights from the phone list objects (Phone class - explicit cast)
- public class VectThread implements Runnable {
- private List<ElectronicDevices> phonesList;
- private double avgWeight;
- public VectThread(String file)
- {
- try {
- phonesList=Utils.readBinaryPhones(file);
- avgWeight=0;
- } catch (ClassNotFoundException | IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public List<ElectronicDevices> getPhonesList() {
- return phonesList;
- }
- public double getAvgWeight() {
- return avgWeight;
- }
- @Override
- public void run() {
- for(ElectronicDevices ed : phonesList)
- {
- avgWeight+=((Phone)ed).getWeight();
- }
- avgWeight=avgWeight/phonesList.size();
- }
- }
- package eu.ase.test;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.ObjectOutputStream;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.sql.SQLException;
- import org.json.JSONArray;
- // Subject of + 2 points <=> Mark 6 or 7 (and parts of the mark 8):
- // a. Create public class TCPServerSocketMultiT which handles multi-threading TCP server socket connections
- // for implementing a proprietary communication protocol (set of rules)
- // b. The class contains the following private fields:
- // - serverSocket as ServerSocket, port = 50001 as int, f as File and vt as VectThread ("has a" relationship)
- // c. The class contains the following methods and constructor:
- // c.1 - constructor which get the port as parameter and create the serverSocket:
- // public TCPServerSocketMultiT(int port) throws Exception
- // c.2 - getter and setter for the field port
- // c.3 - public void setFileName(String newFName) method which allocate memory for the field f, if and only if,
- // the String parameter is different than null, otherwise is setting null
- // c.4.- public void startTCPServer() throws IOException method which is having the infinite processing loop and is implementing 3 commands from the proprietary protocol
- // HINTS for startTCPServer method:
- // -create multi-threading by using lambda expressions from Runnable functional interface after the blocking accept() method from serverSocket object
- // -get the input stream as BufferedReader and output stream as ObjectOutputStream
- // -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
- // -parse line by line the TCP request
- // - 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.)
- // - (mark 6) if GETFILE text command is received over the socket, then reply back the serialized list encapsulated in the vt object field
- // - (mark 7) if GETJSON text command is received over the socket, then reply back with the list in JSON format
- // - (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);
- // 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)
- public class TCPServerSocketMultiT {
- private ServerSocket serverSocket;
- private int port=50001;
- File f;
- VectThread vt;
- public TCPServerSocketMultiT(int port) throws Exception
- {
- serverSocket=new ServerSocket(port);
- }
- public int getPort() {
- return port;
- }
- public void setPort(int port) {
- this.port = port;
- }
- public void setFileName(String newFName)
- {
- if(newFName!=null)
- f=new File(newFName);
- else
- f=null;
- }
- public void startTCPServer() throws IOException
- {
- vt=new VectThread(f.getAbsolutePath());
- while(true)
- {
- Socket clientSocket=serverSocket.accept();
- Thread th=new Thread(()->
- {
- try(BufferedReader bf=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
- ObjectOutputStream oos= new ObjectOutputStream(clientSocket.getOutputStream()))
- {
- boolean proces=true;
- while(proces)
- {
- String linie=null;
- while((linie=bf.readLine())!=null)
- {
- switch (linie) {
- case "EXIT":
- {
- serverSocket.close();
- }
- break;
- case"GETFILE":
- {
- oos.writeObject(vt.getPhonesList());
- }
- break;
- case"GETJSON":
- {
- JSONArray json= new JSONArray(vt.getPhonesList());
- oos.writeObject(json.toString());
- }
- break;
- case"GETDB":
- {
- UtilsDAO.setConnection();
- oos.writeObject(UtilsDAO.selectData());
- System.out.println(UtilsDAO.selectData());
- UtilsDAO.closeConnection();
- }
- break;
- default:
- break;
- }
- }
- }
- } catch (IOException | SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- });
- th.start();
- try {
- th.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- package eu.ase.test;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- // Mark 8: create public class UtilsDAO with only one static field c from class Connection (SQL/JDBC)
- // This class contains the following 3 static methods:
- // a. public static void setConnection() - set the connection by using org.sqlite.JDBC driver and connection string: jdbc:sqlite:test.db
- // b. public static void closeConnection() - close the SQL/JDBC connection
- // c. public static String selectData() throws SQLException - for SQL selecting all the phones from the already created SQLite DB file
- // - select * from PHONES
- // - PHONES table is already created with the following columns id - INT, PRODUCER - TEXT, DIAGONAL - REAL and WEIGHT - REAL
- // - 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 ":"
- public class UtilsDAO {
- static Connection c;
- public static void setConnection() throws ClassNotFoundException, SQLException
- {
- Class.forName("org.sqlite.JDBC");
- c=DriverManager.getConnection("jdbc:sqlite:test.db");
- }
- public static void closeConnection()
- {
- try {
- c.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- public static String selectData() throws SQLException
- {
- Statement statement=c.createStatement();
- String sql="select * from PHONES;";
- ResultSet rs=statement.executeQuery(sql);
- String rez=null;
- while(rs.next())
- {
- rez+=rs.getInt(1)+":"+rs.getString(2)+":"+rs.getDouble(3)+":"+rs.getFloat(4)+"\r\n";
- }
- return rez;
- }
- }
- package eu.ase.test;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- //Subject+2 points <=> Mark 9/10:
- //Create public class UDPClientSocket which implements a proprietary communication protocol and implements AutoCloseable (override specific method)
- //It has 2 fields: socket - DatagramSocket
- //It contains the following constructor methods:
- //a. public UDPClientSocket() throws SocketException - init socket WITHOUT bind port
- //b. public String sendAndReceiveMsg(String msg, String ipAddr, int port) throws UnknownHostException
- // - send UDP packets and process them (without infinite loop) with the following rules:
- // - when the sent request contains W? , then the response UDP packet from server contains as pay-load "UDPS".
- // - when the sent request contains BYE , then the response UDP packet from server contains as pay-load "BYE ACK"
- // - when the sent request contains any other pay-load , then the response UDP packet contains as pay-load "ACK".
- public class UDPClientSocket implements AutoCloseable {
- private DatagramSocket socket;
- public UDPClientSocket() throws SocketException
- {
- socket=new DatagramSocket();
- }
- public String sendAndReceiveMsg(String msg, String ipAddr, int port) throws UnknownHostException, IOException
- {
- String raspuns=null;
- switch (msg) {
- case "W?":
- {
- raspuns="UDSP";
- socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
- }
- break;
- case"BYE":
- {
- raspuns="BYE ACK";
- socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
- }
- break;
- default:
- {
- raspuns="ACK";
- socket.send(new DatagramPacket(raspuns.getBytes(), raspuns.length(), InetAddress.getByName(ipAddr), port));
- }
- break;
- }
- return raspuns;
- }
- @Override
- public void close() throws Exception {
- // TODO Auto-generated method stub
- socket.close();
- }
- }
- package eu.ase.test;
- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.SocketAddress;
- import java.net.SocketException;
- //Subject+2 points <=> Mark 9/10:
- // Create public class UDPServerSocket which implements a proprietary communication protocol and implements AutoCloseable (override specific method)
- // It has 2 fields: socket - DatagramSocket and bindPort - int
- // It contains the following constructor methods:
- // a. public UDPServerSocket() throws SocketException - init bindPort on 60001
- // b. public int getBindPort() - returns the bindPord field
- // c. public void processRequest() throws IOException - receive UDP packets and process them (without infinite loop) with the following rules:
- // - if the request contains W? , then the reply UDP packet contains as pay-load "UDPS".
- // - if the request contains BYE , then the reply UDP packet contains as pay-load "BYE ACK" and close the resources (e.g. socket)
- // - if the request contains any other pay-load , then the reply UDP packet contains as pay-load "ACK".
- public class UDPServerSocket implements AutoCloseable{
- private DatagramSocket socket;
- private int bindPort;
- public UDPServerSocket() throws SocketException
- {
- bindPort=60001;
- socket=new DatagramSocket(bindPort);
- }
- public int getBindPort()
- {
- return bindPort;
- }
- public void processRequest() throws IOException
- {
- DatagramPacket packet=new DatagramPacket(new byte[256], 256);
- socket.receive(packet);
- String req=new String(packet.getData());
- switch (req) {
- case "W?":
- {
- socket.send(new DatagramPacket("UDPS".getBytes(), "UDPS".length(), packet.getAddress(), packet.getPort()));
- }
- break;
- case "BYE":
- {
- socket.send(new DatagramPacket("BYE ACK".getBytes(), "BYE ACK".length(), packet.getAddress(), packet.getPort()));
- socket.close();
- }
- break;
- default:
- {
- socket.send(new DatagramPacket("ACK".getBytes(), "ACK".length(), packet.getAddress(), packet.getPort()));
- }
- break;
- }
- }
- @Override
- public void close() throws Exception {
- socket.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment