How to retrieve post data, validate it in controller and save it in database using GORM in Micronaut? - groovy

I come from Grails background and have recently started a project in Micronaut using GORM.
I tried to find required information in documentation but its not clear how we retrieve post data in controller, validate it similar to Command Objects offered in Grails and save it into database using interface service provided in documentation
PS : I know I can map every field to action argument in controller, and also declare a interface method specifying each argument as property but that does not seems right thing to do as my domain class has so many properties.
Making the action #Transactional or any method would work for saving data as far as I know but I want to know the proper way in Micronaut.
My requirement is simple, save post data in database using GORM in Micronaut.

If I were you I would look back at the documentation, sections 6.4 to 6.11:
https://docs.micronaut.io/snapshot/guide/index.html#binding
https://docs.micronaut.io/snapshot/guide/index.html#datavalidation
http://hibernate.org/validator/
Micronaut is very annotation based, unlike Grails which uses convention over configuration. However in Grails 4, Micronaut will toke over the application context, giving you some of the benefits of Micronaut, but still maintaining the convention over configuration.

Related

Customize Controller from commercewebservices in SAP Commerce Cloud

From what I understand, from SAP Commerce Cloud 2005 onward the way to customize the REST-endpoints within SAP Commerce Cloud for Spartacus is to use commercewebservices (non-template) and then add own occ-extensions with your REST-endpoints.
That works fine for new endpoints, but what if I want to customize an existing controller from within commercewebservices? Since I am not using the template anymore commercewebservices cannot be modified anymore. I don't see a way how I could for example customize de.hybris.platform.commercewebservices.core.v2.controller.CartsController.
Swapping out commercewebservices with your own extension generated from the template does not work since multiple OOTB (e.g. cmsocc) extensions depend on commercewebservices hence it will always be loaded and clash with our own extension derived from commercewebservices.
Customizing commercewebservices with an addOn also does not solve the problem since, as I understand, it is not possible to add your own controller and bind it to the a url-pattern already used from a controller within commercewebservices
If you want to override an existing API endpoint (CartsController in our case), you can do so with the #RequestMappingOverride annotation.
Using this annotation, you can "shadow" the existing request mapping of the out-of-the-box controller with your custom controller in your own OCC extension.
You can find more details and an example here:
Overriding the REST API [help.sap.com]
EDIT
And let's not forget:
All of the action happens in the facades anyway, and you can also extend the API responses without overriding the Controller using the WsDTO concept plus additional converters. (see Extending Data Objects[help.sap.com] for more details)
Thanks for the response.
The annotation RequestMappingOverride works fine. There is one problem with this approach, lets assume I do following:
Introduce an new called MyController extending the CartsController
Override a single method and annotated this method with RequestMappingOverride
Starting up the system I do get now ambiguous mappings on all mappings of CartsController which I did not override
The reason is, I have now two Controllers registered with the same mappings. The CartsController and MyController which inherits all the methods which are not overriden from CartsController. The only solution I found is to override every single method of the CartsController, annotate all methods with RequestMappingOverride and then just do a super call. That is a bit clumsy and leads to a lot of boilerplate code. I wish the annoation RequestMappingOverride would work on class-level rather than only on method level

why should I not use MVC Jsonresult instead of apicontroller get method

I have developed an application which was MVC application. It has a requirement that the application will return json data for one get request.
So I have added apicontroller and created a get method to return json data.
So far so good. but then I thought, is it really needed to add apicontroller to create just one get method.
I started exploring and googling what is the difference other than content negotiation. Got lots of answers and articles but non of them were satisfactory.
So here is the actual confusion, why can't I just create a method in the MVC controller with JsonResponse and return the json data(Which I know only is need for my requirement, but other application on different domain will consume it).
Can anyone convince me why should I use apicontroller instead of MVC JsonResponse for my requirement or should I not be using apicontroller at all.
apology if there is any mistake.
If I get it right the question is Can we use MVC action to serve json content answer is yes! Is it okay to use Json Result? answer is It depends where do you want to consume it
Say I am an in a Web Environment where I have no need for the APIs (that means I am not going to serve my data to multiple clients) If that's the scenario where only your View is going to consume data returned from your Action Method you are good to go. An Action returning a Json Result is basically an Action Result and that's what it is made for.
but If you are in a REST scenario and you need your backend to serve your data to the client de facto standard is to use an independent Web API for that.
Controllers' main responsibility should be to work as an intermediary between your View and Model and whatever service layer you want to bring inside it. on the other hand, Web APIs are data-driven there only purpose is to serve data (use them if you need them)
Web APIs are good cause they give you the flexibility of serving the data to possibly any client that might need it. That's what I would pick if I am starting from scratch but if I only need to serve data to one client Controller Action methods will be way to go.
Hope this helps.

