Dec 12, 2017

Spring Boot + Restful Services + MongoDB Demo





















Install and run MongoDB 















Out put:
















 Git Source:

https://github.com/knmuni/spring-boot-mongodb-demo




Dec 3, 2017

Spring Boot Kafka - Producer Consumer Demo
























Test Result :
















Git Source:

https://github.com/knmuni/spring-kafka-demo

Thank you ! :)









Dec 2, 2017

Spring Boot Apache Kafka (Restful Services ) Demo

                  


Kafka download URL:

http://kafka.apache.org/downloads.html















Unzip in to location










Start Apache Zookeper (Open a new command)

D:\j2ee-workspace-neon\kafka_2.11-1.0.0>.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties













Start Apache Kafka (Open a new command)

D:\j2ee-workspace-neon\kafka_2.11-1.0.0>.\bin\windows\kafka-server-start.bat .\config\server.properties














Start Topic  (Open a new command)

D:\j2ee-workspace-neon\kafka_2.11-1.0.0>.\bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic kafka_test_topic --from-beginning
















Test url:

http://localhost:8080/kafka-rest-demo/producer?message=test

Git Source 
https://github.com/knmuni/SpringBootKafkaRestDemo


Thank you  :)






Oct 29, 2017

MyBatis with Spring Boot Example



                                                Eclipse Project Structure
                      
       



Git : https://github.com/knmuni/MyProjectWorkspace#spring-boot-mybatis-mysql-example
      

Oct 16, 2016

A Simple EJB3 project (Jboss-as-7.1.1 , Eclipse and Maven)


