Pageable and PageRequest Issue - java

Hey everyone i have been trying to make this tutorial in youtube about spring boot and angular js https://www.youtube.com/watch?v=zBLXWIhrg7U
i have some trouble with using pageRequest Page<> in Java ps this is my controller
package cat.Controller;
import cat.dao.ProduitRepository;
import cat.entities.Produit;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ProduitController {
#Autowired
private ProduitRepository produitRepository ;
#RequestMapping("/test")
public String test() {
return "test";
}
#RequestMapping("/save")
public Produit saveProduit(Produit p)
{
produitRepository.save(p);
return p ;
}
#RequestMapping("/all")
public List<Produit> getProduits()
{
return produitRepository.findAll();
}
#RequestMapping("/produit")
public Page<Produit> getProduits(int page)
{
return produitRepository.findAll(new PageRequest(page, 5));
}
**#RequestMapping("/produict")
public Page<Produit> getProduitss(String mc,int page)
{
return produitRepository.produitmc(mc, new PageRequest(page, 5) );**
}
and this my Dao layer using JpaRepository
package cat.dao;
import java.awt.print.Pageable;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import cat.entities.Produit;
public interface ProduitRepository extends JpaRepository<Produit, Long> {
// recuperé par mot clé
#Query("select p from produit as p where p.ref like x ")
public Page<Produit> produitmc (#Param("x")Long mc, Pageable p);
public List<Produit> findByRef (Long ref);
public List<Produit> findByRef (Long ref, Pageable p);
}
the function produitmc is suppose to make me search in entity produit by Ref the Erorr is in the function in controller (Bold) and it says
Description Resource Path Location Type
The method produitmc(Long, Pageable) in the type ProduitRepository is not applicable for the arguments (String, PageRequest) ProduitController.java /Mycatalogue/src/main/java/cat/Controller line 45 Java Problem

Yes.... Seems your argument passed doesn't match datatype expected. Else it should work.

Related

Deploy issues with data base connection Heroku

I'm working with a project that has the back in Java deployed at Heroku and the front in Angular dpeloyed at Firebase. Data base is in CleverCloud.
I'm having problems with bringing data to the front from the data base.
PERSON TABLE (WORKS JUST FINE):
CONTROLLER (JAVA):
package com.portfoliocardone.portfoliocardone.Controller;
import com.portfoliocardone.portfoliocardone.Entity.Person;
import com.portfoliocardone.portfoliocardone.Interface.IPersonService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin(origins = "https://portfoliocardone.web.app")
public class PersonController {
#Autowired IPersonService ipersonService;
#GetMapping("/person/get")
public List<Person> getPerson(){
return ipersonService.getPerson();
}
#PostMapping("/person/new")
public String createPerson(#RequestBody Person person){
ipersonService.savePerson(person);
return "The person was created correctly";
}
#DeleteMapping("/person/delete/{id}")
public String deletePerson(#PathVariable Long id){
ipersonService.deletePerson(id);
return "The person was deleted correctly";
}
//URL:PORT/person/edit/id/name & lastname & img & about me
#PutMapping("/person/edit/{id}")
public Person editPerson(#PathVariable Long id,
#RequestParam("name") String newName,
#RequestParam("lastname") String newLastname,
#RequestParam("img") String newImg,
#RequestParam("aboutme") String newAboutme){
Person person = ipersonService.findPerson(id);
person.setName(newName);
person.setLastname(newLastname);
person.setImg(newImg);
person.setAboutme(newAboutme);
ipersonService.savePerson(person);
return person;
}
#GetMapping("/person/find/profile")
public Person findPerson(){
return ipersonService.findPerson((long)1);
}
}
SERVICE ANGULAR PROJECT:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { person } from '../model/person.model';
#Injectable({
providedIn: 'root'
})
export class PersonService {
URL = 'https://portfoliocardone.herokuapp.com/person/';
constructor(private http:HttpClient) { }
public getPerson(): Observable<person>{
return this.http.get<person>(this.URL+'find/profile');
}
}
After I bring the data to the component by putting {{person.name}}, {{person.lastname}}, {{person.aboutme}} in the html file. I left the image empty and it works just fine.
HERE IS THE PROBLEM WITH THE OTHER TABLE:
CONTROLLER (JAVA):
package com.portfoliocardone.portfoliocardone.Controller;
import com.portfoliocardone.portfoliocardone.Entity.Experience;
import com.portfoliocardone.portfoliocardone.Interface.IExperienceService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin(origins = "https://portfoliocardone.web.app")
public class ExperienceController {
#Autowired IExperienceService iexperienceService;
#GetMapping("/experience/get")
public List<Experience> getExperience(){
return iexperienceService.getExperience();
}
#PostMapping("/experience/new")
public String createExperience(#RequestBody Experience experience){
iexperienceService.saveExperience(experience);
return "The experience was created correctly";
}
#DeleteMapping("/experience/delete/{id}")
public String deleteExperience(#PathVariable Long id){
iexperienceService.deleteExperience(id);
return "The experience was deleted correctly";
}
//URL:PORT/experience/edit/id/title & time & location & description
#PutMapping("/experience/edit/{id}")
public Experience editExperience(#PathVariable Long id,
#RequestParam("title") String newTitle,
#RequestParam("time") String newTime,
#RequestParam("location") String newLocation,
#RequestParam("description") String newDescription){
Experience experience = iexperienceService.findExperience(id);
experience.setTitle(newTitle);
experience.setTime(newTime);
experience.setLocation(newLocation);
experience.setDescription(newDescription);
iexperienceService.saveExperience(experience);
return experience;
}
#GetMapping("/experience/find/profile/{id}")
public Experience findExperience(#PathVariable("id") Long id){
return iexperienceService.findExperience((long)id);
}
}
ANGULAR SERVICE
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { experience } from '../model/experience.model';
#Injectable({
providedIn: 'root'
})
export class ExperienceService {
URL = 'https://portfoliocardone.herokuapp.com/experience/';
constructor(private http:HttpClient) { }
public getExperience(): Observable<experience>{
return this.http.get<experience>(this.URL+'find/profile/{id}');
}
}
ERRORS I GET IN CONSOLE:
headers: An, status: 400, statusText: 'OK', url:...
Does someone know how to be able to bring the data from this second table? Thanks!

