Thursday, February 27, 2020

Spring Boot REST API with SQLServer 2019

In this post I will demonstrate how to change MySQL Spring Boot application in to Microsoft SQL database. For this I will use code base of my previous post "Spring Boot REST API CRUD operations with MySQL with Spring Data". You can access steps to correctly install MSSQL server in following blog post "Installing SQL Server 2017 Express edition in windows".

Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.
  4. MS SQL server need to be installed. 

Dependency Configure existing project 

I will use following project https://github.com/NirmalBalasooriya/RestApiSpringBoot for the demonstration of this post. Check out the project in to you IDE. 

First remove the MySQL dependency as show below
<!-- Runtime -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

Add the MSSQL dependency 

<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>


After update pom file would be as follows.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nirmal.springbootrest</groupId>
  <artifactId>RestApiSpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Provided -->
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
<!-- Runtime -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.1.0.jre8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>



Modify SpringBoot Configure on application.properties 


To configure MSSQL database we have to modify database URL, username, password, driver class name and database-platform. Update the file based on your configuration for username and password.

#==== connect to mysql ======#
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=TestDB
spring.datasource.username=nirmal
spring.datasource.password=Test123_
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect


spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=true

#==== Logging configurations ======#
logging.level.root=WARN,INFO,ERROR
logging.level.com.baeldung=TRACE



Run the application

In order to run first we have to perform maven install command and then we can run the application

Go to run debug configuration and add following command 

spring-boot:run



Then run the application  by click on Run button


After successful execution you should be able to see similar output as show below.



Also you should be see table has been created on your configured Database and you can access the web service from following URL. 

http://localhost:8080/findBook/1

With following out put on web browser.





Lets Test the application 


Then lets add new Book in to API


curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{ \"isbmNumber\":\"9999\", \"name\":\"How to develop API\", \"description\":\"sample book\", \"auther\":\"Nirmal Balasooriya \" }" http://localhost:8080/saveOrUpdate

  
For this one following output will return


{"code":"1","desc":"Book save successful","t":"9999"}


If you check the database you can see data has been inserted to the Database.


Also we can access data through API as well http://localhost:8080/findBook/9999





You can access the updated code base from following GitHub URL.

Tuesday, February 25, 2020

SpringBott change default port

In this post I will demonstrate situation where we need to run two Spring Boot instance in single server on two different ports.

Prerequisites 
  1. You should have install java 1.8 or above.
  2. You should have Eclipse installed in your PC.
  3. Your PC should setup Maven installed and configured.
  4. Your PC should have installed MySQL and Server need to have user who have access to the configured database and user should able to log in to the database by user name/password. 


Configure existing project from GITHUB

I will use https://github.com/NirmalBalasooriya/RestApiSpringBoot Project for the demonstration of this post. Check out the project in to you IDE.

Then open project property file and update the Database username and password according to your MySQL instance.

#==== connect to mysql ======#
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/sample?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.continueOnError=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=true

#==== Logging configurations ======#
logging.level.root=WARN,INFO,ERROR
logging.level.com.baeldung=TRACE


Run the application

I will demonstrate it from IntelliJ as mention below. First perform maven install command by double click on "install" under maven in InelliJ as show below.



Then after successful installation you can see generated jar file in target folder. Go to that target folder from command line and run the application by executing following command in command line.


java -jar RestApiSpringBoot-0.0.1-SNAPSHOT.jar

After successful run you should be able to see following output on command line. As you can see server started on port 8080 which is default port.




Now you should be able to access following web endpoint

http://localhost:8080/findBook/1


Lets configure the application on different port and Run the application

In order to run on different port we need to add server.port configuration in to Spring Boot property file.

#==== connect to mysql ======#
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/sample?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.continueOnError=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port = 8090

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=false
spring.jpa.properties.hibernate.format_sql=true

#==== Logging configurations ======#
logging.level.root=WARN,INFO,ERROR
logging.level.com.baeldung=TRACE

Now lets run the application

Go to run debug configuration and add following command 

spring-boot:run



Then run the application  by click on Run button




Then you should be able to see following output after successful start of the applciation



Now server started on 8090 and you should be able to access same web service from following like.


http://localhost:8090/findBook/1

Monday, February 17, 2020

External Active MQ + Hibernate with JBoss FUSE 7.4

In this post I will demonstrate how to configure External Active MQ with JPA implementation of Hibernate on Karaf platform on JBoss fuse 7.4. I will use previous JPA project as code base to start the development. You can refer about it from my previous blog post.


Prerequisites 


  1. You should have install java 1.8 or above.
  2. You should have IDE installed in your PC in my case I'm using IntelliJ IDEA.
  3. Your PC should setup Maven installed and configured.
  4. Your  PC should install and setup SQLServer.
  5.  Checkout base project from JPA project as code base.


Application module Dependency 

First Lets add relevant dependencies in to Application POM file. Following is the full feature file content and updated part on bold font. Since we are using ActiveMQ we need to add relevant dependency for that.


<?xml version="1.0" encoding="UTF-8"?>
<features name="osgi-customer-management-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.3.0 http://karaf.apache.org/xmlns/features/v1.3.0">
    <feature name="osgi-customer-management-datasource" version="${project.version}">
        <config name="org.ops4j.datasource-customer-management">
            osgi.jdbc.driver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver
            osgi.jdbc.driver.name=mssql
            databaseName=customer-management
            url=jdbc:sqlserver://LAPTOP-E0A1RCAN:1433;databaseName=customer-management
            user=nirmal
            password=Test123_
            dataSourceName=customer-management
            org.apache.karaf.features.configKey = org.ops4j.datasource-customer-management
        </config>
        <capability>osgi.service;javax.persistence.EntityManager;objectClass=javax.sql.DataSource;osgi.jndi.service.name=customer-management</capability><!--;effective:=active-->
    </feature>
    <feature name="Model" version="${project.version}">
        <feature>transaction</feature>
        <feature>jndi</feature>
        <feature>pax-jdbc-config</feature>
        <feature>pax-jdbc-h2</feature>
        <feature>pax-jdbc-mssql</feature>
        <feature>pax-jdbc-pool-dbcp2</feature>
        <feature>jdbc</feature>
        <feature>pax-jms-pool</feature>
        <feature>pax-jms-config</feature>
        <feature>camel-activemq</feature>
        <feature>artemis-jms-client</feature>
        <feature>pax-jms-artemis</feature>
        <feature>camel-blueprint</feature>
        <feature>camel-jms</feature>
        <feature>camel-activemq</feature>
        <feature>pax-jms-activemq</feature>
        <feature dependency="true">aries-blueprint</feature>
        <feature version="[2,3)">jpa</feature>
        <feature version="[5,6)">hibernate</feature>
        <bundle>mvn:com.fuse.hibernate.example/Model/${project.version}</bundle>
    </feature>
    <feature name="Service" version="${project.version}">
        <feature version="${project.version}">Model</feature>
        <bundle>mvn:com.fuse.hibernate.example/Service/${project.version}</bundle>
        <capability>osgi.service;objectClass=javax.persistence.spi.PersistenceProvider;effective:=active;javax.persistence.provider=org.hibernate.jpa.HibernatePersistenceProvider</capability>
    </feature>
    <feature name="Application" version="${project.version}">
        <feature version="${project.version}">Model</feature>
        <feature version="${project.version}">Service</feature>
        <bundle>mvn:com.fuse.hibernate.example/Application/${project.version}</bundle>
    </feature>
</features>



Defining the ActiveMQ endpoint in BluePrint  


We can add ActiveMQ endpoint in to our BlurPrint.xml file in the Application module. We just need to modify following content which colored in bold. 

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0" xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
  <jpa:enable />
  <tx:enable-annotations />
  <service ref="personService" interface="com.fuse.hibernate.example.service.PersonService" />
  <bean id="personService" class="com.fuse.hibernate.example.service.PersonServiceImpl" />
  <bean
          class="com.fuse.hibernate.example.app.ExchangeProcessor" id="exchangeProcessor">
    <property name="personService" ref="personService"/>
  </bean>
  <bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
    <property name="brokerURL" value="tcp://localhost:61616"/>
  </bean>

  <camelContext xmlns="http://camel.apache.org/schema/blueprint"
                id="cbr-example-context" >
    <route id="cbr-route" >
      <from uri="file:work/cbr/input" />
      <log message="Sending order ${file:name} to another country" />
      <log id="logStatusIncident" message="OrderDetails Call ${body}"/>
      <to uri="file:work/cbr/output/others" />
      <convertBodyTo type="java.lang.String"/>
      <process ref="exchangeProcessor"/>
      <log  message="${body}" />

    </route>

    <route id="ACTIVEMQ">
      <from uri="activemq:queue:inbound.queue"/>
      <process ref="exchangeProcessor"/>
      <log  message="${body}" />
    </route>
  </camelContext>

</blueprint>


Explanation of the route "ACTIVEMQ"
It will read messages from "inbound.queue" and then it will pass to the "exchangeProcessor"  which have the responsibility of saving the message that passing from the queue.


Installing in to FUSE 7.4

We can use same set of commands except one new dependency addition code. In order to add dependencies first we have to run the fuse.bat file and then go to the console and enter following commands one by one. Only the third command new from previous post.


osgi:install -s mvn:com.microsoft.sqlserver/mssql-jdbc/7.4.1.jre8

osgi:install -s mvn:org.ops4j.pax.jdbc/pax-jdbc-mssql/1.3.5

osgi:install -s mvn:org.apache.cxf/cxf-rt-rs-client/3.0.4.redhat-621084



Then lets install application by entering following commands one by one


feature:repo-add mvn:com.fuse.hibernate.example/Feature/1.0-SNAPSHOT/xml



feature:install osgi-customer-management-datasource


feature:install Model

feature:install Service

feature:install Application


Then after "list" command you should be able to see all the things we installed. Similar to below figure.

After Successful installation LIST command should return something similar to this.

You can verify by accessing http://localhost:8181/cxf/ link you should be able to see following UI in browser.

http://localhost:8181/cxf/ output once successfully installed the Application 

Now you can click the WADL link and see the defined endpoints in there.

WADL output for defined REST service.
If you check the "http://localhost:8181/hawtio/camel/routes" then you should be able to see similar figure to below figure.

hawtio camel routes 

Lets run ActiveMQ server


In order to demonstrate this we need to have ActiveMQ server run in our local PC. First lets download it from official web page in following location. Then extract it in to your local PC and then go to apache-activemq-5.15.11\bin\win64 location from extraction parent directory. Then run the activemq.bat to start our ActiveMQ server.


Then you can go to http://localhost:8161/admin/queues.jsp URL and see your available Queues in PC. Since we have note created any you suppose to see similar page as bellow.




Then you can enter "inbound.queue" as Queue Name and then clieck Create button. after it successfully created queue you could be able to see the newly created ActiveMQ queue "inbound.queue" as show in bellow.





Test the functionality

We can test the functionality by sending new message in to "" queue as mentioned follows. First go to ActiveMQ web console(you need to provide login details) Then click on send To link inline with your created queue.

Click Send To link as show on figure 

Then past following structured xml in message box as show in below figure.


<Person>   <name>nirmal</name>   <city>Seatle</city>   <country>USA</country></Person>





Then click on the send button. Now you can check the database and you should be able to see persist person data as show below.


Database Person table after executing above command




You can download the entire source code from following GIT hub URL.