Eclipse Project Structure (EJB & Client


EJB Demo (EJB project)



  
1. HelloWorld .java (Interface )

package com.test.ejb;
import javax.ejb.Remote;
@Remote
public interface HelloWorld {
 public String sayHello();
}

2. HelloWorldBean

package com.test.ejb;
import javax.ejb.Stateless;
/**
 * Session Bean implementation class HelloWorldBean
 */
@Stateless
public class HelloWorldBean implements HelloWorld {
    /**
     * Default constructor.
     */
    public HelloWorldBean() {
        // TODO Auto-generated constructor stub
    }
 @Override
 public String sayHello() {
  // TODO Auto-generated method stub
  return "Hello World !!!";
    }
}

3. jboss-ejb-client.properties (This needs to be under SRC folder)

remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false
remote.connections=default
remote.connection.default.host=localhost
remote.connection.default.port = 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
remote.connection.default.username=userName
remote.connection.default.password=password123

4. pom.xml

<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>EJBDemo</groupId>
 <artifactId>EJBDemo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>EJBDemo</name>
 <url>http://maven.apache.org</url>
 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <!-- JBoss dependency versions -->
  <version.org.jboss.as.plugins.maven.plugin>7.1.Final</version.org.jboss.as.plugins.maven.plugin>
  <version.org.jboss.spec.jboss.javaee.6.0>3.0.0.Final</version.org.jboss.spec.jboss.javaee.6.0>
  <!-- other plugin versions -->
  <version.compiler.plugin>2.3.1</version.compiler.plugin>
  <version.ejb.plugin>2.3</version.ejb.plugin>
  <!-- maven-compiler-plugin -->
  <maven.compiler.target>1.6</maven.compiler.target>
  <maven.compiler.source>1.6</maven.compiler.source>
 </properties>
 <dependencyManagement>
  <dependencies>
   <dependency>
    <groupId>org.jboss.spec</groupId>
    <artifactId>jboss-javaee-6.0</artifactId>
    <version>${version.org.jboss.spec.jboss.javaee.6.0}</version>
    <type>pom</type>
    <scope>import</scope>
   </dependency>
  </dependencies>
 </dependencyManagement>
 <dependencies>
  <dependency>
   <groupId>org.jboss.spec.javax.annotation</groupId>
   <artifactId>jboss-annotations-api_1.1_spec</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss.spec.javax.ejb</groupId>
   <artifactId>jboss-ejb-api_3.1_spec</artifactId>
   <scope>provided</scope>
  </dependency>
 </dependencies>
 <build>
  <!-- Set the name of the deployment -->
  <plugins>
   <!-- JBoss AS plugin to deploy the application -->
   <plugin>
    <groupId>org.jboss.as.plugins</groupId>
    <artifactId>jboss-as-maven-plugin</artifactId>
    <version>${version.org.jboss.as.plugins.maven.plugin}</version>
    <configuration>
     <filename>${project.build.finalName}.jar</filename>
    </configuration>
   </plugin>
   <!-- Compiler plugin enforces Java 1.6 compatibility and activates annotation
    processors -->
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${version.compiler.plugin}</version>
    <configuration>
     <source>${maven.compiler.source}</source>
     <target>${maven.compiler.target}</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ejb-plugin</artifactId>
    <version>${version.ejb.plugin}</version>
    <configuration>
     <ejbVersion>3.1</ejbVersion>
     <!-- this is false by default -->
     <generateClient>true</generateClient>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

EJB EAR folder structure


After successfully compiled please deploy EJBDemoEAR.ear to JBoss server




EJB client





















ClientUtility.java

package com.test.ejbclient;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ClientUtility {

 private static Context initialContext;
 private static final String PKG_INTERFACES = "org.jboss.ejb.client.naming";
 public static Context getInitialContext() throws NamingException {
  if (initialContext == null) {
   Properties properties = new Properties();
   properties.put(Context.URL_PKG_PREFIXES, PKG_INTERFACES);
   initialContext = new InitialContext(properties);
  }
  return initialContext;
 }
}

Client.java (Run as Java Application)

package com.test.ejbclient;
import javax.naming.Context;
import javax.naming.NamingException;
import com.test.ejb.HelloWorld;
public class Client {

 public static void main(String[] args) {

  HelloWorld bean = doLookup();
  // 4. Call business logic
  System.out.println(bean.sayHello());
 }
 private static HelloWorld doLookup() {
  Context context = null;
  HelloWorld bean = null;
  try {
   // 1. Obtaining Context
   context = ClientUtility.getInitialContext();
   System.out.println("Context::::::::" + context);
   // 2. Generate JNDI Lookup name
   String lookupName = getLookupName();
   System.out.println("lookup::::::::" + lookupName);
   // 3. Lookup and cast
   bean = (HelloWorld) context.lookup(lookupName);
   System.out.println("Bean look up ..........." + bean);
   context.close();
  } catch (NamingException e) {
   e.printStackTrace();
  }
  return bean;
 }
 private static String getLookupName() {
  /*
   * The app name is the EAR name of the deployed EJB without .ear suffix.
   * Since we haven't deployed the application as a .ear, the app name for
   * us will be an empty string
   */
  String appName = "EJBDemoEAR";
  /*
   * The module name is the JAR name of the deployed EJB without the .jar
   * suffix.
   */
  String moduleName = "EJBDemo";
  /*
   * AS7 allows each deployment to have an (optional) distinct name. This
   * can be an empty string if distinct name is not specified.
   */
  String distinctName = "";
  // The EJB bean implementation class name
  String beanName = "HelloWorldBean";
  // Fully qualified remote interface name
  final String interfaceName = "com.test.ejb.HelloWorld";
  // Create a look up string name
  String name = "ejb:" + appName + "/" + moduleName + distinctName + "/"
    + beanName + "!" + interfaceName;

  return name;
 }
}

pom.xml

<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>EJBDemo</groupId>
 <artifactId>EJBDemoClient</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>
 <name>EJBDemoClient</name>
 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <!-- JBoss dependency versions -->
  <version.org.jboss.as>7.1.1.Final</version.org.jboss.as>
  <version.org.jboss.as.plugins.maven.plugin>7.3.Final</version.org.jboss.as.plugins.maven.plugin>
  <version.org.jboss.spec.jboss.javaee.6.0>3.0.0.Final</version.org.jboss.spec.jboss.javaee.6.0>
  <!-- other plugin versions -->
  <version.compiler.plugin>2.3.1</version.compiler.plugin>
  <version.exec.plugin>1.2.1</version.exec.plugin>
  <!-- maven-compiler-plugin -->
  <maven.compiler.target>1.6</maven.compiler.target>
  <maven.compiler.source>1.6</maven.compiler.source>
 </properties>
 <dependencyManagement>
  <dependencies>
   <dependency>
    <groupId>org.jboss.spec</groupId>
    <artifactId>jboss-javaee-6.0</artifactId>
    <version>${version.org.jboss.spec.jboss.javaee.6.0}</version>
    <type>pom</type>
    <scope>import</scope>
   </dependency>
   <dependency>
    <groupId>org.jboss.as</groupId>
    <artifactId>jboss-as-ejb-client-bom</artifactId>
    <version>${version.org.jboss.as}</version>
    <type>pom</type>
    <scope>import</scope>
   </dependency>
  </dependencies>
 </dependencyManagement>
 <dependencies>
  <dependency>
   <groupId>org.jboss.spec.javax.transaction</groupId>
   <artifactId>jboss-transaction-api_1.1_spec</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss.spec.javax.ejb</groupId>
   <artifactId>jboss-ejb-api_3.1_spec</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>EJBDemo</groupId>
   <artifactId>EJBDemo</artifactId>
   <type>ejb-client</type>
   <version>${project.version}</version>
  </dependency>
  <dependency>
   <groupId>org.jboss</groupId>
   <artifactId>jboss-ejb-client</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss.xnio</groupId>
   <artifactId>xnio-api</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss.xnio</groupId>
   <artifactId>xnio-nio</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss.remoting3</groupId>
   <artifactId>jboss-remoting</artifactId>
   <scope>runtime</scope>
  </dependency>
  <!-- Remote EJB accesses can be secured -->
  <dependency>
   <groupId>org.jboss.sasl</groupId>
   <artifactId>jboss-sasl</artifactId>
   <scope>runtime</scope>
  </dependency>
  <!-- data serialization for invoking remote EJBs -->
  <dependency>
   <groupId>org.jboss.marshalling</groupId>
   <artifactId>jboss-marshalling-river</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.jboss</groupId>
   <artifactId>jboss-remote-naming</artifactId>
   <version>1.0.7.Final</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <!-- Enforce Java 1.6 -->
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${version.compiler.plugin}</version>
    <configuration>
     <source>${maven.compiler.source}</source>
     <target>${maven.compiler.target}</target>
    </configuration>
   </plugin>
   <!-- Add the maven exec plugin to allow us to run a java program via maven -->
   <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>${version.exec.plugin}</version>
    <executions>
     <execution>
      <goals>
       <goal>exec</goal>
      </goals>
     </execution>
    </executions>
    <configuration>
     <executable>java</executable>
     <workingDirectory>${project.build.directory}/exec-working-directory</workingDirectory>
     <arguments>
      <!-- automatically creates the classpath using all project dependencies,
       also adding the project build directory -->
      <argument>-classpath</argument>
      <classpath>
      </classpath>
      <argument>com.test.ejbclient.Client</argument>
     </arguments>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

Output :











Thank you ! :)