UnsatisfiedDependencyException: Error creating bean with name 'locationController'

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'locationController': Unsatisfied
dependency expressed through field 'locationRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'locationRepository' defined in
com.abunyc.location.repository.LocationRepository defined in
#EnableJpaRepositories declared on
JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Validation failed for query for
method public abstract java.util.List
com.abunyc.location.repository.LocationRepository.findTypeAndCount()!
ReportUtil.java
package com.abunyc.location.util;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
public interface ReportUtil {
void generatePieChart(String path, List<Object[]> data );
}
ReportUtilImpl.java
package com.abunyc.location.util;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.stereotype.Component;
#Component
public class ReportUtilImpl implements ReportUtil {
#Override
public void generatePieChart(String path, List<Object[]> data) {
DefaultPieDataset dataset = new DefaultPieDataset();
for (Object[] objects : data) {
dataset.setValue(objects[0].toString(), new Double(objects[1].toString()));
}
JFreeChart chart = ChartFactory.createPieChart3D("Location Type Report", dataset);
try {
ChartUtilities.saveChartAsJPEG(new File(path + "/pieChart.jpeg"), chart, 300, 300);
} catch (IOException e) {
e.printStackTrace();
}
}
}
LocationReportory.java##
package com.abunyc.location.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.abunyc.location.entities.Location;
/**
* #author Abu
*/
#Repository
public interface LocationRepository extends JpaRepository<Location, Integer> {
#Query("select type, count(type) from location_tbl group by type")
public List<Object[]> findTypeAndCount();
}
LocationController.java
package com.abunyc.location.controller;
import java.util.List;
import java.util.Optional;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.abunyc.location.entities.Location;
import com.abunyc.location.repository.LocationRepository;
import com.abunyc.location.service.LocationService;
import com.abunyc.location.util.EmailUtil;
import com.abunyc.location.util.ReportUtil;
/**
* #author Abu
*/
#Controller
public class LocationController {
#Autowired
LocationRepository locationRepository;
#Autowired
LocationService locationService;
#Autowired
EmailUtil emailUtil;
#Autowired
ReportUtil reportUtil;
#Autowired
ServletContext servletContext;
#RequestMapping("/showCreate")
public String showCreate() {
return "createLocation";
}
#RequestMapping(value = "/saveLoc", method = RequestMethod.POST)
public String saveLocation(#ModelAttribute("location") Location location, ModelMap modelMap) {
Location locationSaved = locationService.createLocation(location);
String msg = "Location Saved with id " + locationSaved.getId();
modelMap.addAttribute("successMsg", msg);
//Email calls to send email.
emailUtil.sendEmail("codeexample7#gmail.com", "Location Saved",
"Location Saved successfully and success response was returned to the calling page");
return "createLocation";
}
#RequestMapping("/displayLocation")
public String displayLocation(ModelMap modelMap) {
List<Location> locations = locationService.getAllLocation();
modelMap.addAttribute("locations", locations);
return "displayLocation";
}
#RequestMapping("/deleteLocation")
public String deleteLocation(#RequestParam("id") int id, ModelMap modelMap) {
Location location = new Location();
location.setId(id);
locationService.deleteLocation(location);
// Reloading with all remaining datas
List<Location> locations = locationService.getAllLocation();
modelMap.addAttribute("locations", locations);
return "displayLocation";
}
#RequestMapping("/showUpdate")
public String showUpdateLocation(#RequestParam("id") int id, ModelMap modelMap) {
Optional<Location> location = locationService.getLocationById(id);
if (location.isPresent()) {
Location locationUpdate = location.get();
modelMap.addAttribute("location", locationUpdate);
}
return "updateLocation";
}
#RequestMapping("/updateLoc")
public String updateLocation(#ModelAttribute("location") Location location, ModelMap modelMap) {
locationService.updateLocation(location);
List<Location> aLllocation = locationService.getAllLocation();
modelMap.addAttribute("locations", aLllocation);
return "displayLocation";
}
#RequestMapping("/generateReport")
public String generateReport() {
List<Object[]> data = locationRepository.findTypeAndCount();
String path = servletContext.getRealPath("/");
reportUtil.generatePieChart(path, data);
return "report";
}
}

