Light4j Cookbook - Rest API, CORS and RDBMS

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Light 4j is a fast, lightweight and cloud-native microservices framework. To learn and know how Light4j works, read our previous article which will give some insight on Light4j and its architecture. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like Mysql, also built in option of CORS handler for in-flight request.

Hybrid framework
 
Hybrid framework provides the facility of both monolithic and microservice options. This is happening because server is separate project and each service is built as individual project, then deploy by bundling the services on each server node or all services in one server as monolithic.

1. Hybrid server can be generated from the scaffold codegen-cli tool by providing the below command.

 java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f light-hybrid-4j-server -o light-example-4j/hybrid/hello-world/server -c model-config/hybrid/hello-world/server/config.json

 Now go to the generated folder path light-example-4j/hybrid/hello-world/server and execute       

 mvn clean install exec:exec

Below will be console output.

 colferPath = /api/colfer
 jsonPath = /api/json
 formPath = /api/form
 HOST IP null
 Http port disabled.
 Https Server started on ip:0.0.0.0 Port:8443

 

2. Hybrid service1 can be generated from the codegen-cli tool by providing the below command. Config project has the project settings and schema for the rest api specifications. 

  java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f light-hybrid-4j-service -o light-example-4j/hybrid/hello-world/service1 -m model-config/hybrid/hello-world/service1/schema.json -c model-config/hybrid/hello-world/service1/config.json

 
 Then build the project with

  mvn clean install

3. Now we can start the server with generated service with following command.   

   > cd networknt/light-example-4j/hello-world/server/target/
   >java -cp hello-1.0.0.jar;../../service1/target/service1-1.0.0.jar com.networknt.server.Server
  

The two services will be included in the server and it can be started.

Handler scanning package =
  RpcStartupHookProvider: handlers size 2
  RpcStartupHookProvider add id lightapi.net/service1/info/0.1.0 map to com.networ
  knt.hello.handler.Info
  RpcStartupHookProvider add id lightapi.net/service1/query/0.1.0 map to com.netwo
  rknt.hello.handler.Query
  Unable to load config 'handler' with extension yml, yaml and json from external
  config, application config and module config. Please ignore this message if you
  are sure that your application is not using this config file.
4. Likewise we can create hello service 2 project and build the project like below.
 java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f light-hybrid-4j-service -o light-example-4j/hybrid/hello-world/service2 -m model-config/hybrid/hello-world/service2/schema.json -c model-config/hybrid/hello-world/service2/config.json

 mvn clean install
5. We can start the server with both services 
   >java -cp hello-1.0.0.jar;../../service1/target/service1-1.0.0.jar;../../service2/target/service2-1.0.0.jar com.networknt.server.Server
 
Develop Hybrid rest services
Now we can develop the command rest API available in service2 project. Below code will receive three parameters, one is command and other two inputs for the command.
 
@ServiceHandler(id="lightapi.net/service2/command/0.1.1")
 public class Command implements Handler {
  @Override
  public ByteBuffer handle(HttpServerExchange exchange, Object input)  {
   LinkedHashMap linkedHashMap = (LinkedHashMap) input;
   String command = linkedHashMap.get("command").toString();
   Integer input1 = Integer.parseInt(linkedHashMap.get("input1").toString());
   Integer input2 = Integer.parseInt(linkedHashMap.get("input2").toString());
   if (command.equals("add")) {
    Integer result = input1+input2;
    String finalOutput = String.format("Result of add two numbers (%d+%d) => %d", input1, input2, result );
    return NioUtils.toByteBuffer(finalOutput);
   }
   return NioUtils.toByteBuffer("Executing command "+input.getClass());
  }
 }
 
We have to modify accordingly the schema json so that rest api receives the parameters accordingly.
{

   "lightapi.net/service2/command/0.1.1":{"schema": {
        "title": "Service2",
        "type": "object",
        "properties": {
          "command": {
            "type": "string"
          },
          "input1": {
            "type": "integer"
          },
          "input2": {
            "type": "integer"
          }
        },
        "required": ["command", "input1"]
      },

     "scope": "command.w"},"lightapi.net/service2/command/0.1.0":{"schema": {
        "title": "Service2",
        "type": "object",
        "properties": {
          "command": {
            "type": "string"
          },
          "input1": {
            "type": "string"
          },
          "input2": {
            "type": "string"
          }
        },
        "required": ["command", "input1"]
      },

  "scope": "command.w"}

 }
 
