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:
 

Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

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


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


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


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


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


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


Lucene / Solr as NoSQL database

  • lucene solr no-sql nosql document-store

Lucene and Solr are most popular and widely used search engine. It indexes the content and delivers the search result faster. It has all capabilities of NoSQL database. This article describes about its pros and cons.

Read More


Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More


An introduction to LucidWorks Enterprise Search

  • lucene solr search engine enterprise

Lucidworks Enterprise search solution is built on top of Apache Solr. It scales seamlessly w/sub-second response times under extreme query loads for multi-billion document collections. It has user friendly UI, which does all the job of configuration and search.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


Caching using Ehcache Java Library

  • ehcache cache java map key-value

Ehcache from Terracotta is one of Java's most widely used Cache. It is concurrent and highly scalable. It has small footprint with SL4J as the only dependencies. It supports multiple strategies like Expiration policies, Eviction policies. It supports three storage tiers, heap, off-heap, disk storage. There are very few caching products supports multiple tier storage. If you want to scale, you cannot store all items in heap there should be support for off-heap and disk storage. Ehcache is licensed under Apache 2.0. In this article, we can see about basic usage of Ehcache.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More