Wrong Pageable data displayed in my browser

I am trying to display data from MySQL database using spring data with Pageable class. I am new in Spring Data and unfortunately I get all rows shown in my browser, instead of some.
Find below my code
pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
ProductDaoImpl
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.model.Product;
#Repository
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#SuppressWarnings("unchecked")
public Page<Product> getPageProduct(#Param("libelleProduct")String libelleProduct, Pageable pageable) {
List<Product> listProduct = sessionFactory.getCurrentSession().createQuery("From Product p where p.libelleProduct like :libelleProduct").setParameter("libelleProduct", libelleProduct).list();
Page<Product> pageProduct = new PageImpl<Product>(listProduct, pageable, listProduct.size());
return pageProduct;
}
}
ProductService
package com.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.dao.ProductDao;
import com.model.Product;
#Service
#Transactional
public class ProductServiceImpl implements ProductService {
#Autowired
private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
public Page<Product> getPageProduct(String libelleProduct, int page, int size) {
return productDao.getPageProduct(libelleProduct, new PageRequest(page, size));
}
}
ProductController
package com.controller;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.model.Product;
import com.service.ProductService;
#RestController
public class ProductController {
public Logger logger = Logger.getLogger(ProductController.class);
public ProductController(){
System.out.println("ProductController()");
}
#Autowired
private ProductService service;
#RequestMapping(value="/listedesproduit", method=RequestMethod.GET, headers="Accept=application/json")
#ResponseBody
public Page<Product> getPageProduct(){
Page<Product> pageProduct = service.getPageProduct("%e%",0, 1);
pageProduct.forEach(p->System.out.println(p.getLibelleProduct()));
return pageProduct;
}
}
Find below the result I get in my browser, I get four rows shown instead of one on each page.
{"content":[{"idProduct":2,"libelleProduct":"sprite","qteProduct":5},{"idProduct":3,"libelleProduct":"eku","qteProduct":5},{"idProduct":4,"libelleProduct":"33 export","qteProduct":5},{"idProduct":6,"libelleProduct":"guiness","qteProduct":5}],"size":1,"number":0,"numberOfElements":4,"sort":null,"totalPages":4,"totalElements":4,"firstPage":true,"lastPage":false}
Can you please help me to find what I do wrong?
You are using it wrong here:
List<Product> listProduct = sessionFactory.getCurrentSession()
.createQuery("From Product p where p.libelleProduct like :libelleProduct")
.setParameter("libelleProduct", libelleProduct).list();
Page<Product> pageProduct = new PageImpl<Product>(listProduct, pageable, listProduct.size());
You are basically loading all the query results and then returning it in a PageImpl, which is just a wrapper of the data.
You should create a PagingAndSortingRepository and call query methods passing the Pageable, which is the page request to be executed by the repository.
If this doesn't make sense to you, look for tutorials about "spring data paging" like this one and take a look at the documentation.

