How to define custom handling for a response class in Spring doc? - springdoc

I've been using arrow-kt and spring together a lot lately. I've actually constructed a bridge between the two with several key features, one of which is a spring controller that returns an Either will automatically unwrap it and either handle the exception (Left) or return the result (Right). My long term goal is to publish this as a library.
My latest obstacle is Swagger, or more accurately springdoc openapi. Obviously it is seeing the Either, but i want it to show only the Right value as the success response type. While I know there are annotations where I can set the response model on each controller method individually, I'm trying to avoid this.
My real goal is to setup some global converter so that wherever Swagger sees an Either it will automatically unpack this. I'm just not super familiar with the customization API in Spring doc, and everything I Google just points me to the ApiResponse annotation solution.
How can I define default handling for this type of response?

Related

Spring Boot to return JSON String from an external API

I have a simple Spring boot project that uses controller mappings to get hard coded information from a class in my project.
For example, if I run the request : localhost:8080/topics, A JSON response is returned with the list of Topic Objects that i have previously created
I want to take this one step further and have a class who's variables are populated by calling this API and parsing the response : https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo
I believe this can be done in Java by creating a HTTP connection and reading the data from an input stream, but is the an easier way of doing this with spring boot? Im not fully sure of the name of this procedure hence Im having trouble finding solutions online
Since you are using Spring Boot, making use of Spring's RestTemplate makes sense. It comes with several message converters out of the box, and uses Jackson by default for json content.
Spring has published a good Getting Started page for consuming RESTful web services.
However, the json content returned by that services doesn't look like it will map well to a Java object, so you may have to deserialize it to a HashMap to get to the data you want.
I did an attempt to create something like this.
https://github.com/StanislavLapitsky/SpringSOAProxy
The idea is to register controller interfaces. Each of the interfaces are mapped to some URL. For the interfaces a dynamic proxy are generated (if the implementations are not available locally). So developer just call controller's interface method. The method is invoked for dynamically generated proxy. The proxy uses RestTemplate to call remote URL. It sends and receive JSON and deserializes the returned JSOn to POJO objects returned from the controller.
You need to declare contract - controller interfaces plus DTO to exchange data as well as mapping to understand which URL should be called for each controller.

Create JSON Object in React.js from Rest Service

I am looking for either guidance or a good example where I can map data coming from rest services to JSON "type" object which can then be used in a number of different react components.
The JSON Object will be used to map data from a few different rest services, which essentially hold very similar data which makes it better to use one object and then to bind the data to the respective React Components.
I am fairly new to React.JS and I have googled around to find a data mapper to JSON from Rest Service example.
Can anyone help?
You typically don't have to do too much, at least on the front end side. As long as the REST endpoint can return JSON responses you'll be fine. Just make sure you set the appropriate Content-Type headers in the request. Note that setting the header doesn't guarantee a JSON response, the server has to be able to send it in that format.
If you're creating the REST service yourself, you have many options. If you're using node, you can simply return a javascript object. If you're using some other language like Java, C#, etc., they come with libraries that can serialize objects into JSON for you. I use JSON.net when working with C#. In these cases, because the data will be returned as a string, you'll just need to JSON.parse() it upon receiving it and then set it to the appropriate React component's state.

Grails - Do you still need parseRequest for JSON binding to work in controller?

Ok, this is my Nth question regarding this topic, and I'm getting really frustrated with Grails. Please have a quick look on one of my earlier questions for more details.
Among other things, my problem is that sending JSON formatted data to the controller when testing doesn't seem to work. The controller doesn't get null object, but the argument passed is practically empty--the JSON properties don't get set.
Aside from the controller code from the link above, I also tried,
def save() {
def model = new MyModel(request.JSON)
model.save()
}
but it still fails to set properties.
From my Web searches, I read that in older versions, parseRequest must be set to true in UrlMapping.groovy so that request data formatted in XML, JSON, etc. would automatically be parsed and passed as controller method argument. I'm working on Grails 2.3.9, and I'm not sure if it's still necessary to do that.
The time I thought I'd save if I use Grails on this project is being spent on looking for an answer to this seemingly simple task of testing a RESTful Web service.
No since 2.3.0 the parseRequest option doesn't do anything. The request is parsed lazily only when request.XML or request.JSON is accessed or when binding to a command object.

JSON Objects vs Spring Model Objects