How to understand jHipster frontend parts?

I've never had anything to do with AngularJS or any frontend technologies, so it's hard for me to grasp. I have a jHipster project that I need to customize and turn into a useful thing. How it looks doesn't matter for now, it needs to work. I watched the "jHipster in 20 minutes" video and even read the minibook, but these didn't help me understand how to deal with the generated files.
I need some guidelines and explanation on how files like entities/entity1/entity1.controller.js, entity1.service.js and entity1.state.js are dependent on each other (and on Java Spring #Services/#Controllers/ Spring Data entities in general). What's the procedure to add new functionalities (views, dialogs)?
In short.
Controller: decorator of the entity
Entity: is what backend(spring boot) gives you
Service: used to make calls to the backend to get the entity data.
State: -> uses the service -> uses the "Backend" to get Entity data
and sets the Entity on the Controller

re-using ServiceStack validation in Winforms offline client

We have a working website using ServiceStack as the back end that amounts to a complex data-entry form.
My users have requested an "offline editor" for the forms. To use the offline program, the user will have to connect to the ServiceStack service, create empty instances of the forms, and then I will save the POCOs from the service to disk using ServiceStack's JSON serializer. From there the user can log off the service and edit the POCOs. When they're done, they reconnect to the service, and post/put the edited POCO object.
This all works great. My question involves validation. The validation logic is built into my Service.Interface library, which isn't available offline. The winforms program references only the POCO library and the ServiceStack "common" libraries, which do not look like they include the ServiceStack.Validation namespace.
Is there a way I can rearrange my project so that both the service and the Winforms client can run Validation against the POCOs, so that they can have data validation while offline?
UPDATE:
getting closer, I think - I moved all of the Validation classes into their own project. From my Winforms project, I can now manually set up a validator for a POCO class like this:
ServiceStack.FluentValidation.IValidator<SomePOCO> IValidator;
IValidator = new Tonto.Svc.Validation.SomePOCOValidator();
ServiceStack.FluentValidation.Results.ValidationResult vr =
IValidator.Validate(_rpt);
I can see the validator constructor being set up and the rules being initialized, but the .Validate method doesn't seem to do anything. (object comes back as valid, and breakpoints into custom validator code never get there).
UPDATE #2
I discovered my validator code wasn't running from Winforms because my validators all specify a servicestack ApplyTo Put/Post only (see sample code below). When I remove the entire Ruleset clause, though, then validation happens in my service on GETs - something I never want.
Can anyone think of a way to configure the validator rules to run for POST/PUT only when called from ServiceStack, but to also always run when NOT in servicestack? So close!
public class SomePOCOValidator : AbstractValidator<SomePOCO>
{
public SomePOCO()
{
RuleSet(ApplyTo.Put | ApplyTo.Post, () =>
{
(rules)
});
}
}
If your validation is doing anything interesting, then it probably HAS to be done "online".
Maybe just allow your client to save the POCOs locally until they go back online, at which point you send them up to your server. Any transactions that are okay, get processed normally, and any that fail, get returned for the user to edit (so your client will need some smarts to have a working set of POCOs for editing)...
If you don't want ANY extra stuff on the client, just have the transactions that fail to validate get stuffed into a "needs_corrections" table on the server, and then code up a supervisor-sort of screen to manage that table.
The validation framework that ServiceStack uses is named FluentValidation. There is no WinForms support in it. Jeremy Skinner the creator of FluentValidation answerd a question about this back in 2010 on his forum here.
Personally I don't use FV with WinForms - the vast majority of my projects are web-based with the occasional WPF project.
However, if I was going to do this then I probably wouldn't validate the controls directly, but instead use a ViewModel which is bound to the controls. I'd use a fairly strict convention where the names of the controls would match the names of the properties that they're bound to. Then, after validation completes I'd walk the control hierarchy to find the control with the name that matches the property that failed validation (I'm not sure how you'd do this in WinForms, but in WPF I'd use LogicalTreeHelper.FindLogicalNode) and then use the ErrorProvider to set the appropriate error.
Jeremy
I was able to work out a solution that allowed me to use ServiceStack validation libraries on both a ServiceStack client and an offline client. Here are the details.
Move all AbstractValidators to their own project: Proj.Svc.Validation.
get rid of all RuleSets in your AbstractValidators.
Reference Proj.Svc.Validation from Proj.Svc.Interface and Proj.OfflineWinformsClient projects.
Turn OFF the ValidationFeature() plugin in your service. All validation will have to be done manually. This means no iOC injected validators in your service classes.
When it's time to validate, either from your service or the offline client, manually declare the validator and use it like this.
IValidator validator = new
Tonto.Svc.Validation.SomePOCOValidator();
ServiceStack.FluentValidation.Results.ValidationResult vr =
validator.Validate(poco);
if (!vr.IsValid)
(throw exception or notify user somehow);

Creating Database class Library using NHibernate

I am writing an Class Library as DataModel. DataModel capable of handling all the Database related task. I am using NHibernate and Fluent NHibernate for the same.
Now the question arises are as follows :
Should we expose the Entity (POCO Class).
Is it good to have a Entity with internal protected property and property exposed as a interface.
Entity created for mapping can be a Model for WPF MVVM.
Or should we directly bind entity ?.
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
Is it right to throw Exception occurring in an API or should I return null?.
Is it good keep logging in the Library ?.
Should we expose the Entity (POCO Class).
Yes, Creating wrapper class makes more effort.
Is it good to have a Entity with internal protected property and property exposed as a interface.
Yes, Setter and non-exposed properties are control.
Entity created for mapping can be a Model for WPF MVVM.
For primitive type can be, but reference can be exposed by interface.
Or should we directly bind entity ?.
If Model is created rather directly use of POCO object. It is much more flexible for refresh cases. User can not change property of POCO object if cancel operation is there.
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
IEnumerable is used to exposed collection by interface.
Is it right to throw Exception occurring in an API or should I return null?.
Exception is much more better to make know to user about error. but wrap the exception in user readable rather returning NHibernate exception.
Is it good keep logging in the Library
Logging is very good feature to know about issue.
Should we expose the Entity (POCO Class).
yes, otherwise whats the use of the entities when nobody uses
Is it good to have a Entity with internal protected property and property exposed as a interface.
It depends! internal protected properties are no problem when using an ORM but i prefere to reduce internal stuff to a minimum because i like objects maintaining their own state. interfaces are fine
Entity created for mapping can be a Model for WPF MVVM.
of course. No need to duplicate them another time. That's what persistence ignorance is for
Or should we directly bind entity ?
More ofthen than not, the UI requirements are very different than persistence/businessrules so there will be specialised ViewModels for UseCases/Views. However simple Dataholders like Order class thrown into Lists can be bound directly (e.g. using a DatabindingFactory to make them implement INPC)
There is no control if Library returns a List of entity as API return. So anybody can do add or delete in list. How should I keep control on it. Should I create proxy derived from IList which will keep track of it.
Lists are just in memory container. The user still has to go through the API to Save/Update state.
Is it right to throw Exception occurring in an API or should I return null
if collections are returned then empty collections are far better than null.
Exceptions however should bubble up preferably wrapped in own handable Exceptions. Implement NHibernate.Exceptions.ISQLExceptionConverter (e.g. like NHibernate.Test.ExceptionsTest.MSSQLExceptionConverterExample) and configure it with e.g.
config.DataBaseIntegration(db => db.ExceptionConverter<MyExceptionConverter>())
Is it good keep logging in the Library
absolutly. Logging enables debugging deployed applications. (Fluent)NHibernate already has lot's of logging built in use it if possible.

Resources