Controller class:
#RestController
#RequestMapping("/allergen")
public class AllergenController {
#Autowired
AllergenService allergenService;
#GetMapping
public ResponseEntity<List<Allergen>> getAll() {
List<Allergen> allergens = new ArrayList<>(allergenService.getAllAllergens());
if(allergens.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(allergens, HttpStatus.OK);
}
#GetMapping("{id}")
public ResponseEntity<Allergen> getById(#PathVariable(value = "id") Long allergenId) throws ResourceNotFoundException {
return new ResponseEntity<>(allergenService.getAllergenById(allergenId), HttpStatus.OK);
}
#PostMapping(consumes = "application/json")
public ResponseEntity<Allergen> createAllergen(#Valid #RequestBody Allergen allergen) throws AlreadyExistsException {
return new ResponseEntity<>(allergenService.createAllergen(allergen), HttpStatus.OK);
}
#PutMapping("{id}")
public ResponseEntity<Allergen> updateAllergen(#PathVariable(value = "id") Long allergenId,
#Valid #RequestBody Allergen allergen) throws ResourceNotFoundException, AlreadyExistsException {
return new ResponseEntity<>(allergenService.updateAllergen(allergen, allergenId), HttpStatus.OK);
}
#DeleteMapping("{id}")
public ResponseEntity<String> deleteAllergen(#PathVariable(value = "id") Long allergenId) throws ResourceNotFoundException {
allergenService.deleteAllergen(allergenId);
return new ResponseEntity<>("Allergen with id " + allergenId + " successfully deleted", HttpStatus.OK);
}
}
Test class:
#SpringBootTest
#AutoConfigureMockMvc
public class AllergenControllerTest {
private static final String ALLERGEN_TEST_NAMING = "AllergenType";
private static final String URL = "/allergen/";
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#Autowired
private AllergenRepository allergenRepository;
#AfterEach
public void tearDown() {
allergenRepository.deleteAll();
}
#Test
public void getAllTest() throws Exception {
String testType = "getAll";
createAllergen(testType, true);
createAllergen(testType + 2, true);
this.mockMvc
.perform(get(URL)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andReturn();
}
#Test
public void getByIdTest() throws Exception {
String testType = "getById";
Allergen allergen = createAllergen(testType, true);
this.mockMvc
.perform(get(URL + allergen.getId())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.name").value(testType + ALLERGEN_TEST_NAMING))
.andReturn();
}
#Test
public void createTest() throws Exception {
String testType = "create";
Allergen allergen = createAllergen(testType, false);
this.mockMvc
.perform(post(URL)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(allergen))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.name").value(testType + ALLERGEN_TEST_NAMING))
.andDo(result -> System.out.println(result.getResponse().getContentAsString()))
.andReturn();
}
#Test
public void updateTest() throws Exception {
String testType = "update";
Allergen allergen = createAllergen(testType, true);
Allergen updatedAllergen = new Allergen();
updatedAllergen.setName("updateTestAllergenModified");
this.mockMvc
.perform(put(URL + allergen.getId())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedAllergen))
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.name").value("updateTestAllergenModified"))
.andReturn();
}
#Test
public void deleteTest() throws Exception {
String testType = "delete";
createAllergen(testType, true);
String tempId = String.valueOf(allergenRepository.findAll().get(0).getId());
this.mockMvc
.perform(delete(URL + tempId)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andReturn();
}
private Allergen createAllergen(String testType, Boolean saveAllergen) {
Allergen allergen = new Allergen();
allergen.setName(testType + ALLERGEN_TEST_NAMING);
if(saveAllergen) allergenRepository.save(allergen);
return allergen;
}
}
When running createTest test, I'm getting
java.lang.AssertionError: Status expected:<200> but was:<415>
Expected :200
Actual :415
This is the response I'm getting:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /allergen/
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"36"]
Body = {"id":0,"name":"createAllergenType"}
Session Attrs = {}
Handler:
Type = com.personal.stockcontroltest.controller.AllergenController
Method = com.personal.stockcontroltest.controller.AllergenController#createAllergen(Allergen)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 415
Error message = null
Headers = [Accept:"application/json, application/*+json"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
I know it means Unsupported Media Type but how to solve the problem?
It also started happening only after changing from JUnit4 to JUnit5.
I've also tried adding #EnableWebMvc on the Controller class, but it did not fix the problem.
Thanks in advance.
Related
I have a mapping to patch data:
#Data
#NoArgsConstructor
public class CertificateUpdateDTO {
#InjectString
private String name;
#InjectString
private String description;
#Min(value = 0, message = "Price cannot be negative")
private double price;
#Min(value = 1, message = "Duration cannot be less than one day")
private int duration;
}
#ApiOperation("Update certificate by id")
#ApiResponses({
#ApiResponse(code = 200, message = "If updated successfully or certificate doesn't exist"),
#ApiResponse(code = 400, message = "If JSON object in request body is invalid"),
#ApiResponse(code = 404, message = "Certificate with given id doesn't exist")
})
#PatchMapping(value = "/{id}", consumes = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity update(#PathVariable int id, #Valid #DefaultDto CertificateUpdateDTO certificateUpdateDTO){
if(certificateService.updateCertificate(id, certificateUpdateDTO)){
return ResponseEntity.ok().build();
}
return ResponseEntity.notFound().build();
}
#DefaultDto and #InjectString are my annotations, they just do same as #RequestBody and inject default value to string fields annotated by #InjectString, it works fine.
I need to check if request to this mapping with id 1 returns 404, and it works from curl:
curl -X PATCH -H "Content-Type: application/json" -d '{"duration": "10", "price": "10"}' localhost:8080/v1/certificate/1
Response code of curl is 404.
But when i try to run test it returns 400:
#ExtendWith(SpringExtension.class)
#ContextConfiguration(classes = ControllerTestConfiguration.class, loader = AnnotationConfigContextLoader.class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CertificateControllerTest {
#Autowired
private CertificateService certificateService;
#Autowired
private CertificateController certificateController;
private ObjectMapper objectMapper = new ObjectMapper();
private MockMvc mockMvc;
#BeforeAll
public void init(){
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).build();
}
#AfterEach
public void postEach(){
reset(certificateService);
}
...
#Test
#SneakyThrows
public void updateFailTest(){
CertificateUpdateDTO certificateUpdateDTO = new CertificateUpdateDTO();
certificateUpdateDTO.setName("c1");
certificateUpdateDTO.setDescription("desk");
certificateUpdateDTO.setDuration(10);
certificateUpdateDTO.setPrice(10);
when(certificateService.updateCertificate(1, certificateUpdateDTO)).thenReturn(false);
mockMvc.perform(patch("/v1/certificate/1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(certificateUpdateDTO))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(404));
verify(certificateService, times(1)).updateCertificate(1, certificateUpdateDTO);
}
}
Configuration for current test class is:
#Configuration
public class ControllerTestConfiguration {
...
#Bean
public CertificateService certificateService(){
return mock(CertificateService.class);
}
#Bean
public CertificateController certificateController(){
return new CertificateController(certificateService());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Error message says that duration is invalid: duration = 0
UPD:
I tried to remove #Valid and saw that my annotations don't work in testing enviroment, that how i'm processing them:
public class DefaultValueHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
#Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(DefaultDto.class) != null;
}
#Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest servletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
BufferedReader reader = servletRequest.getReader();
String body = reader.lines().collect(Collectors.joining());
Class<?> clazz = methodParameter.getParameterType();
Object dto = new ObjectMapper().readValue(body, clazz);
for(Field field : clazz.getDeclaredFields()){
InjectString annotation = field.getAnnotation(InjectString.class);
if(annotation != null){
field.setAccessible(true);
if(ReflectionUtils.getField(field, dto) == null) {
ReflectionUtils.setField(field, dto, annotation.value());
}
}
}
return dto;
}
}
And that how i register MethodResolver:
public class AppConfig implements WebMvcConfigurer {
private final Environment env;
#Autowired
public AppConfig(Environment env) {
this.env = env;
}
...
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new DefaultValueHandlerMethodArgumentResolver());
}
...
}
After a little bit of researching and my leed fiend's help i found solution :)
To add custom ArgumentResolver you should register it in your MockMvcBuilder.
Change this:
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).build();
To this:
mockMvc = MockMvcBuilders.standaloneSetup(certificateController).setCustomArgumentResolvers(new DefaultValueHandlerMethodArgumentResolver()).build();
I have a Service Class which has following method
NewCartService.java:
#Service
public class NewCartService {
#Autowired
private LoginRepository loginRepository;
#Autowired
private ProductRepository productRepository;
#Autowired
private CartRepository cartRepository;
#Autowired
private CartDao cartDao;
#Autowired
private Mailer mailService;
public MessageResponse order(List<Cart> cart) throws MessagingException {
for (Cart cart1 : cart) {
String userName = cart1.getUserName();
String password = cart1.getPassword();
String productName = cart1.getProductName();
String price = cart1.getPrice();
String discription = cart1.getDiscription();
if (!cartRepository.existsAllByUserNameAndPasswordAndProductNameAndPriceAndDiscription(userName, password, productName, price, discription)) {
throw new ResourceNotFoundException("not found");
}
MustacheFactory mf = new DefaultMustacheFactory();
Mustache m = mf.compile("cart.mustache");
StringWriter writer = new StringWriter();
String messageText = "";
List<Cart> carts = cartDao.getCart(cart);
Map<String, Object> params = new HashMap<>();
params.put("carts", carts);
Writer m1 = m.execute(writer, params);
System.out.println(m1);
messageText = m1.toString();
mailService.sendMail("/*email address*/", "/*email address*/", messageText, "demo", true);
cartRepository.deleteByUserNameAndPasswordAndProductNameAndPriceAndDiscription(userName, password, productName, price, discription);
return new MessageResponse("product Successfully ordered from cart");
}
throw new BadArgumentsException("bad arguments");
}
}
I have controller
CartController.java:
#RestController
public class CartController {
#Autowired
public CartService cartService;
#GetMapping("/orders")
public ResponseEntity<?> orders(#Valid #RequestBody List<Cart> carts) throws MessagingException {
return newCartService.order(carts);// it gives error because i need to convert MessageResponse into the ResponseEntity<?>
}
}
Now my Question is that how can i convert these MessageResponse into the ResponseEntity<?> ?
please suggest me code so that i can solve these issue and Thanks in Advance.
Have you tried:
return new ResponseEntity<>(newCartService.order(carts), HttpStatus.OK);
or as suggested in the comments:
return ResponseEntity.ok(newCartService.order(carts));
In addition if you want set header with response entity you can try:
HttpHeaders headers = new HttpHeaders();
headers.add("Custom-Header", "<header>");
return new ResponseEntity<>(newCartService.order(carts), headers, HttpStatus.OK);
alternative you can use:
return ResponseEntity.ok()
.header("Custom-Header", "<header>")
.body(newCartService.order(carts));
This is the actual code
RateNegotiationController.java
#GetMapping(value = "/rate-negotiation/{uniqueId}", produces = {APPLICATION_JSON_VALUE})
public ResponseEntity<RateNegotiation> rateNegotiationByUniqueId(#PathVariable(name = "uniqueId") final String uniqueId) {
final RateNegotiation rateNegotiation =
rateNegotiationService.retrieveRateNegotiationsByUniqueId(uniqueId);
final Optional<String> courierID = validationUtils.getCourierIDFromToken();
if (courierID.isPresent()) {
if (!courierID.get().equals(rateNegotiation.getCourierId())) {
return ResponseEntity.notFound().build();
}
log.info("RateNegotiationController, rateNegotiationByUniqueId {} ", rateNegotiation);
return ResponseEntity.ok(rateNegotiation);
}
throw new CourierIdNotFoundException(COURIER_ID_NOT_FOUND);
}
ValidationUtils.java
public Optional<String> getCourierIDFromToken() {
if (appConfigBean.isSecurityEnabled()) {
return Optional.of(requestPayloadValidator.getCourierIDFromToken());
}
return Optional.empty();
}
I am writing the testcase for this one ..
#MockBean
private ValidationUtils validationUtils;
#MockBean
private AppConfigBean appConfigBean;
#MockBean
private RequestPayloadValidator requestPayloadValidator;
#Test
public void shouldRetrieveRateNegotiationDetailsByUniqueId(){
when(validationUtils.getCourierIDFromToken()).thenReturn(Optional.of("123456"));
when(appConfigBean.isSecurityEnabled()).thenReturn(true);
when(requestPayloadValidator.getCourierIDFromToken()).thenReturn("123456");
rateNegotiationServiceWireMockRule.stubFor(WireMock.get(urlEqualTo(RETRIEVE_RATE_NEGOTIATION_BY_UNIQUE_ID_PATH))
.willReturn(aResponse()
.withHeader(CONTENT_TYPE, APPLICATION_JSON_CHARSET)
.withBodyFile("RateNegotiationByUniqueId.json")
.withStatus(200)
)
);
given()
.port(port)
.when()
.header(CONTENT_TYPE, APPLICATION_JSON_CHARSET)
.get(RETRIEVE_RATE_NEGOTIATION_BY_UNIQUE_ID_URL)
.then()
.assertThat()
.statusCode(200);
}
but still it is not wokring and , showing error,CourierIdNotFoundException: Courier ID not found
I have mock the method validationUtils.getCourierIDFromToken() but still it is not wokring
can anyone please help ?
DemoAppController.java
package com.application.packagename.controller;
#RestController
#Api(value="demoappcontroller", description="Application configuration")
#RequestMapping("app")
#ApiIgnore
public class DemoAppController {
#Autowired
SomeService service;
#ApiOperation(value = "demo app config", response = DemoReponse.class)
#RequestMapping(value="/v1/getDemoAppInfo", produces = "application/json", method= RequestMethod.GET)
public ResponseEntity getDesc(#Valid DemoAppRequest demoAppRequest) {
DemoReponse response = service.getDemoAppInfo(demoAppRequest.getVarNameOne(),
demoAppRequest.getEnvType());
return new ResponseEntity(response, HttpStatus.OK);
}
}
DemoAppRequest.java
package com.application.packagename.model;
#Data
#Component("demoapprequestVo")
#ApiModel("demoapprequestVo")
public class DemoAppRequest {
#ApiModelProperty(example = "value1")
public String varNameOne;
#ApiModelProperty(example = "value2")
public String varNameTwo;
}
DemoAppControllerTest.java
public class DemoAppControllerTest extends TestServiceApiIntegerationTest {
private MultiValueMap<String, String> requestParams;
private URI url;
#BeforeEach
void init() {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("varNameOne", "value 1");
params.add("varNameTwo", "value 2");
requestParams = params;
url = URI.create("/app/v1/getDemoAppInfo/");
}
#Test
public void testGetDesc() throws Exception {
mockMvc.perform(get(url)
.params(requestParams))
.andExpect(status().isOk());
}
}
TestServiceApiIntegerationTest.java
#SpringBootTest
#AutoConfigureMockMvc
public class TestServiceApiIntegerationTest {
#Autowired
protected MockMvc mockMvc;
}
This is just a template for unit testing , you can follow and implement it in your project.
I have a service class, that executes user's request:
public class UnitServiceImpl extends HttpRequestServiceImpl implements UnitService {
private final UnitRepository unitRepository;
public UnitServiceImpl(UnitRepository unitRepository) {
this.unitRepository = unitRepository;
}
#Override
public Unit addUnit(String unitName) {
final Unit unit = new Unit();
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Unit getUnit(int id) {
final Unit unit = unitRepository.findById(id);
if (unit == null) {
throw new EntityNotFoundException("Unit is not found");
}
return unit;
}
#Override
public Unit updateUnit(int id, String unitName) {
final Unit unit = getUnit(id);
unit.setUnitName(unitName);
return unitRepository.save(unit);
}
#Override
public Iterable<Unit> getAllUnits() {
return unitRepository.findAll();
}
}
Controller, that's use Service:
#RestController
public class UnitController {
private final UnitService managementService;
public UnitController(UnitService managementService) {
this.managementService = managementService;
}
#GetMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Iterable<Unit>> getAllUnits() {
final Iterable<Unit> allUnits = managementService.getAllUnits();
return new ResponseEntity<>(allUnits, HttpStatus.OK);
}
#PostMapping(value = "/unit", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> addUnit(HttpServletRequest request) throws FieldsIsAbsentException {
final String unitName = managementService.getParameter(request, "unit_name");
final Unit unit = managementService.addUnit(unitName);
return new ResponseEntity<>(unit, HttpStatus.CREATED);
}
#GetMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> getUnitById(#PathVariable("id") int id) {
final Unit unit = managementService.getUnit(id);
return new ResponseEntity<>(unit, HttpStatus.OK);
}
#PutMapping(value = "/unit/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Unit> updateUnit(HttpServletRequest request, #PathVariable("id") int id) {
final String unitName = managementService.getParameter(request, "unit_name");
return new ResponseEntity<>(managementService.updateUnit(id, unitName), HttpStatus.ACCEPTED);
}
}
I created unit tests. They are mockito methods isn't working. All test methods doing request to database. Test class:
#SpringBootTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationTestConfig.class)
#WebAppConfiguration
#AutoConfigureMockMvc
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#Mock
UnitService unitService;
#Autowired
private UnitController unitController;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
this.mockMvc = MockMvcBuilders.standaloneSetup(unitController)
.setControllerAdvice(new ExceptionHandlingController()).build();
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
#Test
void testGetAllUnits() throws Exception {
when(this.unitService.getAllUnits()).thenReturn(units);
mockMvc.perform(get("/unit"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitNotFound() throws Exception {
int id = -1;
given(this.unitService.getUnit(id)).willThrow(EntityNotFoundException.class);
mockMvc.perform(get("/unit/" + id))
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_JSON));
}
#Test
void testUnitFound() throws Exception {
int id = 5;
Unit unitWithName = new Unit();
unitWithName.setId(id);
unitWithName.setUnitName("NameUnit");
given(unitService.getUnit(id)).willReturn(unitWithName);
mockMvc.perform(get("/unit/" + id).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(id))
.andExpect(jsonPath("$.unitName").value(unitWithName.getUnitName()));
}
#Test
void testAddUnit() throws Exception {
Unit unit = new Unit();
unit.setId(1);
unit.setUnitName("TestUnit");
given(unitService.addUnit("TestUnit")).willReturn(unit);
mockMvc.perform(post("/unit").param("unit_name", "TestUnit"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.unitName").value(unit.getUnitName()))
.andExpect(jsonPath("$.id").value(1));
}
}
This code is trying to read or write to database. I've tried so many variants.
I've been trying to write tests for a few days.=( What is the error?
I've changed my test class onto next code and it works now:
#WebMvcTest(UnitController.class)
class UnitControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
UnitService unitService;
private final List<Unit> units = new ArrayList<>();
#BeforeEach
public void initUnits() {
Unit unit = new Unit();
unit.setUnitName("someUnit 1");
unit.setId(1);
units.add(unit);
unit = new Unit();
unit.setId(2);
unit.setUnitName("Some unit 2");
units.add(unit);
}
///test methods
I have a Rest API Created with Spring Framework 3.2.4. I am trying to write test cases in the WebApplicationContext. I see from the server log that the xml configuration files are loaded but it fails while executing the TestContextManager.
ROR org.springframework.test.context.TestContextManager- Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#4c980278] to prepare test instance
Here is my Test Class:
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class })
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = {"file:WebContent/WEB-INF/applicationContext.xml","file:WebContent/WEB-INF/spring-security.xml","file:WebContent/WEB-INF/spring-servlet.xml"})
public class AppControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setUp() {
//Mockito.reset();//awesome_service
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
#Test
public void testGetSignupForm() throws Exception {
this.mockMvc.perform(get("/apps"))
.andExpect(status().isOk());
}
}
Here is my Controller
#Controller
#RequestMapping(value = "/apps")
public class AppController
{
#Resource(name = "appAPIService")
private AppAPIService appAPIService;
#Resource(name = "applicationVersionService")
private ApplicationVersionService applicationVersionService;
#Resource(name = "applicationService")
private ApplicationService applicationService;
#Autowired
Validator validator;
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
#InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Model.class, "model", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
BasicDBObject obj = (BasicDBObject)JSON.parse(text);
Model model = new Model();
model.setPrice(obj.getInt(ApplicationFields.MODEL_PRICE,0));
model.setTrial(obj.getInt(ApplicationFields.MODEL_TRIAL,0));
model.setType(obj.getString(ApplicationFields.MODEL_TYPE));
setValue(model);
}
});
}
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> find(HttpServletRequest request, #RequestParam(value="query", required=false) String queryString, #RequestParam(value="sort", required=false) String sortString, #RequestParam(value="pageNumber", required=false) Integer pageNumber, #RequestParam(value="limit", required=false) Integer limit, #RequestParam(value="userId", required=false) String hostUserId)
{
ObjectId marketplaceId = null;
try
{
marketplaceId = AuthenticationUtils.getUserId();
BasicDBObject query;
try
{
query = FormatUtils.toJsonObject(queryString);
}
catch(Exception e)
{
return ResponseUtils.badRequest("query", "Invalid query: " + queryString);
}
BasicDBObject sort;
try
{
sort = FormatUtils.toJsonObject(sortString);
}
catch(Exception e)
{
return ResponseUtils.badRequest("sort", "Invalid sort: " + sortString);
}
return appAPIService.find(marketplaceId, query, sort, pageNumber, limit, hostUserId);
}
catch (Exception e)
{
String message = "Unable to find apps";
ToStringBuilder builder = new ToStringBuilder(message);
LoggingUtils.addToBuilder(builder, request);
builder.append("marketplaceId", AuthenticationUtils.getUserId());
LOGGER.error(builder.toString(), e);
return ResponseUtils.internalError();
}
}
....
}