Skip to content
Advertisement

How to convert an input into a method that the program will understand

I’m currently working on my homework about client and server topic: I created a class called VehileRequest.java which will take three variables (year, make, model) from Client.java and pass them to Server.java then the Server will get information from VehicleRespone.java and display the information about price, miles vv…

As I understand, the program didn’t recognize the request that pass to the respond file.

I got stuck at passing the Request to Response so that the Response will understand. Any help please. thank you

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

public class VehicleResponse {
    private VehicleRequest request;
    private int milesOnVehicle;
    private int price;
    private int numberOfSeats;
    private int numberOfDoors;
    private String[] options;

    @JsonIgnore
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    public static String toJSON(VehicleResponse vehicle) throws Exception {
        return objectMapper.writeValueAsString(vehicle);
    }
    
    public static VehicleResponse fromJSON(String input) throws Exception{
        return objectMapper.readValue(input, VehicleResponse.class);
    }
    
    protected VehicleResponse() {}
    
    public VehicleResponse(VehicleRequest request, int milesOnVehicle,int price, int numberOfSeats, int numberOfDoors,String[] options) {
        this.request=request;
        this.milesOnVehicle=milesOnVehicle;
        this.price=price;
        this.numberOfSeats=numberOfSeats;
        this.numberOfDoors=numberOfDoors;
        this.options=options;
    }

    @Override
    public String toString() {
        return String.format(
                "Vehicle request:[miles=%d, price=%d, number of seats=%d,number of doors=%d, option='%s']",
                milesOnVehicle,price,numberOfSeats,numberOfDoors,options);
    }

    public VehicleRequest getRequest() {return request;}
    public int getMilesOnVehicle(){return milesOnVehicle;};
    public int getPrice(){return price;}
    public int getNumberOfDoors() {return numberOfDoors;}
    public int getNumberOfSeats() {return numberOfSeats;}
    public String[] getOptions() {return options;}

    public void setRequest(VehicleRequest request) {
        this.request = request;
    }
    public void setMilesOnVehicle(int milesOnVehicle) {
        this.milesOnVehicle = milesOnVehicle;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void setNumberOfSeats(int numberOfSeats) {
        this.numberOfSeats = numberOfSeats;
    }

    public void setNumberOfDoors(int numberOfDoors) {
        this.numberOfDoors = numberOfDoors;
    }

    public void setOptions(String[] options) {
        this.options = options;
    }
}

Here is the VehicleRequest file

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

public class VehicleRequest {
    private int year;
    private String make;
    private String model;

    @JsonIgnore
    private static final ObjectMapper objectMapper = new ObjectMapper();
    public static String toJSON(VehicleRequest vehicle) throws Exception {
        return objectMapper.writeValueAsString(vehicle);
    }
    public static VehicleRequest fromJSON(String input) throws Exception{
        return objectMapper.readValue(input, VehicleRequest.class);
    }
    protected VehicleRequest() {}

    public VehicleRequest(int year, String make, String model) {

        this.year = year;
        this.make =make;
        this.model=model;
    }

    @Override
    public String toString() {
        return String.format(
                "Vehicle: [year=%d, make='%s', model='%s']",
                year,make,model);
    }

    public int getYear() {
        return year;
    }
    public String getMake(){return make;}
    public String getModel(){return model;}

    public void setYear(int year) {
        this.year = year;
    }
    public void setMake(String make){
        this.make=make;
    }
    public void setModel(String model){
        this.model=model;
    }
}

Here is the Server

public class Server {
    private ServerSocket serverSocket;
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void start(int port) throws Exception {
        serverSocket = new ServerSocket(port);
        clientSocket = serverSocket.accept();
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            VehicleRequest request = VehicleRequest.fromJSON(inputLine);
            VehicleResponse response = new VehicleResponse(request,10000,12000,5,4, null);
            out.println(VehicleResponse.toJSON(response));
        }
    }

    public void stop() throws IOException {
        in.close();
        out.close();
        clientSocket.close();
        serverSocket.close();
    }

    public static void main(String[] args) {
        Server server = new Server();
        try {
            server.start(4444);
            server.stop();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Here is the client

public class Client {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void startConnection(String ip, int port) throws IOException {
        clientSocket = new Socket(ip, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }

    public VehicleRequest sendRequest() throws Exception {
        out.println(VehicleRequest.toJSON(new VehicleRequest(2008,"Honda","Civic")));
        return VehicleRequest.fromJSON(in.readLine());
    }

    public void stopConnection() throws IOException {
        in.close();
        out.close();
        clientSocket.close();
    }
    public static void main(String[] args) {
        Client client = new Client();
        try {
            client.startConnection("127.0.0.1", 4444);
            System.out.println(client.sendRequest().toString());
            client.stopConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

I got the result was

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "request" (class edu.sdccd.cisc191.template.VehicleRequest), not marked as ignorable (3 known properties: "model", "year", "make"])
 at [Source: (String)"{"request":{"year":2008,"make":"Honda","model":"Civic"},"milesOnVehicle":10000,"price":12000,"numberOfSeats":5,"numberOfDoors":4,"options":null}"; line: 1, column: 13] (through reference chain: edu.sdccd.cisc191.template.VehicleRequest["request"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:855)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1212)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1604)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1582)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:299)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4482)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3434)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3402)
    at edu.sdccd.cisc191.template.VehicleRequest.fromJSON(VehicleRequest.java:17)
    at edu.sdccd.cisc191.template.Client.sendRequest(Client.java:32)
    at edu.sdccd.cisc191.template.Client.main(Client.java:44)
}

Advertisement

Answer

In the line VehicleRequest.fromJSON(in.readLine()); you are trying to parse whatever it is the input, which seems to be:

{
   "request":{
      "year":2008,
      "make":"Honda",
      "model":"Civic"
   },
   "milesOnVehicle":10000,
   "price":12000,
   "numberOfSeats":5,
   "numberOfDoors":4,
   "options":null
}

However, you are expecting this to be parseable to VehicleRequest which is not possible because it contains only 3 parameters and not all that. Either you parse this as VehicleResponse as follows:

VehicleResponse.fromJSON(in.readLine());

Or you change the input to be something that can be parsed to VehicleRequest:

{
    "year":2008,
    "make":"Honda",
    "model":"Civic"
}

If I am understanding your code correctly you are trying to make communication between Client and Server. In that case, you will need to change your Client code:

public class Client {
    private Socket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    public void startConnection(String ip, int port) throws IOException {
        clientSocket = new Socket(ip, port);
        out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }

    public VehicleResponse sendRequest() throws Exception {
        out.println(VehicleRequest.toJSON(new VehicleRequest(2008,"Honda","Civic")));
        return VehicleResponse.fromJSON(in.readLine());
    }

    public void stopConnection() throws IOException {
        in.close();
        out.close();
        clientSocket.close();
    }
    public static void main(String[] args) {
        Client client = new Client();
        try {
            client.startConnection("127.0.0.1", 4444);
            System.out.println(client.sendRequest().toString());
            client.stopConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement