I have the method in my RestController, that accepts an object:
#RestController
#RequestMapping(value = "/statistic")
public class MyController {
#Autowired
private StatisticService statistic;
#RequestMapping(method=RequestMethod.POST, value="/add")
public ResponseEntity<String> add(#RequestBody PersonData personData) {
if(statistic.addToStatistic(personData)) {
return new ResponseEntity<String>(HttpStatus.OK);
}
return new ResponseEntity<String>("Person already exists", HttpStatus.CONFLICT);
}
}
I want to send the object from my another Controller. I only read, that I can send the object to /statistic/add as json via different browser tools (REST clients). But my another controller accepts only "login" (unique name) and it should create the object from this login and send to /statistic/add. Like this I wanted to create json object and send it, but I get the error
org.springframework.web.client.RestClientException: No HttpMessageConverter for org.codehaus.jettison.json.JSONObject
Here is my attempt:
#Controller
#RequestMapping("/main")
public class ViewController {
#RequestMapping(value = "/newPerson/{login}", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> registerNewPerson(#PathVariable String login) {
RestTemplate restTemplate = new RestTemplate();
try {
String uri_create = "http://localhost:8082/add/";
//creation of json doesnt't help
JSONObject entity = new JSONObject();
entity.put("login", login);
entity.put("points", 0);
ResponseEntity<String> responce = restTemplate.postForEntity(uri_create, entity, String.class);
return responce;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
Related
I have restful spring controller with method getUser, I want this method to return user data: name, age, city, etc. and user images.
How can I return java object and files in one response?
#RequestMapping(value = "/getUser", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity getUser(#RequestBody UserRequest req)
{
User user=userProfileService.getUserProfileByEmail(req.getEmail());
Resource resourceImg1 = new ServletContextResource(servletContext, "D:/images/userImg1.jpg");
Resource resourceImg2 = new ServletContextResource(servletContext, "D:/images/userImg2.jpg");
List<Resource> resourcesList = new ArrayList<Resource>();
resourcesList.add(resourceImg1);
resourcesList.add(resourceImg2);
return new ResponseEntity(user, resourcesList, new HttpHeaders(), HttpStatus.OK);
}
I want to return the images and the user
Your response body needs to be a single object. Your best bet is to create an object like
public class UserWithResources() {
private User user;
private List<Resources> resources;
...etc
}
then return the UserWithResources in your response
You can use map to wrap the data,
#RequestMapping(value = "/getUser", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity getUser(#RequestBody UserRequest req)
{
User user=userProfileService.getUserProfileByEmail(req.getEmail());
Resource resourceImg1 = new ServletContextResource(servletContext, "D:/images/userImg1.jpg");
Resource resourceImg2 = new ServletContextResource(servletContext, "D:/images/userImg2.jpg");
List<Resource> resourcesList = new ArrayList<Resource>();
resourcesList.add(resourceImg1);
resourcesList.add(resourceImg2);
Map<String,Object> dataMap=new HashMap<String,Object>();
dataMap.put("user",user);
dataMap.put("resourcesList",resourcesList);
return new ResponseEntity(dataMap,new HttpHeaders(), HttpStatus.OK);
}
I have the following controller which accept input as #RequestParam
#RequestMapping(value = "/fetchstatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response fetchStatus(
#RequestParam(value = "userId", required = true) Integer userId) {
Response response = new Response();
try {
response.setResponse(service.fetchStatus(userId));
response = (Response) Util.getResponse(
response, ResponseCode.SUCCESS, FETCH_STATUS_SUCCESS,
Message.SUCCESS);
} catch (NullValueException e) {
e.printStackTrace();
response = (Response) Util.getResponse(
response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
} catch (Exception e) {
e.printStackTrace();
response = (Response) Util.getResponse(
response, ResponseCode.FAILED, e.getMessage(), Message.ERROR);
}
return response;
}
I need a unit test class for this and I am beginner with spring mvc. I don't know writing test classes with #RequestParam as input.
Any help will be appreciated ..
I solved this issue. I just changed the url. Now it contains the parameter as below in test class:
mockMvc.perform(get("/fetchstatus?userId=1").andExpect(status().isOk());
You can use MockMvc for testing Spring controllers.
#Test
public void testControllerWithMockMvc(){
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllerInstance).build();
mockMvc.perform(get("/fetchstatus").requestAttr("userId", 1))
.andExpect(status().isOk());
}
Also, it is possible to do it using pure JUnit, as long as you need to test only the logic inside your class
#Test
public void testControllerWithPureJUnit(){
Controller controller = new Controller();
//do some mocking if it's needed
Response response = controller.fetchStatus(1);
//asser the reponse from controller
}
I have this class DemoController. In this class I want to send a message along with REST request.
How can I send it? Suppose M sending http://localhost:8080/sendmessage...
How can I send a message along with this request?
#RestController
#EnableAutoConfiguration
public class DemoController {
#Autowired
DemoPublisher demopublisher;
#Autowired
DemoConsumer democonsumer;
#RequestMapping(value="/sendmessage", method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#RequestParam String message, Model model){
try {
demopublisher.demoPublishMessage(message);
} catch (JMSException e) {
e.printStackTrace();
}
return message;
}
}
QueryParam
url: /sendMessage?msg=HelloWorld!
#RequestMapping(value="/sendmessage",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#QueryParam("msg") String message,Model model){
}
UrlParam
url: /sendMessage/HelloWorld!
#RequestMapping(value="/sendmessage/{message}",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#PathVariable String message,Model model){
}
When you are posting data to the server, you can also send data in the body parameter too. I recommend you use this for when you have a form or other data you want to send to the server.
RequestBody
url: /sendMessage
body (RAW in postman or other rest client, accept need to be application/xml):
{
"my message"
}
controller
#RequestMapping(value="/sendmessage",method= {RequestMethod.POST})
#ResponseBody
public String messageSenderController(#RequestBody String message,Model model){
}
I'm handling an exception in my project
This is my GET endpoint:
#RequestMapping(method = RequestMethod.GET)
public ResponseEntity<V6SubnetRec> get(#RequestBody V6SubnetRequest requestBody) throws QIPException {
Site site = getSite(requestBody.getOrganization());
V6SubnetRec wsSubnet = (V6SubnetRec) requestBody.getV6Subnet();
V6SubnetRec v6SubnetRec = null;
try {
v6SubnetRec = getQipService1().getV6Subnets(wsSubnet, site);
} catch (Exception e) {
log.error(Keys.QIP_CALLOUT_ERROR, e);
throw new RestException(e);
}
return new ResponseEntity<V6SubnetRec>(v6SubnetRec, HttpStatus.OK);
}
#ExceptionHandler(RestException.class)
public ResponseEntity rulesForRestException(RestException restEx){
return new ResponseEntity(restEx.getResponse().getContent(), restEx.getResponse().getStatus());
}
RestException.java
#XmlRootElement(name = "RestException")
#XmlAccessorType(XmlAccessType.FIELD)
public class RestException extends RuntimeException{
#XmlElement
RestResponse response;
public RestException(Exception e){
//...
}
}
When I request with URL http://localhost/api/v1/v6subnet.json (return with JSON format), it will return HTTP status code 404 and include the content. It's OK.
But when I request with URL http://localhost/api/v1/v6subnet.xml (return with XML format) with the same request, it return HTTP status code 500 like a normal exception which is not handled as JSON format
I want to have results like when I request to JSON format.
Thanks.
I've fixed my issue. It's only change from
restEx.getResponse().getContent()
into
restEx.getResponse().getContent().toString()
I've an heartbeat API implemeted using Spring REST service:
#RequestMapping(value = "heartbeat", method = RequestMethod.GET, consumes="application/json")
public ResponseEntity<String> getHeartBeat() throws Exception {
String curr_time = myService.getCurrentTime();
return Util.getResponse(curr_time, HttpStatus.OK);
}
And MyService.java has below method:
public String getCurrentTime() throws Exception {
String currentDateTime = null;
MyJson json = new MyJson();
ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
try {
Date currDate = new Date(System.currentTimeMillis());
currentDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(currDate);
json.setTime(currentDateTime);
ObjectWriter writer = mapper.writerWithView(Views.HeartBeatApi.class);
return writer.writeValueAsString(json);
} catch (Exception e) {
throw new Exception("Excpetion", HttpStatus.BAD_REQUEST);
}
}
It works as expected but have 2 issues:
When I invoke this API, Content-Type header is mandatory & I want to know how to make this header optional.
How to add "Accept" header so that it can support other format such as Google Protobuf?
Thanks!
If you don't want to require Content-Type exist and be "application/json", you can just omit the consumes section entirely.
"Accept" is available via the "produces" value, as opposed to "consumes." So if you wanted to support Google Protobuf OR application/json, you could do this:
#Controller
#RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public ResponseEntity<String> getHeartBeat() throws Exception {
String curr_time = myService.getCurrentTime();
return Util.getResponse(curr_time, HttpStatus.OK);
}