How to properly #Autowire a component in a Spring Boot App

I'm putting together a simple Spring Boot app, and having an issue with an #Autowired field not "showing up".
My main app class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringElasticCatalogApi {
public static void main(String[] args) {
SpringApplication.run(SpringElasticCatalogApi.class, args);
}
}
My Repository class:
import com.discover.harmony.elastic.model.Customer;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface CustomerRepository extends ElasticsearchRepository<Customer, String> {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
This class ("Loaders") requires an #Autowired repository field, which is NULL:
import com.discover.harmony.elastic.model.BusinessMetadata;
import com.discover.harmony.elastic.model.Customer;
//import com.discover.harmony.elastic.repository.CustomerRepository;
import com.discover.harmony.elastic.api.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
//#Configuration
#Component
public class Loaders {
#Autowired
private CustomerRepository repository;
#PostConstruct
#Transactional
public void loadAll(){
this.repository.deleteAll();
saveCustomers();
fetchAllCustomers();
fetchIndividualCustomers();
}
private void saveCustomers() {
this.repository.save(new Customer("Alice", "Smith"));
this.repository.save(new Customer("Bob", "Smith"));
}
private void fetchAllCustomers() {
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : this.repository.findAll()) {
System.out.println(customer);
}
System.out.println();
}
private void fetchIndividualCustomers() {
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(this.repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : this.repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
private List<BusinessMetadata> getData() {
List<BusinessMetadata> metadata = new ArrayList<>();
metadata.add(new BusinessMetadata((long)1,"TradeLine"));
metadata.add(new BusinessMetadata((long)2,"Credit Line"));
metadata.add(new BusinessMetadata((long)3,"Other Line"));
return metadata;
}
}
What should I change, to make the #Autowire work as expected here?
The problem is that your example is not complete on implementing the ElasticSearch. To proof this, turn your CustomerRepository into a class and remove ElasticsearchRepository<Customer, String> then everything goes fine.
What you need to do is adding a new Configuration class, with #EnableElasticsearchRepositories(basePackages = "com.discover.harmony.elastic.api.CustomerRepository") to scan the provided package for Spring Data repositories.
You can find a complete example here.

Dependency Injection in JHipster with Mybatis

I have little problem with Spring and Mybatis connection in JHipster framework( (out of the box).
Problem is occurred when I try inject class, which have Mybatis mapper injected. In this situation class returns null pointer exception. When I try to autowire this class I get "cannot find candidate to autowire error".
Architecture of class:
Repository(Mybatis mapper interface) ->
ServiceImplementation (Class with injected Mybatis Repository, business logic) ->
Resource (REST controller with instance of Service)
I think solution is simple, but I cannot find right implementation:
Service Implementation is invisible for Spring Beans Mapper and I
can't find in JHipster configuration for them.
I have to use another annotation to get right injection of Service
Implemenation
Somebody meet with this situation and can get litte clue for me to refactor my code? :-) Thanks
Code:
Repository
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.apache.ibatis.annotations.Insert;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import pl.xxx.xxx.domain.City;
import pl.xxx.xxx.domain.Dish;
#Mapper
public interface CityMapper {
#Select("SELECT * FROM CITY WHERE id = #{id}")
City getCityByID(#Param("id") Long id);
#Select("SELECT * FROM CITY WHERE name = #{name}")
City getCityByName(#Param("name") String name);
#Insert("INSERT INTO CITY('name') VALUES(#{name})")
void createCity(City city);
#Delete("DELETE FROM CITY WHERE id = #{id}")
void deleteCityByID(City city);
#Select("SELECT count(*) FROM CITY")
int getNumberOfCities();
#Select("<script>"
+ "SELECT * FROM CITY "
+ "</script>")
List<City> findAll();
}
Service
package pl.xxx.xxx.service.impl;
import java.util.List;
import javax.inject.Inject;
import pl.xxxx.xxxx.domain.City;
import pl.xxxx.xxx.repository.CityMapper;
import pl.xxx.xxx.service.CityService;
import pl.xxx.xxx.web.rest.util.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Bean;
#Service
#Transactional
public class CityServiceImpl implements CityService {
#Inject
private CityMapper cityMapper;
#Override
public List<City> findAll(Pageable pageable) {
return cityMapper.findAll();
}
}
Interface
package pl.xxx.xxx.service;
import java.util.List;
import pl.xxx.xxx.domain.City;
import pl.xxxx.xxx.domain.Dish;
import pl.xxx.xxx.web.rest.util.Pageable;
public interface CityService {
/**
* Get all the dishes.
*
* #param pageable the pagination information
* #return the list of entities
*/
List<City> findAll(Pageable pageable);
}
Resource
package pl.xxx.xxxx.web.rest;
import com.codahale.metrics.annotation.Timed;
import pl.xxx.xxx.xxx.City;
import pl.xxx.xxx.domain.Dish;
import pl.xxx.xxx.repository.CityMapper;
import pl.xxx.xxx.service.impl.CityServiceImpl;
import pl.xxx.xxx.web.rest.util.Pageable;
import pl.xxx.xxx.web.rest.util.PaginationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Resource;
import javax.inject.Inject;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing City.
*/
#RestController
#RequestMapping("/api")
public class CityResource {
private final Logger log = LoggerFactory.getLogger(CityResource.class);
private CityServiceImpl cityServiceImpl;
#Inject
private CityMapper cityMapper;
/**
* GET /Cities: get all the cities.
*
* #param pageable the pagination information
* #return the ResponseEntity with status 200 (OK) and the list of citires in body
* #throws URISyntaxException if there is an error to generate the pagination HTTP getHeaders()
*/
#RequestMapping(value = "/cities",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed()
public ResponseEntity<List<City>> getAllCities(Pageable pageable)
throws URISyntaxException {
log.debug("REST request to get a page of Cities");
Pageable p = new Pageable();
List<City> page = cityServiceImpl.findAll(p);
HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeadersLM("/api/cities");
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
}

Categories

Resources