Apr 21, 2016

Hibernate EHCache Second Level Caching Example(Hibernate 4.x + Maven + MySQL 5.x)

1. Eclipse Project Structure



2. Java Code

2.1.Employee.java ( Entity Class)

package com.test.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Table(name = "employee")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY, region = "employee")
public class Employee {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 private int id;
 @Column(name = "firstname")
 private String firstName;
 @Column(name = "lastname")
 private String lastName;
 @Column(name = "telephone")
 private String telephone;
 @Column(name = "email")
 private String email;
 public Employee() {
 }
 public Employee(String firstName, String lastName, String telephone,
   String email) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.telephone = telephone;
  this.email = email;
 }
 public int getId() {
  return id;
 }
 public String getFirstName() {
  return firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public String getTelephone() {
  return telephone;
 }
 public String getEmail() {
  return email;
 }
 @Override
 public String toString() {
  return "Employee [Employee ID=" + id + ", FirstName=" + firstName
    + ", LastName=" + lastName + ",Telephone=" + telephone
    + ",Email=" + email + "]";
 }
}

2.2.HibernateUtility.java

package com.test.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtility {

 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();
  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);
  return sessionFactory;
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
2.3.SecondLevelCacheTest.java

package com.test.service;
import org.hibernate.Session;
import com.test.entity.Employee;
import com.test.util.HibernateUtility;
public class SecondLevelCacheTest {

