Dynamic java business rule validation - java

I am struggling to fit below use case.
Requiremnet:Dyamic comparison tool.Input to method is a json and then map it java class and then run some validation and persist it to database along with the result of the validation.
This looks simple when your json is predefined.You can create a java class and write code to do the required validation.
My use case is to be able to handle any kind of json and then create a beam dynamically and run some rule on it on the go
Now for example
Json 1:Student info json which has information about name,class,marks.
Validation:Persist data to DB only if marks>50
Json 2:Order info json which has information about order id,price,order type.
Validation:Persist data to DB only if order type= shoe.
Things i need to do:
Step 1: create a test file that has info regarding data type of validation object and the validation condition.
(Only way i think i can pass validation rule dynamically.Like how Apache does it on log stash.
Eg: https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html)
Step 2:Pass this test file while compiling your spring boot project.
Sample text file format
input{
name:String
class:String
grade:String
}
ValidationRule{
marks>50
}
output{
//if in case you don't want to persist all the data to db.You can mention which
field to use.
}
Now with the help of this text file i am assuming that java can create a bean.Then apply business rule to it.

Related

DB Migration in Spring boot

I want to load a json file in to Database while application start up.
Let take an example:
i have a json file as below.
Person.json
{
{
"name":"Rahul",
"age":"61"
},
{
"name":"Raj",
"age":"67"
}
}
DB Table : Person
name | age
I want to store json data in DB. If i add any new object in json file it should be identified and added.
What is the best design for this. Need to use Spring Boot, Spring.
You can use a CommandLineRunner and reflect over all the classes inside of your model package and look for a .json file. If you find one, deserialize the contents and save them to a database.
See this link:
http://therealdanvega.com/blog/2017/07/05/read-json-data-spring-boot-write-database
The code to get all classes within a package can be found here:
https://dzone.com/articles/get-all-classes-within-package

REST response with selective json properties from json

I have an entity like
public class Pojo{
int id;
org.json.JSONObject json;
/* other properties */
}
Now what I want to do is to send this Pojo object back as JSON BUT in a selective way so that an admin user has access to all properties and a regular user has selective access.
I can do that by using Spring JSONView and creating different views for admin and a regular user. However, the problem which i am stuck at that how can i add selective properties for admin/regular user from JSONObject? The only possible way i could think of is to create a another Pojo to map that object and then use that object in response. But I want to make sure that there is no other way to approach this.
P.S: its a spring boot application
I'm not sure if it works with JsonObject but you can give this a try. Would be interesting to know if it works with "dynamic" objects.
https://github.com/Antibrumm/jackson-antpathfilter
(I'm the creator of that project)

How to add JSP form data into a JSON object and store it in a database?

I have a user entry form with the following fields :
Name
Age
Address
I want to convert its value to JSON and save it in a database. How can I achieve this?
Which library can I use ?
At server side in servlet save all request parameters to corresponding bean and then you can convert using google's gson library for more info check this tutorial
For example:
You need servlet that takes form submission
To work with JSON I recommend eclipse source minimal JSON, I like it
database - plain JDBC, hibernate or JPA ..
Refer the following steps:
In JSP page, at javascript convert the form fields to JSON using JSON.stringify() method.
At server parse the JSON using appropriate JSON parsers like GSON or Jackson.
After parsing you will get desired object.
Perform database operation on the object.
You will probably need GSON jar , Jackson jar.

How to switch a Spring Roo or Grails project from typical MVC to AJAX/JSON/REST

This might seem like an odd question, but I am trying to get a handle on what the "best practice" is for converting an application that is set up to use something like Roo's or Grails' generation of controllers (which provides basic CRUD functionality) to something that returns a JSON response body instead for use in a JavaScript application.
The ambiguity of technology here is because I haven't actually started the project yet. I am still trying to decide which (Java-based) technology to use, and to see what kind of productivity tools I should learn/use in the process. It will be a web application, and it will use a database persistence layer. All other details are up in the air.
Perhaps the easiest way to accomplish my goal is to develop using some sort of AJAX plugin to start with, but most of the tutorials and descriptions out there say to start with a normal MVC architecture. Roo seems to make conversion of the controllers it generates to JSON-friendly return types difficult, and I'm not familiar enough with Groovy/Grails to know what it takes to do that.
This is mostly a learning experience for me, and I am open to any criticism or advice, but being a Q/A forum, I realize I need to incorporate an objective question of some sort. To fill that need, I ask:
What is the best way to set up an AJAX/RESTful interface for my entities in Roo and/or Grails?
I recently did exactly this with a Grails application and found it surprisingly easy to take the generated controllers and get them to output JSON or XML or the HTML from the view depending on the content negotiation.
The places in the Grails manual to look into are the section(s) on Content Negotiation and, if you need to deal with JSON or XML input, marshaling.
To get JSON and XML output, in the default list() method, changed it to this (I have a Session object, in this case...one of my domain classes):
def list() {
params.max = Math.min(params.max ? params.int('max') : 10, 100)
def response = [sessionInstanceList: Session.list(params), sessionInstanceTotal: Session.count()]
withFormat {
html response
json {render response as JSON}
xml {render response as XML}
}
}
Anywhere you are returning just an object by default, you will want to replace the returned value with the withFormat block.
You also may need to update your Config.groovy file where it deals with mime types. Here's what I have:
grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format
grails.mime.use.accept.header = true
grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'],
text: 'text/plain',
js: 'text/javascript',
rss: 'application/rss+xml',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
all: '*/*',
json: ['application/json','text/json'],
form: 'application/x-www-form-urlencoded',
multipartForm: 'multipart/form-data'
]
As input (to an update() or save() action, for example) JSON and XML payloads will automatically be unmarshaled and will be bound just like a form input would be, but I've found that the unmarshaling process is a bit picky (especially with JSON).
I found that, in order for JSON to be handled correctly in the update() method, the class attribute had to be present and correct on the inbound JSON object. Since the library I was using in my client application didn't make this an easy issue to deal with, I switched to using XML instead.