Then build the project and start the server with service2. When we execute the service, it produces the addition value.
$ curl -k -X POST https://localhost:8443/api/json -d '{"host":"lightapi.net","service":"service2","action":"command","version":"0.1.1","data":{"command":"add","input1":"1","input2":"2"}}'
 
 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current Dload  Upload   Total   Spent    Left  Speed
 100   168  100    36  100   132     74    272 --:--:-- --:--:-- --:--:--   347

Result of add two numbers (1+2) => 3 
 
Rest Database Access
 
In Hybrid server, add the datasource in service.yml
  - javax.sql.DataSource:
    - com.zaxxer.hikari.HikariDataSource:
         DriverClassName: com.mysql.jdbc.Driver
         jdbcUrl: jdbc:mysql://host:port/dbname?useSSL=false
         username: root
         password:
         maximumPoolSize: 10
         useServerPrepStmts: true
         cachePrepStmts: true
         cacheCallableStmts: true
         prepStmtCacheSize: 10
         prepStmtCacheSqlLimit: 2048
         connectionTimeout: 2000
 
Also add the corresponding dependencies in server pom.xml. Now in service 1 project, do the connection from data source and then query the datbase with prepraredstatement and respond back.
   

     <version.hikaricp>3.1.0</version.hikaricp>
     <version.mysql>6.0.5</version.mysql>
     <version.h2>1.3.176</version.h2>
    <version.gson>2.8.5</version.gson>

     <dependency>
       <groupId>com.zaxxer</groupId>
         <artifactId>HikariCP</artifactId>
         <version>${version.hikaricp}</version>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${version.mysql}</version>
      </dependency>
 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version> ${version.gson}</version>
  </dependency>
      <dependency>
       <groupId>com.h2database</groupId>
         <artifactId>h2</artifactId>
         <version>${version.h2}</version>
         <scope>test</scope>
      </dependency>

 

  public class StudentModel {
    private int id;
    private String studentName;
 
    public StudentModel(int id, String studentName) {
      super();
      this.id = id;
      this.studentName = studentName;
    }
    public int getId() {
      return id;
    }
    public void setId(int id) {
      this.id = id;
   }
   public String getStudentName() {
     return studentName;
  }
  public void setStudentName(String studentName) {
     this.studentName = studentName;
 }
}
 
@ServiceHandler(id="lightapi.net/service1/query/0.1.0")
public class Query implements Handler {
    private static final DataSource ds = SingletonServiceFactory.getBean(DataSource.class);
    @Override
    public ByteBuffer handle(HttpServerExchange exchange, Object input)  {
        String result = "";
        try {
            Connection connection = ds.getConnection();
            System.out.println("connected to database");

         List<StudentModel> studentList = new ArrayList<>();
            PreparedStatement statement = connection.prepareStatement("SELECT * FROM studentdb");

            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                studentList.add(new StudentModel(resultSet.getInt("id"), resultSet.getString("studentname")));
            }
        } catch (Exception exception){
            System.out.println("exception: "+exception);

        }
        return NioUtils.toByteBuffer(gson.toJson(studentList));
    }
 }

 

So now when we hit the curl command for the query service, it will retrieve all the records from the database.(so please create table with dbname and have some records).

$  curl -k -X POST https://localhost:8443/api/json -d '{"host":"lightapi.net","service":"service1","action":"query","version":"0.1.0","data":{"param1":"value1","param2":"value2"}}'

 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current  Dload  Upload   Total   Spent    Left  Speed
 100   385  100   261  100   124    341    162 --:--:-- --:--:-- --:--:--   503 

 [{"id":1,"studentName":"Ram"},{"id":2,"studentName":"Sam"},{"id":3,"studentName":"Tom"},{"id":4,"studentName":"Bob"}]

 

CORS handler

Cross Origin Resource Sharing handler handles the pre-flight OPTIONS request to enable CORS. Light4j provides flexibility of adding allowed origins in the configuration file cors.yml.

Generate the cors project from light codegen tool as shown below. It also works for simple rest api tutorial.

  java -jar light-codegen/codegen-cli/target/codegen-cli.jar -f openapi -o light-example-4j/rest/openapi/cors -m model-config/rest/openapi/cors/openapi.json -c model-config/rest/openapi/cors/config.json

 

