jersey webservice not returning jsonp - jsonp

I am trying to create a webservice that will return jsonp.
At the moment it is only returning json
Here is my code:
#Path("/jsonp")
public class JsonpWebservice {
#GET
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public JSONWithPadding readAllP(#QueryParam("jsoncallback") #DefaultValue("jsoncallback") String jsoncallback)
{
ToolKitBean tkBean = new ToolKitBean();
tkBean.setNegativeCount("10");
tkBean.setPositiveCount("11");
System.out.println("jsoncallback: " + jsoncallback);
return new JSONWithPadding( new GenericEntity<ToolKitBean>(tkBean) {}, jsoncallback);
}
}
i also have a JAXBContext resolver defined.
When i look at the response from this webservice, I see the json and not jsonp - {"negativeCount":"10","positiveCount":"11"}
Any ideas what I need to do in order to have jsonP returned from this webservice?
Thanks
DAmien

By changing
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) to be
#Produces("application/x-javascript")
This has fixed my issue
Thanks
Damien

Related

Adding custom Response header to Spring WebFlux contoller endpoint

Is there a way to add a response header to spring webflux controller endpoint? for example to the following method I have to add a custom header say 'x-my-header'
#GetMapping(value = "/search/{text}")
#ResponseStatus(value = HttpStatus.OK)
public Flux<SearchResult> search(#PathVariable(
value = "text") String text){
return searchService().find(text);
}
In the functional API, this is really easy; the ServerResponse builder has builders for almost everything you need.
With the annotated controllers; you can return an ResponseEntity<Flux<T>> and set the headers:
#GetMapping(value = "/search/{text}")
public ResponseEntity<Flux<SearchResult>> search(#PathVariable(
value = "text") String text) {
Flux<SearchResult> results = searchService().find(text);
return ResponseEntity.ok()
.header("headername", "headervalue")
.body(results);
}
Note that the updated code doesn't need the #ResponseStatus annotation now.
UPDATE:
Apparently the solution above works; unless you have spring-cloud-starter-netflix-hystrix-dashboard dependency. In that case you can use the following code:
#GetMapping(value = "/search/{text}")
public Mono<ResponseEntity<List<SearchResult>>> search(#PathVariable(
value = "text") String text) {
return searchService().find(text)
.collectList()
.map(list -> ResponseEntity.ok()
.header("Header-Name", "headervalue")
.body(list));
}
A couple of things to note:
Outer type should be Mono<ResponseEntity<T>>: There is one response for request. If you declare it to be a Flux, Spring will try to deserialize the ResponseEntity as if it was a POJO.
You need to use an operator to transform the Flux into a Mono: collectList() or single() will do the job for you.
Checked with Spring Boot 2.0.3.RELEASE

What is the replacement of FormDataCollection in Asp.Net core?

I am trying to use FormDataCOllection in Asp.Net core web api project. As per the documentation it is not there in .net core.
How can I still use it? Or What has replaced it?
You can use the Form property of HttpContext.Request which will return an IFormCollection instance.
FormDataCollection is normally type of the information/class/model sent by forms or grid edit or sumbit links. You can simply use the string as input parameter and then using Json, convert it to the class type you've expected.
Here is an example:
public string NewUser(string values)
{
var message = "";
try
{
var newUser = new User_Detail();
JsonConvert.PopulateObject(values, newUser);
db.User_Detail.Add(newUser);
db.SaveChanges();
message = "User cretaed successfully";
}
catch (Exception ex)
{
message = "An error happened in this method.";
}
return JsonConvert.SerializeObject(message);
}
So, PopulateObject converts your input string (values in this example) to the class you've expected, something similar to FormDataCollection you've needed.
Note: JsonConvert is in Newtonsoft.Json namespace

Doesn't ASP.NET Core have an InternalServerError()?

The Microsoft.AspNetCore.Mvc.Controller base class doesn't have an equivalent of BadRequest(), Ok(), NoContent(), etc. for returning HTTP 500 status codes.
Why can't we do?
try{
oops();
}
catch(Excpetion e){
//some handling
return InternalServerError(e);
}
I know can do return StatusCode(500);, but we are trying to be more consistent with our HTTP codes and would like to know if there is something more consistent with Ok() for returning a 500 code?
ASP.NET Core 2.x doesn't have InternalServerError method. Instead you can include the following library.
using Microsoft.AspNetCore.Http;
And then use the following code.
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
Or if you want to add the exception along with the response, try the following code
var result = StatusCode(StatusCodes.Status500InternalServerError, exception);
return result;
If just like me you didn't understand where the StatusCode method is coming from in Karim's answer, this code will work just as well:
var errorObjectResult = new ObjectResult(exceptionMessage);
errorObjectResult.StatusCode = StatusCodes.Status500InternalServerError;
return errorObjectResult;

Accept header precedence with spring-data-rest

I am trying spring-data-rest with mithril.js. However, I keep getting xml response from the repository instead of json.
I have this repository:
#RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends JpaRepository<Person, Long> {
And request with this:
var users = m.request({method: "GET", url: "/api/people/"});
However, I just got a list of string in xml response.
I tried to check the source as below, though I may mislook and point out the wrong source:
Found that mithril set the accept header as
xhr.setRequestHeader("Accept", "application/json, text/*")
mithril source: line 1079
However, it sounds spring-data-rest handle the request with
#ResponseBody
#SuppressWarnings({ "unchecked" })
#RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET, produces = {
"application/x-spring-data-compact+json", "text/uri-list" })
public Resources<?> getCollectionResourceCompact(RootResourceInformation repoRequest, DefaultedPageable pageable,
spring-data-rest source: line 171-173
instead of
#ResponseBody
#RequestMapping(value = BASE_MAPPING, method = RequestMethod.GET)
public Resources<?> getCollectionResource(final RootResourceInformation resourceInformation,
on spring-data-rest source: line 210-213
Is anything wrong on my ajax request?
Use curl to create the request and get that working the way you think it should. After that works, tackle the mithril part.

REST GET api - what to return when resource not found

I am using jersey to create rest api. I have GET api which returns xml or json representation of an object instance using JaXB. Everything is fine as long as I can get this instance based on id and return it. But when I don't find instance what should I return. I know 404 response has to be returned. But my method already returns a given type. So how do I setup 404 status is response?
Here is simplified version of my method
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public GameDAO getGameState(#PathParam("gameId") String gameId)
{
//code to get game instance based on gameId
if(game != null)
{
GameDAO d = new GameDAO(game);
return d; //gets auto converted to xml or json
}
return null; //how to return not found response ?
}
A 404 response is what you want, and I think the best way to get there is by throwing a "not found" WebApplicationException. Here's an example:
throw new WebApplicationException(Response.Status.NOT_FOUND);
There are plenty of ways to customize the error handling; you can find more details in the Jersey docs: https://jersey.java.net/documentation/latest/representations.html