Create Spring Boot microservice that accepts a given Json? - spring-boot

So the question: i have the following Json:
{
"type": "ipv4",
"value": "1.2.3.4",
"firstSeen": "2020-07-10 15:00:00.000",
"totalCount": 8
}
i need to create a spring boot microservice from it ,with the following restrictions:
TotalCount cannot be less than 0 and cannot be more than 100.
firstSeen date should ALWAYS be converted to ISO 8601 format. The user can enter the date
in any string format. Return error if it is not well formed.
Expose the following RESTful APIs
Create a new record (as shown above, id auto-generated)
Get record by value
as this is my first time working with microservice,i can not understand this problem,is there anyone can help me with this please?

You will need to create a basic Spring Boot project using Spring Initializer, if you are using Intellij you can use this link as reference https://www.jetbrains.com/help/idea/your-first-spring-application.html#create-new-spring-boot-project.
Then add a new controller method which accepts a Json Request. Since you are trying to create a new record, I suggest you use POST method. Json Request will accept the 4 input parameters you mentioned. This is very basic and you should be able to find it in pretty much any Spring boot tutorial online. you can refer for example https://dzone.com/articles/simple-spring-boot-post
This Json Request can have validator annotations which check for the criteria you give. For example you can have #Size(min=0, max=100, message="TotalCount cannot be less than 0 and cannot be more than 100"). https://www.baeldung.com/jpa-size-length-column-differences
For date you might need to write a custom validator to check the specific format you want. For creating a record I guess you mean adding it to database. here you can configure your database using the yaml file, again there are lot of online resources on how to configure a Database in your spring boot project. https://blog.tericcabrel.com/write-custom-validator-for-body-request-in-spring-boot/
Since its your first time, it might take a while to figure out various details but I assure you once you get a hold of it, its going to be easy.

Related

How to load/retrieve In Memory Database (H2 Database) using karate Framework as a prerequisite step before Microservice REST API is called [duplicate]

This question already has an answer here:
How to pull data from a DB to compare with rest api response from karate
(1 answer)
Closed 1 year ago.
Problem Statement :
Microservices retrieves data from DB2 Database as part of Production
Different Set of data feasible in Different Environment
As part of it, it needs to ensure Retrieval logic is accurate
java Code Converts DB2 Data into JSON structure
Microservices logic doesnt control creating Database,its only limited to retrieval
As part of above requirement , In memory DB (H2) is being discussed for Testing where data is loaded using DDL/DML and Expected JSON response to be generated manually as part of unit Testing
Test Validation Objective : test "Retrial Logic" so that irrespective of Environment, same values are retrieved .When Microservices is invoked, internally Test Harness URL calls to In Memory Database to retrieve Actual response
Test Automation Framework in Place :
Karate Framework
Test Automation Approach:
Load data into in Memory Database using DDL/DML (file) as part of Test Execution
Invoke Microservice Request using karate
Compare Actual Response against Expected JSON response captured in Step
Delete the Database as part of Cleanup
Note - As it would be very tedious to write same Test Automation logic which helps to convert Data into DB ( In Memory ) to JSON (Expected Response), Expected JSON response to be captured as base expected response
Its Expected to have Test Automation Maintenance to Update DDL/DML or expected JSON is there is any change in actual Retrieval Logic.
Refernce for In memory DB Testing :
https://www.baeldung.com/spring-jpa-test-in-memory-database
#xyz-service-response.json is generated as part of unit testing while In memory DB is Created
#TestRetrivalLogicusingInMemoryRequirnments
Feature: demo reading files and using in a test
Background:
* url 'http://localhost:8080/api/sample/v1.0/'
* header Accept = 'application/json'
* configure logPrettyResponse = true
* configure ssl = true
Scenario: using json as a string
Load data into In Memory Database ---->> This is expected Gherkin Statement. Need to understand how we can do in Karate
Given path 'getDerivedRules'
And request { "pricingVerIds": [{ "AncestorVersionId": 123456123, "kidsVersionIds": [3432432,345324324] }],"executionFlow": "Cheque","PriceType": "dollarinINYIELD", "validationLevel": "Aggrement_LEVEL"}
When method POST
Then status 200
Then match $ == read('xyz-service-response.json')
Challenge and Query :
As karate Gherkin statement doesn't have Java Glue Code , and it has own DSL, can this be achieved using Karate or we need to stick to RESTAssured or similar Framework
Request for Help :
Any suggestion or code snippet to handle above would be helpful
Absolutely possible, please refer this example in the demos: dogs.feature.
The point is you can easily mix any custom Java code into a Karate test. Please refer the documentation for more: https://github.com/intuit/karate#calling-java
You do NOT need the Cucumber "Glue" code and step-definitions to achieve this, and we consider all that as un-necessary overhead. You do NOT need a custom DSL. You just have to write custom Java code and invoke those methods from a Karate test. It may not look like "pure English" but it will get the job done in the simplest way possible.
For more examples of advanced Java interop that is possible, please see this example: https://twitter.com/KarateDSL/status/1128170638223364097

Spring Webflux Server Sent Events Thymeleaf

I have a list of subjects that can be registered to students. A subject has a property maxParticipants.
Example:
Subject: Spanish
Max Participants: 5
I want to update the available subject places by a Spring Flux with a given interval. This is no problem (every 10s i do a select count on the datasource to get the available places).
My question is:
How do i update the frontend being rendered with thymeleaf?
There are numerous examples using thymeleaf and spring webflux but all of them are dealing with a large list where the #Controller Model is set with a certain thymeleaf type.
I just want to update existing records.
Do i need to do this with plain javascript/jquery?
Thanks for your tips!
Thomas
You should use EventSource in the web page. Follow example
https://www.mkyong.com/spring-boot/spring-boot-webflux-server-sent-events-example/