Enable the cors handler by doing the below steps:

1. Add the maven dependency

    <dependency>
       <groupId>com.networknt</groupId>
       <artifactId>cors</artifactId>
       <version>${version.light-4j}</version>
    </dependency>

2. Create cors.yml file in src/main/resources/config/

    description: Cors Http Handler
    enabled: true
   allowedOrigins:
     - http://example.com
   allowedMethods:
     - GET
     - POST

3. Add the pathhandler provider

    # HandlerProvider implementation
     - com.networknt.handler.HandlerProvider:
     - com.networknt.cors.PathHandlerProvider under singletons.

 
4. Add the cors http handler in the middleware handler.

    - com.networknt.handler.MiddlewareHandler:
      #Cors handler to handler post/put pre-flight
      - com.networknt.cors.CorsHttpHandler

The above steps can be done in the ligh4j rest api project to enable CORS handler, only the path handler routing need to be added. Build and execute the below project.

    mvn clean install exec:exec
 
Now hit the pet store api with OPTIONS methods through curl command.
 
  curl -k -H "Origin: http://test123.com" -H "Access-Control-Request-Method: POST"  -H "Access-Control-Request-Headers: X-Requested-With"  -X OPTIONS --verbose https://localhost:8443/v1/postData
 
Following output will produce it.
 
 < HTTP/2 200 
 < access-control-allow-headers: X-Requested-With
 < server: L
 < access-control-allow-credentials: true
 < content-length: 0
 < access-control-allow-methods: GET
 < access-control-allow-methods: POST
 < access-control-max-age: 3600
 < date: Sat, 30 Mar 2019 15:14:31 GMT

References:
 

   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Laravel Paypal Integration - Smart button with server-side integration

  • laravel paypal smart-button

You would have seen a lot of blogs for paypal php integration with REST api which is driven completely in the backend. For checkout, paypal provides an easy way to checkout for client side ready-to-use smart button payment. This approach will work only from the frontend, which will not be safe and difficult to reconcile as the backend does not have any information about it. Server side integration with the paypal smart button will help us to reconcile or track the payments even after some issues in the users payment journey. In this blog, we have walkthrough the paypal smart button with server side php laravel integration.

Read More


RESTEasy Advanced Guide - Filters and Interceptors

  • resteasy rest-api filters interceptors java

RESTEasy is JAX-RS 2.1 compliant framework for developing rest applications. It is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More



ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More


Data dumping through REST API using Spring Batch

  • spring-batch data-dump rest-api java

Most of the cloud services provide API to fetch their data. But data will be given as paginated results as returning the complete data will overshoot the response payload. To discover the complete list of books or e-courses or cloud machine details, we need to call the API page-wise till the end. In this scenario, we can use Spring Batch to get the data page by page and dump it into a file.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More


Solr vs Elastic Search

  • full-text-search search-engine lucene solr elastic-search

Solr and Elastic Search are built on top of Lucene. Both are open source and both have extra features which makes programmer life easy. This article explains the difference and the best situation to choose between them.

Read More


Data Fetching and Form Building using NextJS

  • nextjs data-fetching form-handling

Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in Next.js and collect the data without maintaining the database.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More


An introduction to MongoDB

  • mongodb database document-oriented-databse no-sql c++ data-mining

MongoDB is the most exciting SQL-free database currently available in the market. The new kid on the block, called MongoDB is a scalable, high-performance, open source, schema free and document oriented database that focuses on the ideas of NoSQL Approach. Written in C++, it has taken rapid strides since its emergence into the public sphere as a popular way to build your database applications.

Read More


Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More


PrestaShop - A feature rich Open Source eCommerce solution

PrestaShop is an Open Source eCommerce Solution. It comes complete with over 310 features that have been carefully developed to assist business owners in increasing sales with virtually little effort. It is being used in more than 150,000 online stores.

Read More


Web based commenting system. Embed directly in to your site

  • comment free commenting-system

Comments are very important for a blog or website to get feedback from their users. Comments could be threaded where users could be discuss and post reply to the comment. Here we going discuss about the most popular and widely used free commenting system. You need to embed their javascript code in your every page and it will take care the rest of the task.

Read More


Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.