Automatically generate java backend and rest api from existing database. Part 2

Expanding on the previous subject about the generation of a back-end and rest API from existing database .

  • Netbeans has a generate entities from database script
  • Jeddict  . This could be already be pre-installed in some Netbeans products
  • Dali persistence tools from Eclipse
  • Hibernate Tools

Jipster offers the on line tool JDL-studio: there you can visually create tables and relationships. Entities generation from database is only available with an external tool. Beware of some cumbersome issues.

 

Last and most important: your good SQL database may be able to generate the text of the most important queries towards you database. Look at PostgreSql . Their pgAdmin toll has many features like these for generating things.

 

 

REST and CQRS Command Query Responsibility Segregation

CQRS stands for Command Query Responsibility Segregation.
REST goes well with CQRS when we use the paradigm of “REST without PUT”.
The idea is that we no longer PUT the “new” state of an entity, instead we make our mutations be first class  citizen nouns (rather than verbs), and POST them.

REST without PUT has a side-benefit of separating command and query interfaces (CQRS)  and forces consumers to allow for eventual consistency.
We POST command entities to one endpoint (the “C” of CQRS) and GET a model entity from another endpoint  (the “Q”).

Automatically generate java backend and rest api from existing database

I am working a lot with databases , hibernate , restful apis in Java SE / java EE with HTML clients.
I am pleased to suggest this workflow that relies on Netbeans automatic generation capabilities.

1. Netbeans generates JPA entities from an existing database.

As it is described at Dzone and at Oracle site.
You have also the option of generating JAXB annotations directly in the JPA entity classes.

2. Netbeans generates then restful api from the entities.

As it is described at NetBeans Help site.

It is really a breeze to come up fast with a Java backend.
I am working now on the HTML / javascript/ jquery client and I will let you know.

Comparison of Automatic REST API Code Generation Tool

I spent some time trying to find a proper tool that is able to generate tidy Java code for REST resources.

My requirements are:

  • The Java code must be readable and not polluted with a lot of imports that refer to the tool maker .
  • The input should be short and simple.

I stopped by two tools as they were the only ones that would comply with my requirements. They are:

  • Restunited
  • Swaggerhub

Swaggerhub wins.

The reason is that a yaml definition file is used as input to Swaggerhub. Also the output consisted of tidy and simple java classes for the server implementations based on jax-rs.

Here it is a yaml specification file you can begin with at Swaggerhub:

swagger: '2.0'
info:
version: '0'
title: Cars Rental Store
description: Allow clients to loan cars
paths:
    /rentals:
        get:
                summary: Product Types
                description: |
                        bla bla bla.
                parameters:
                        - name: rentals_id
                in: query
                    description: id of.
                    required: true
                    type: number
                    format: double
                tags:
                    - Rentals
                responses:
                    200:
                        description: An array of rentals
                        schema:
                            type: array
                            items:
                                $ref: '#/definitions/Rental'
                        default:
                            description: Unexpected error
                            schema:
                                $ref: '#/definitions/Error'
definitions:
        Car:
                type: object
                properties:
                        car_id:
                            type: number
                            description: Unique identifier representing a specific car.
                        title:
                            type: string
                            description: Description of car.
        Rentals:
                type: object
                properties:
                        rental_id:
                            type: string
                            description: Unique identifier representing a specific rental.
        Cars:
                type: array
                items:
                        $ref: "#/definitions/Car"
                description: bla bla.
        Error:
                type: object
                properties:
                code:
                        type: integer
                        format: int32
                        message:
                                type: string
                fields:
                        type: string

A REST and websocket programmers daily log

We want to share issues and annoyances that made our trip slower.

ThreadLocalRandom

Good to remember that it exists.

JSON Parsing

It is possible to use Jackson with no JAXB as for these examples
https://github.com/jersey/jersey/tree/2.17/examples/json-jackson
and this specification
https://jersey.java.net/nonav/documentation/latest/media.html#json.jackson

MessageBodyProviderNotFoundException

The MessageBodyProviderNotFoundException has to do with JSON deserialization.
It is the sympton and happens when Jersey client deserializea a map or collections when readEntity fails
http://stackoverflow.com/questions/26818492/serialization-and-deserialization-of-map-with-jersey-and-jackson

Test With ObjectMapper

@Test
public void testGetIt() throws Exception {
String responseMsg = target.path(“apipath”).request().get(String.class);
ObjectMapper mapper = new ObjectMapper();
MyList books = mapper.readValue(
responseMsg, MyListAnswer.class);
System.out.println(books);
}

SERVLET, JERSEY and TOMCAT

Jersey version 2 servlet

If you want to use jersey version 2 you need to replace the servlet definition with the following:

<servlet>
<servlet-name>Jersey-Servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.memorynotfound.rs</param-value>
</init-param>
</servlet>
===============
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>

Cannot call sendError() after the response has been committed

Solution: return after sendError() to avoid chain.doFilter(request, response); to be called

How throttle servlet requests-Solution

Use a  web filter.

ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Solution: .war file is incomplete. Make it again and check that it contains all libraries.

Setting property ‘source’ to ‘org.eclipse.jst.jee.server:appname’ did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate “Publish module contents to separate XML files”. Finally, restart your server, the message must disappear.

At least one JAR was scanned for TLDs yet contained no TLDs

Set catalina.properties
tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*.jar

Charting, Rickshaw, JavaScript, Servlet, JSON

set “Keep-alive” to … with JAX-RS Response.header() .

IMPLEMENT PUSH WITH WEBSOCKETS IN JAVA

Client javascript parsing of Json

Use JSON.parse in onMessage(), or everything will be caos 🙂

function onMessage(event) {
  var json = JSON.parse(event.data);

Some help

http://stackoverflow.com/questions/25947790/real-time-updates-from-database-using-jsf-java-ee/

MAVEN

Update repository , and mirrors
https://maven.apache.org/guides/mini/guide-configuring-maven.html

Install custom jars
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

GIT

Setting up kdiff3 as the Default Merge Tool for git on Windows

Edit .gitconfig , it is usually in your user directory. There may exist other .gitconfig files, pay attention please!

[merge]
tool = kdiff3
[mergetool “kdiff3”]
path = “D:/Progra~1″/KDiff3/kdiff3.exe
cmd = “D:\\Progra~1\\KDiff3\\kdiff3.exe” $BASE $LOCAL $REMOTE -o $MERGED
cmdOK = “D:/Progra~1″/KDiff3/kdiff3.exe
keepBackup = false
trustExitCode = false