 public static void main(String[] args) {
 
  Session session = HibernateUtility.getSessionFactory().openSession();
  session.beginTransaction();
  Employee employee = null;
  System.out.println("=============================================================");
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println("Employee details from the Database :: " + employee);
  System.out.println("=============================================================");
  System.out.println("Printing Employee details from First Level Cache");
  // Second time loading the same Employee entity from the first level cache
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println(employee);
  System.out.println("=============================================================");
  // Removing Employee object from the first level cache.
  session.evict(employee);
  System.out.println("Object removed from the First Level Cache");
  System.out.println("=============================================================");
 
  System.out.println("Printing Employee details from Second level Cache");
  employee = (Employee) session.load(Employee.class, 1);
  System.out.println(employee);
  session.getTransaction().commit();
  System.out.println("=============================================================");
  // Loading object in another session
  Session session2 = HibernateUtility.getSessionFactory().openSession();
  session2.beginTransaction();
  System.out.println();
  System.out.println("Printing Employee details from Second level Cache in another session");
  employee = (Employee) session2.load(Employee.class, 1);
  System.out.println(employee);
  session2.getTransaction().commit();
 }
}
3.ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <diskStore path="D:/tmp" />
 <defaultCache maxEntriesLocalHeap="4000" eternal="false"
  timeToIdleSeconds="60" timeToLiveSeconds="120" diskSpoolBufferSizeMB="20"
  maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
  memoryStoreEvictionPolicy="LRU" statistics="true">
  <persistence strategy="localTempSwap" />
 </defaultCache>
 <cache name="employee" maxEntriesLocalHeap="4000" eternal="false"
  timeToIdleSeconds="5" timeToLiveSeconds="10">
  <persistence strategy="localTempSwap" />
 </cache>
 <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
  maxEntriesLocalHeap="5000" eternal="true">
  <persistence strategy="localTempSwap" />
 </cache>
</ehcache>

4.hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
<hibernate-configuration>

 <session-factory>

  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/nadhu</property>
  <property name="connection.username">root</property>
  <property name="connection.password">knmuni</property>
  <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  <!-- Enable Second Level Cache -->
  <property name="hibernate.cache.use_second_level_cache">true</property>
  <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
  <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
  <mapping class="com.test.entity.Employee" />
 </session-factory>

</hibernate-configuration>

5.pom.xml

<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"&gt;
 <modelVersion>4.0.0</modelVersion>
 <groupId>Hibernate-SecondLevelCache-Demo</groupId>
 <artifactId>Hibernate-SecondLevelCache-Demo</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>Hibernate-SecondLevelCache-Demo</name>
 <dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>
  <!-- EhCache Core APIs -->
  <dependency>
   <groupId>net.sf.ehcache</groupId>
   <artifactId>ehcache-core</artifactId>
   <version>2.6.9</version>
  </dependency>
  <!-- Hibernate Integration EhCache API -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-ehcache</artifactId>
   <version>4.3.5.Final</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

6. Output

INFO: HHH000126: Indexes: [primary]
Apr 21, 2016 6:18:41 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
 
=============================================================

Hibernate:

select

employee0_.id as id1_0_0_,

employee0_.email as email2_0_0_,

employee0_.firstname as firstnam3_0_0_,

employee0_.lastname as lastname4_0_0_,

employee0_.telephone as telephon5_0_0_

from

employee employee0_

where

employee0_.id=?

Employee details from the Database :: Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Printing Employee details from First Level Cache

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Object removed from the First Level Cache

=============================================================

Printing Employee details from Second level Cache

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]

=============================================================

Printing Employee details from Second level Cache in another session

Employee [Employee ID=1, FirstName=Jon, LastName=Stephens,Telephone=0000000003,Email=jon.s@abc.com]


 Thank you ! :)