I am trying to Stream results from a Spring Data Rest Call and am getting the error:
java.lang.IllegalArgumentException: PersistentEntity must not be null!
The call works when I do not try to stream the results. Any insight is appreciated.
Here is the Repository definition:
/**
*
*/
package com.xxx.beverage.repository.db2;
import java.util.List;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.transaction.annotation.Transactional;
import com.xxx.xxx.model.db2.Vbrk;
#RepositoryRestResource
public interface VbrkRepository extends PagingAndSortingRepository<Vbrk, String> {
Vbrk findOne(String id);
#RestResource(path="findByKunag")
#Query(value="SELECT * FROM VBRK v WHERE v.KUNAG = :kunag ", nativeQuery=true)
Stream<Vbrk> findByKunagAndStream(#Param("kunag") String kunag);
Page<Vbrk> findAll(Pageable pageable);
}
Related
I Upgraded Project to SpringBoot Version 2.2.0.RELEASE to 2.7.4.This is the example Repository Interface.
import com.flyaero.aeromasterapiservice.data.AddLanguageRequest;
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.Query;
import org.springframework.data.couchbase.repository.CouchbasePagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
#Repository
#N1qlPrimaryIndexed
public interface LanguageRepository extends CouchbasePagingAndSortingRepository<AddLanguageRequest, String> {
Optional<AddLanguageRequest> findById(String id);
AddLanguageRequest save(AddLanguageRequest entity);
#Query("#{#n1ql.selectEntity} WHERE modelName = 'AddLanguageRequest' AND #{#n1ql.filter}")
List<AddLanguageRequest> findAll();
}
After Change the SpringBoot version to 2.7.4 cannot use CouchbasePagingAndSortingRepository.We can use only CouchbaseRepository. Problem is #Query is not supporting.
import com.flyaero.aeromasterapiservice.data.AddLanguageRequest;
import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed;
import org.springframework.data.couchbase.core.query.Query;
//import org.springframework.data.couchbase.repository.CouchbasePagingAndSortingRepository;
import org.springframework.data.couchbase.repository.CouchbaseRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
#Repository
#N1qlPrimaryIndexed
public interface LanguageRepository extends CouchbaseRepository<AddLanguageRequest, String> {
Optional<AddLanguageRequest> findById(String id);
AddLanguageRequest save(AddLanguageRequest entity);
#Query("#{#n1ql.selectEntity} WHERE modelName = 'AddLanguageRequest' AND #{#n1ql.filter}")
List<AddLanguageRequest> findAll();
}
What would be the best possible options?
Repositories & Queries
org.springframework.data.couchbase.core.query.Query became org.springframework.data.couchbase.repository.Query
More details available in latest Spring Data Couchbase - Reference Documentation https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.repository.multibucket
Hi I am new to spring and have created an Export csv application with two controllers which can give all the data as well as selective columns data and want to write junits for the same but it is quite difficult for me to do the same as I am not aware how i should do it some help would be really great
Main class:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
import net.bytebuddy.implementation.bind.annotation.Super;
#SpringBootApplication
public class ExampleApplication implements CommandLineRunner {
#Autowired
ExampleRepository exampleRepository;
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Example> example= new ArrayList<>();
// create dummy
example.add(new Example(1,"abc","sachin","abc","abc"));
example.add(new Example(2,"abc","rahul","abc","abc"));
example.add(new Example(3,"abc","rahul","abc","abc"));
exampleRepository.saveAll(example);
}
}
Entity layer:
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="example")
public class Example{
#Column(name="city")
private String city;
#Column(name="name")
private String name;
#Column(name="amount")
private String amount;
#Column(name="country")
private String country;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
//getter and setters
}
Repository layer is as follows:
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.model.Example;
#Repository("exampleRepository")
public interface ExampleRepository extends JpaRepository<Example,Long> {
List<Report> findByName(String name);
}
service layer is as follows
package com.example.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
#Transactional
#Service
public class ExampleService {
#Autowired
ExampleRepository exampleRepository;
public List<Example> fetchAll() {
return exampleRepository.findAll();
}
public List<Example> findByName(String name){
return exampleRepository.findByName(name);
}
}
I have 2 controllers one to get all details and one to get selective columns and here we are generating csv files based on records that match the name
COntroller 1:
package com.example.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/demo")
public class Controller1 {
#Autowired
ExampleService exampleService;
#GetMapping("/result")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "names.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(examplesService.findByName(name));
}
}
Controller 2:
package com.reports.controllers;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/example")
public class Controller2 {
#Autowired
ExampleService exampleService;
#GetMapping("/output")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Example.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())
))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(exampleService.findByname(name));
}
}
Try this approach :
generate a file in your /src/test/resources path and then test if it contains the generated data you expected
use combine it with a file system mocking to do it
You will :
test your ResController
mock your Service class
Also use Contructor Injection for you dependency
I am trying to create a webapp but it's not working I am geeting 404 response.
The package structure is like:
com.example.demo
com.example.demo.jerseyConfig.java
com.example.demo.demo.java
com.example.demo.backend.service.userManagementService.java
My Application.java is
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import com.example.pentest.backend.service.userManagementService;
#SpringBootApplication
public class demo {
public static void main(String[] args) {
//new demo().configure(new SpringApplicationBuilder(demo.class)).run(args);
SpringApplication.run(demo.class, args);
}
}
My Jersey config is
package com.example.demo;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.context.annotation.Profile;
import com.example.pentest.backend.service.userManagementService;
import org.springframework.stereotype.Component;
#Component
#ApplicationPath("/")
public class jerseyConfig extends ResourceConfig {
public jerseyConfig() {
register(userManagementService.class);
}
}
My userManagementService.java is
package com.example.demo.backend.service;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.POST;
import javax.ws.rs.GET;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Profile;
#Component
#Path("/backend")
public class userManagementService {
#Path("/user/login")
#GET
#Consumes(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#Produces(MediaType.APPLICATION_JSON_VALUE)
public Response createUser() {
return Response.status(Response.Status.OK).build();
}
}
I am running it on tomcat server, I am seeing no errors. The url I am trying to access is http://localhost:8080/demo/backend/user/login
I built a package to give a authentication handler. That engine will be triggered when a method/class as annotated with #Secured so the ContainerRequestFilter will be triggered.
But I'm using this library in another package and when I annoted a method with the #Secured the ContainerRequestFilter` engine is not triggered. So I need help with that.
I tried to import manually with #Inject and #EJB but when I deployed that application in weblogic container I got some errors about dependency.
AuthenticatePackage -
The interceptor:
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
#Secured
#Provider
#Priority(Priorities.AUTHORIZATION)
public class SecurityInterceptor implements ContainerRequestFilter {
#Context private ResourceInfo resourceInfo;
#Inject private JWTService jwtService;
public static final String AUTHENTICATION_SCHEME = "Bearer";
....
The Annotation
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#NameBinding
#Retention(RUNTIME)
#Target({TYPE, METHOD})
public #interface Secured {
String[] roles() default {};
}
Package when I use that engine
#GET
#Path("/getSignedUser")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Secured
public Response getSignedUser(#HeaderParam("Authorization") String token) {
UserSchema userSchema = this.authenticationService.getSignedUser(token.substring(SecurityInterceptor.AUTHENTICATION_SCHEME.length()).trim());
return Response.status(Response.Status.OK).entity(userSchema).build();
}
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);
}
}