0

I have "transit manager" application. It's a simply app to test how to use Spring framework. I've created endpoint for adding new transit to database (Spring Data) and it works fine. I have added a few transits and now I want to get daily report and here I have problems. This is how endpoint should looks like:

GET http://example.com/reports/daily?start_date=YYYY-MM-DD&end_date=YYYY-MM_DD

And response(in JSON) for example:

{
  "total_distance": "90",
  "total_price":      "115"
}

What I suppose to do? Should I add new fields "startDate" and "endDate" in model class?

This is how my model class looks:

@Entity
public class Transit {

public Transit() {
}

@Column(name = "id")
@Id
@GeneratedValue
private Long id;
@NotEmpty
private String sourceAddress;
@NotEmpty
private String destinationAddress;
private double price;
private DateTime date;
private Long distance;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getSourceAddress() {
    return sourceAddress;
}

public void setSourceAddress(String sourceAddress) {
    this.sourceAddress = sourceAddress;
}

public String getDestinationAddress() {
    return destinationAddress;
}

public void setDestinationAddress(String destinationAddress) {
    this.destinationAddress = destinationAddress;
}

public double getPrice() {
    return price;
}

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

public DateTime getDate() {
    return date;
}

public void setDate(DateTime date) {
    this.date = date;
}


public Long getDistance() {
    return distance;
}

public void setDistance(Long distance) {
    this.distance = distance;
}}

Repository class:

public interface TransitRepository extends JpaRepository<Transit, Long> {
List<Transit> findAllByStartDateGreaterThanEqualAndEndDateLessThanEqual(DateTime startDate, DateTime endDate);
}

Controller class:

@RestController
@RequestMapping("/transit")
public class TransitController {
private TransitService transitService;

@Autowired
public void setTransitService(TransitService transitService) {
    this.transitService = transitService;
}


@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addTransit(@RequestBody Transit transit){
    transitService.calculateDistance(transit);
    transitService.addTransit(transit);
    System.out.println(transit);
}

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void getDailyReport(){}

}

And service class:

@Service
public class TransitService {

private TransitRepository transitRepository;
public static final String API_KEY = "xxxxxx";

@Autowired
public void setTransitRepository(TransitRepository transitRepository) {
    this.transitRepository = transitRepository;
}

public void addTransit(Transit transit) {
    transitRepository.save(transit);
}

public void calculateDistance(Transit transit) {

    GeoApiContext geoApiContext = new GeoApiContext.Builder().apiKey(API_KEY).build();
    DistanceMatrixApiRequest request = DistanceMatrixApi.newRequest(geoApiContext);

    DistanceMatrix result = request.origins(transit.getSourceAddress())
            .destinations(transit.getDestinationAddress())
            .mode(TravelMode.DRIVING)
            .units(Unit.METRIC)
            .awaitIgnoreError();

    long distance = result.rows[0].elements[0].distance.inMeters;
    transit.setDistance(distance);

}

public void countDaily(List<Transit> transitList){

}
}

2 Answers 2

2

You should use the annotaion @RequestParam on the parameters you need to add to your method. The name in the annotaion is optional and defaults to the parameter name.

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
public void getDailyReport(@RequestParam("start_date") String startDate, @RequestParam String end_date){}

}

Adding the fields to your Transit class would not work as the GET-Request has no request body and the parameters are not in the body anyway.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your help. Are you sure that in this case date should be String type or I have to change it?
Depending on the date format an auto-convertion by Spring could also work but you should test this. Dates are difficult to auto convert because of the multiple formatting patterns.
But in this case when I have to compare that date is between two dates I think that i can't use Spring right? I tried with Date type but this one is including minutes, I want to do it with pattern: yyyy-mm-dd
1

You should use @RequestParam annotation in your controller method.

@RequestMapping(path = "reports/daily", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
public void getDailyReport(@RequestParam("start_date") String startDate, @RequestParam("end_date") String endDate){

     // Create a method in service class, that takes startDate and endDate as parameters.

     // And inside that method, you can write a SQL query to find the distance & price for the given date parameters

}

3 Comments

Hi I added new method in repository class (question edited) and there is problem, becouse I there is no property startDate found for type Transit so I can't turn on my app... Am I doing right?
Hey, I did what You say but when I make get request it doesn't work, can You check my app at github: github.com/Dezet-IT/TransitApp ?
In your code, you wrote startDate and endDate instead of start_date and end_date in @RequestParam. Please check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.