I am using standard Spring MVC 3x framework and have my model entities all built up with all the good relational stuff (javax.persistence API)... integrated with my DB.
As the application evolved, we needed to support JSON calls.
Given that I have various relationships mapped out in my Model Entity layer,
(classX->classY as well as classY->classX)
I am wondering what the best practice is in translating some of these model classes to appropriate JSON objects without duplicate re-referencing?
eg: Sample buggy response
{"classX":{"id":"1", "classY":{"id":"2", "classX":{"id":"1", "classY":{"id":"2"...
I am contemplating a couple of methodologies I wouldn't mind feedback on...
Keep the existing model classes and set the cross relationships to NULL before putting it into my ModelMap so there won't be some form of re-referencing (me thinks its a HACK)
{"classX":{"id":"1", "classY":{"id":"2", "classX":null}}}
Recreate JSON classes similar to the existing models without the re-referencing classes (but I think that means they will not be as reusable... since I will end up only having classX->classY and not backwards if I wished to drill the other way for a data response).
{"jsonClassX": {"id":"1", "jsonClassY":{"id":"2"}}}
Just simply construct it as standard ModelMap mappings for every controller call. As such no concept of a reusable JSON class, and is dependent on the way the controller constructs and organises the return values. This seems like the easiest, but it means no-reusable code (besides cut and paste)...
{"x":{"id":"1", "y":{"id":"2"}}} // for controller call 1
{"y":{"id":"2", "x":{"id":"1"}}} // for controller call 2
So those are the options I am juggling with at the moment, and I wouldn't mind getting some feedback and some pointers on how others have done it.
You should use Jackson to manage your json marshalling. Then you can add annotations to your model object which tell Jackson how to handle this type of relationship. http://wiki.fasterxml.com/JacksonFeatureBiDirReferences is a good reference for how to set up these relationships.

Binding JSON to nested Grails Domain Objects

I'm developing a RESTful interface which is used to provide JSON data for a JavaScript application.
On the server side I use Grails 1.3.7 and use GORM Domain Objects for persistence. I implemented a custom JSON Marshaller to support marshalling the nested domain objects
Here are sample domain objects:
class SampleDomain {
static mapping = { nest2 cascade: 'all' }
String someString
SampleDomainNested nest2
}
and
class SampleDomainNested {
String someField
}
The SampleDomain resource is published under the URL /rs/sample/ so /rs/sample/1 points to the SampleDomain object with ID 1
When I render the resource using my custom json marshaller (GET on /rs/sample/1), I get the following data:
{
"someString" : "somevalue1",
"nest2" : {
"someField" : "someothervalue"
}
}
which is exactly what I want.
Now comes the problem: I try to send the same data to the resource /rs/sample/1 via PUT.
To bind the json data to the Domain Object, the controller handling the request calls def domain = SampleDomain.get(id) and domain.properties = data where data is the unmarshalled object.
The binding for the "someString" field is working just fine, but the nested object is not populated using the nested data so I get an error that the property "nest2" is null, which is not allowed.
I already tried implementing a custom PropertyEditorSupport as well as a StructuredPropertyEditor and register the editor for the class.
Strangely, the editor only gets called when I supply non-nested values. So when I send the following to the server via PUT (which doesn't make any sense ;) )
{
"someString" : "somevalue1",
"nest2" : "test"
}
at least the property editor gets called.
I looked at the code of the GrailsDataBinder. I found out that setting properties of an association seems to work by specifying the path of the association instead of providing a map, so the following works as well:
{
"someString" : "somevalue1",
"nest2.somefield" : "someothervalue"
}
but this doesn't help me since I don't want to implement a custom JavaScript to JSON object serializer.
Is it possible to use Grails data binding using nested maps? Or do I really heave to implement that by hand for each domain class?
Thanks a lot,
Martin
Since this question got upvoted several times I would like to share what I did in the end:
Since I had some more requirements to be implemented like security etc. I implemented a service layer which hides the domain objects from the controllers. I introduced a "dynamic DTO layer" which translates Domain Objects to Groovy Maps which can be serialized easily using the standard serializers and which implements the updates manually. All the semi-automatic/meta-programming/command pattern/... based solutions I tried to implement failed at some point, mostly resulting in strange GORM errors or a lot of configuration code (and a lot of frustration). The update and serialization methods for the DTOs are fairly straightforward and could be implemented very quickly. It does not introduce a lot of duplicate code as well since you have to specify how your domain objects are serialized anyway if you don't want to publish your internal domain object structure. Maybe it's not the most elegant solution but it was the only solution which really worked for me. It also allows me to implement batch updates since the update logic is not connected to the http requests any more.
However I must say that I don't think that grails is the appropriate tech stack best suited for this kind of application, since it makes your application very heavy-weight and inflexbile. My experience is that once you start doing things which are not supported by the framework by default, it starts getting messy. Furthermore, I don't like the fact that the "repository" layer in grails essentially only exists as a part of the domain objects which introduced a lot of problems and resulted in several "proxy services" emulating a repository layer. If you start building an application using a json rest interface, I would suggest to either go for a very light-weight technology like node.js or, if you want to/have to stick to a java based stack, use standard spring framework + spring mvc + spring data with a nice and clean dto layer (this is what I've migrated to and it works like a charm). You don't have to write a lot of boilerplate code and you are completely in control of what's actually happening. Furthermore you get strong typing which increases developer productivity as well as maintainability and which legitimates the additional LOCs. And of course strong typing means strong tooling!
I started writing a blog entry describing the architecture I came up with (with a sample project of course), however I don't have a lot of time right now to finish it. When it's done I'm going to link to it here for reference.
Hope this can serve as inspiration for people experiencing similar problems.
Cheers!
It requires you to provide teh class name:
{ class:"SampleDomain", someString: "abc",
nest2: { class: "SampleDomainNested", someField:"def" }
}
I know, it requires different input that the output it produces.
As I mentioned in the comment earlier, you might be better off using the gson library.
Not sure why you wrote your own json marshaller, with xstream around.
See http://x-stream.github.io/json-tutorial.html
We have been very happy with xstream for our back end (grails based) services and this way you can render marshall in xml or json, or override the default marshalling for a specific object if you like.
Jettison seems to produce a more compact less human readable JSON and you can run into some library collision stuff, but the default internal json stream renderer is decent.
If you are going to publish the service to the public, you will want to take the time to return appropriate HTTP protocol responses for errors etc... ($.02)