Spring JPA With mongo Supporting Contains and LessThan

I am using Spring JPA with mongo.I have a requirement to use contains query on one of the fields.If end users(UI/Service) hits the GET Request and looks for information in EMAIL Field,I need to search based on text.Pretty much it is like.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
This link explains that We can Use Contains to get the Data.
List<ScheduledNotification> findByMobileNumberContaining(String mobileNumber);
List<ScheduledNotification> findByEmailIdIgnoreCaseContaining(String emailId);
But when I am using this API,I am not able to get the data.So ,has any one done something like using Contains.
well ,I was not sending content type in header attribute in GET request.So yes it works,alright.There was no issue with method signature.

How to update the "Replacement Value" in ReplaceText Processor using Rest API?

I need to know how to update the values in nifi processors using Rest API.
https://nifi.apache.org/docs/nifi-docs/rest-api/index.html
For example: I have used below processor structure
GetFile>SplitText>ExtractText>ReplaceText>ConvertJSONToSQL>PUTSQL.
I have passed following inputs for above processors.,
FileLocation(GetFile).
validation(ExtractText).
ReplacementValue(ReplaceText).
DBCP ConnectionPool,username and pwd for SQL.
I just need to use nifi rest api client to write above inputs into processors.
For example : If I give Processor name and input file in Rest API Client then it will write into processor.
Please stop me if anything i'm doing wrong.
Help Appreciated and Tell me any other ways is possible?
Mahen,
You can issue a PUT request to /processors/{id} and provide the new value of the "Replacement Value" property. You'll need to provide JSON body in the request to do this, and you can see the structure by expanding the endpoint noted above on the documentation link you provided, then clicking ProcessorEntity > ProcessorDTO > ProcessorConfigDTO to see the pop-up dialogs with the element listing and examples. You can also quickly get the current values of the processor by issuing a GET request to /processors/{id}.

RESTful api for dynamic showform on top of spring mvc

I want to build a typical mvc app for CRUD of simple items, the api s should be RESTful. The catch here is, that i have a large pallete of items that needs to be initialized. On the server side those items are defined as java beans and the corresponding create form for the item is dynamically created from the field information(data type, validation constraints etc) harvested from the bean.
I am new to REST and just read up about how the urls should be nouns defining the resource and action specified by HTTP verb. In that perspective how to model something like
.../client/showForm?type=xyz from non RESTful way to RESTful one ?? My intention here is to tell the server to dynamically construct and send back a CREATE form for client of type xyz. The obvious problem with url i mentioned above is that it specifies action in the url which, from what i have read, makes it non RESTful.
When I think of REST, I think of resources. I think of data. In other words, I don't think of REST as being something that I would typically use to retrieve a form, which is a user interface component.
REST is an architectural style that is used to identify a resource on a server using a uniform resource identifier, or URI. Additionally, actions performed on those resources identified by the URI are determined based on the specific HTTP Method used in the request: GET, POST, PUT, DELETE, etc.
Thus, let's say you have a Client object. That client object might have the following properties:
Name
Location
AccountNumber
If I wanted to retrieve the data for a single client, I might use the following URI:
GET /client/xyz/ # xyx is the accountnumber used to identify the client.
I would use a GET method, since REST describes GET as being the method to use when retrieving data from the server.
The data could theoretically be returned in HTML, since REST is not a standard but more like a series of flexible guidelines; however, to really decouple my data from my user interface, I would choose to use something platform independent like JSON or XML to represent the data.
Next, when adding a client to the collection on the server, I would use the /client/ URI pattern, but I would use the HTTP Method POST, which is used when adding a resource to a collection on the server.
# Pass the data as JSON to the server and tell the server to add the client to the
# collection
POST /client/ {"accountnumber":"abc" , "Name" : "Jones" , "Location" : "Florida"}
If I were to modify an existing record on the server or replace it, I would most likely use the HTTP Method PUT, since REST guidelines say that PUT should be used if repeating the same operation repeatedly would not change the state of the server.
# Replace the client abc with a new resource
PUT /client/abc/ {"accountnumber":"abc" , "Name" : "Bob Jones" , "Location" : "Florida"}
The general idea behind REST is that it is used to identify a resource and then take action on that resource based on what HTTP Method is used.
If you insist on coupling your data with your view, one way accomplish this and retrieve the actual form, with the client data, could be to represent the form as a resource itself:
GET /client/abc/htmlform/
This URL would of course return your client data for client abc, but in an HTML form that would be rendered by the browser.
While my style of coding utilizes data transports such as JSON or XML to abstract and separate my data from my view, you could very well transport that data as HTML. However, the advantage of using JSON or XML is that your RESTful API becomes platform independent. If you ever expand your API to where other developers wish to consume it, they can do so, regardless of what specific platform or programming language they are using. In other words, the API could be used my PHP, Java, C#, Python, Ruby, or Perl developers.
In other words, any language or platform that can make HTTP requests and can send GET, POST, PUT, DELETE requests can be used to extend or build upon your API. This is the true advantage of REST.
For more information on setting up your controllers to use REST with Spring MVC, see this question. Additionally, check out the Spring MVC Documentation for more information.
Also, if you haven't checked out the Wikipedia article on REST, I strongly encourage you to do so. Finally, another good, classic read on REST is How I Explained REST To My Wife. Enjoy.

Resources