After I got XML data, how to parse it and transfer to JSON?

In Jersey RESTful frame work, I know I can get xml data in client as following:
private static final String BaseURI = "http://DOMAN.com";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(BaseURI);
String xmlData = service.path("rest").path("todos").accept(
MediaType.APPLICATION_XML).get(String.class)
My question is how can I parse the xmlData then? I would like to get the needed data from xmlData, and transfer the needed data to JSON, what is the best way to implement this?
As a general rule, NEVER convert straight from XML to JSON (or vice versa) if you do not have to.
Rather, bind data from XML or JSON to POJOs, then do the other conversion. While it may seem non-intuitive this results in cleaner result and less problems, since conversions between POJOs and data formats have much more options, mature, well-designed libs; and POJOs are easier to configure (with annotations) and have more metadata to guide conversion process.
Direct conversions libs (like Jettison, see below) are plagued with various issues; often producing "franken-JSON", JSON that is technically correct but looks alien because of added constructs needed by conversion.
In case of Jersey, then, use JAXB for XML to/from POJOs, and Jackson for doing the same with JSON. These are libraries Jersey uses anyway; and direct usage is quite easy.
If you absolutely insist on direct conversion, you could try Jettison, but be prepared to hit a problem with Lists, arrays and Maps, if you need them (esp. single-element arrays -- arrays are problematic with XML, and auto-conversion often goes wrong).
If your service doesn't provide JSON as an option already (what happens if you change MediaType.APPLICATION_XML to MediaType.APPLICATION_JSON?), then I believe you have a few options, which I list in order of my preference.
Option 1: You have an XML schema for the the data
If you have an XML schema for the returned XML, you could use xjc to generate the JAXB annotated java classes and then leverage jackson to convert the instances to JSON data. I think this will get you going fast by leveraging this libraries over doing the parsing youself. Jackson is a robust library, used by glassfish for their Jersey(JAX-RS) implementation and I don't feel there is any risk in depending on this library.
Option 2: Use the json.org library, but I've had significant problem with this library having to do with its reflection-based methodology, etc. That said, it might work well for you...and you can test relatively easily and see if it does meet your requirements. If so...you're done! =)
Option 3: You don't have the XML schema and/or you want more control
as #Falcon pointed out, you can always use traditional XML parsing technologies to parse the XML into whatever you want. I'm partial to SAX parsing, but DOM could work depending on xml side
Regards,
Steve
Simplest and easiest way would be using org.json package : http://json.org/javadoc/org/json/XML.html
XML.toJSONObject(xmlData).toString()
Just this one line apart from necessary import statement will do it all.
Now that i have mentioned org.json library, lot of people may comment bad about it. Remember, I have said the simplest and easiest way, not the best or the most performant way ;-)
In case you are using maven, add this dependency :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Do you have any access to the "lower level interface" that generates the XML? If you do, the only change needed is to have the xml objects annotated with "#XmlRootElement". Then, you can just pass back the XMLobject as JSON without any further code.
Check Jsonix. If you have an XML schema, you can generate XML-JSON mappings and unmarshal/marshal XML in JavaScript. Very similar to JAXB (which Steve Siebert mentioned), but works on client.
// The PO variable provides Jsonix mappings for the purchase order test case
// Its definition will be shown in the next section
var PO = { };
// ... Declaration of Jsonix mappings for the purchase order schema ...
// First we construct a Jsonix context - a factory for unmarshaller (parser)
// and marshaller (serializer)
var context = new Jsonix.Context([ PO ]);
// Then we create an unmarshaller
var unmarshaller = context.createUnmarshaller();
// Unmarshal an object from the XML retrieved from the URL
unmarshaller.unmarshalURL('/org/hisrc/jsonix/samples/po/test/po-0.xml',
// This callback function will be provided with the result
// of the unmarshalling
function(result) {
// We just check that we get the values we expect
assertEquals('Alice Smith', result.value.shipTo.name);
assertEquals('Baby Monitor', result.value.item[1].productName);
});

Categories

Resources