Uncategorized

Closure in Java

A closure is an inner function that has access to the outer function even after the scope of outer function.This is a common programming concept in JavaScript, but we can achieve the same thing in java with the advent of JDK8 and functional programming.

here is a small java program which explains the closure concept in java,

/**
 * This program explains the closure in java. This is achieved by using functional programming in JDK 8.
 */
package lambdas;

/**
 * @author prabhu kvn
 *
 */
public class LambdaClosureConcept {

	public LambdaClosureConcept() {
	}

	public static void main(String[] args) {
		LambdaClosureConcept obj = new LambdaClosureConcept();
		obj.execute();
	}

	private void execute() {
		LambdaClosure fn = getFunction();
		System.out.println(fn.changeVal(10));

	}

	/**
	 * The "local" variable which got trapped in closure function.
	 * 
	 * @return
	 */
	private LambdaClosure getFunction() {
		int local = 89;
		LambdaClosure fn = (int i) -> {
			return i * local;
		};

		return fn;

	}

}

// Functional interface
@FunctionalInterface
interface LambdaClosure {

	int changeVal(int i);
}
Uncategorized

Auto Deploy Or Hot Deploy of JSP’s in JBOSS EAP 6.1

Jboss EAP 6.1 is not by default detect or deploy latest changes to JSP pages at runtime.

We need to place following settings in order to enable auto deployment or hot deployment of JSP pages.

Add following settings in standalone/configurations/standalone.xml file or In your server specific config file.

    <subsystem xmlns="urn:jboss:domain:web:1.4" default-virtual-server="default-host" native="false">
            <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
            <configuration>
                <jsp-configuration development="true"/>
            </configuration>
            <virtual-server name="default-host" enable-welcome-root="true">
                <alias name="localhost"/>
                <alias name="example.com"/>
            </virtual-server>
        </subsystem>        

            
Uncategorized

Thymeleaf Integration With Spring

Integrating thymeleaf with Spring framework
Note: This is intended for advanced programmers who already knows the spring,Maven, thymeleaf basics.

Thymeleaf will provide view templates for spring web applications like JSP’s.

1. Thymeleaf dependencies configuration
Add following dependencies in pom.xml


<dependency >
      <groupId> org.thymeleaf</groupId >
      <artifactId> thymeleaf</artifactId >
      <version> ${thymeleaf.version}</version >
      <scope> compile</scope >
    </dependency>
    <dependency>
      <groupId> org.thymeleaf</groupId >
      <artifactId> thymeleaf-spring3 </artifactId>
      <version> ${thymeleaf.version}</version >
      <scope> compile</scope >
    </dependency>



2. Configure following belans spring applicationContext.xml file. The view resolver will handle all the view request.

 <bean id="templateResolver"
        class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <!-- Template cache is true by default. Set to false if you want -->
    <!-- templates to be automatically updated when modified.        -->
    <property name="cacheable" value="true" />
  </bean>

  <bean id="templateEngine"
        class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
  </bean>

  <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
  </bean>

3. write the template pages to for displaying in web site.

Uncategorized

Thymeleaf Templating Engine for Web Application Views

Thymeleaf is a templating Engine, which will processes views which are in the form of HTML5/XHTML etc. These view templates will be parsed, cached, cloned and processes for each request. As it cached the templates, it will reduce lot of I/O operation time while displaying pages.
Note: Thymeleaf template engine will construct in memory DOM objects, hence we should avoid larger page templates.

Some of the features of thymeleaf…

1. Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications.
2. Thymeleaf is a template engine framework, which will apply set of processors+data on a template and produce the web pages.
3. Processors + set of artifacts are called dialect in thymeleaf.
4. http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html
5. The minimum goal of the thymeleaf is to provide an elegant and well – formed way of creating templates.
6. Its architecture allows fast processing of templates, relying on intelligent caching of parsed files which will reduce I/O operations.
7. Thymeleaf processing engine constructs the DOM objects from view templates.
8. These DOM objects will be cached in memory. Each time this DOM object will be cloned and processed to display the view. This will reduce IO operation time.

9. Anything that can be modeled as a DOM tree could effectively be processed as a template in thymeleaf.
10. Thymeleaf is an extremely extensible template engine (in fact it should be better called a template engine framework) that
allows you to completely define the DOM nodes that will be processed in your templates and also how they will be processed.
An object that applies some logic to a DOM node is called a processor, and a set of these processors –plus some extra
artifacts– is called a dialect.
11. Natural Template is possible in thymeleaf. where designer and developer will use same template without modifying.
12. all the request, session and application level variables will be accessed in OGNL style.
13. Supports internationalization of the application, where locale specific messages will be externalized to property files.

As of now Thymeleaf supports following formats,
XML
Valid XML
XHTML
Valid XHTML
HTML5
Legacy HTML5

Highlevel view of thymeleaf processing
Construct in memory DOM structure from templates –> traverse each template Node –> apply processors on each Node (Even attribute/business Data to display) –> and produce final page.

How thymeleaf works in a simple web application

1. A servlet filter to direct all requests to the thymeleaf
ex: MyAppFilter
2. MyAppFilter will create thymeleaf resolver and template engine.

* thymeleaf resolver

ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setTemplateMode("XHTML");
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");

* create template engine

templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);

* Even a messages resolver can be attached to thymeleaf to solve internationalization messages apart from out-of-the-box message resolver.
* And MyAppFilter will delegate each request to appropriate conroller


Controller controller = Application.resolveControllerForRequest(request);
            if (controller == null) {
                return false;
            }

            /*
             * Obtain the TemplateEngine instance.
             */
            TemplateEngine templateEngine = Application.getTemplateEngine();

            /*
             * Write the response headers
             */
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            /*
             * Execute the controller and process view template,
             * writing the results to the response writer. 
             */
            controller.process(
                    request, response, this.servletContext, templateEngine);

Controller for path =”/” –> HomeController.java

 public class HomeController implements IGTVGController {

    
    public HomeController() {
        super();
    }
    
    
    public void process(
            final HttpServletRequest request, final HttpServletResponse response,
            final ServletContext servletContext, final TemplateEngine templateEngine) 
            throws Exception {
        
        WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
        ctx.setVariable("today", Calendar.getInstance());
        
        templateEngine.process("home", ctx, response.getWriter());
        
    }

}

Note: Detailed code can be found at http://www.thymeleaf.org/doc/html/Using-Thymeleaf.html

Uncategorized

jmx jstatd remote debug configuration in JVM

To start the jstatd daemon, follow these steps:

Note : Close all the java based applications before starting jstatd.

Create a permissions policy (for example, jstatd.all.policy) that contains the following contents:

grant codebase "file:${java.home}/../lib/tools.jar" { permission java.security.AllPermission; };

Start the jstatd daemon, and specify the policy file and the port that you want to use. The daemon is found in the Java Development Kit (JDK) bin directory. Note: The location for that directory depends on the operating environment.
For UNIX operating environments, specify the following:

JAVA_HOME/bin/jstatd -p 1199 -J-Djava.security.policy=jstatd.all.

For Windows operating environments, specify the following:

JAVA_HOME\bin\jstatd -p 1199 -J-Djava.security.policy=jstatd.all.policy

Remote Monitoring via JMX

To monitor a Java virtual machine (JVM) via JMX, follow these steps:

Add the following arguments to the target JVM:

-Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=4090

Restart the JVM so that the new arguments take effect.
Verify that the JMX port (4090 in this example) is open and listening. Once you verify that the port is open and listening, you can connect to the port for remote monitoring.

Uncategorized

Datasource Configuration In Jboss 7

Follow the below steps to add datasource in jboss 7

1. edit standalone.xml to add datasource in subsystem

Note: standalone.xml location jboss-as-7.1.1.Final/standalone/configuration

 <datasource jndi-name="java:/jdbc/mydatasource" pool-name="mydatasource" enabled="true" use-java-context="true">
                    <connection-url>jdbc:mysql://localhost:3306/mydb</connection-url>
                    <driver>mysql</driver>
                    <security>
                        <user-name>root</user-name>
                        <password></password>
                    </security>
                </datasource>

2. Add the MySql Driver in the same place

 <driver name="mysql" module="com.mysql.jdbc">
                        <driver-class>com.mysql.jdbc.Driver</driver-class>
                    </driver>

3. Create following folder structure in jboss module directory.

jboss-as-7.1.1.Final/modules/com/mysql/jdbc/main

4. create module.xml file with following entry

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.0" name="com.mysql.jdbc">
    <resources>
        <resource-root path="mysql-connector-java-5.1.21.jar"/>
        <!-- Insert resources here -->
    </resources>
    <dependencies>
        <module name="javax.api"/>
        <module name="javax.transaction.api"/>
    </dependencies>
</module>

5. add mysql connector jars. finally main folder should contain below files

module.xml
mysql-connector-java-5.1.21.jar.index
mysql-connector-java-5.1.21.jar

Uncategorized

Jboss Deployment Time Out Increase

Some of the web applications will take longer time to deploy than expected. By default JBoss has only 60 seconds deployment time out.

To Increase the JBoss time, set the following configuration value in standalone.xml in jboss 7. Deployment time out will be in milliseconds.

<subsystem xmlns=”urn:jboss:domain:deployment-scanner:1.1″>
<deployment-scanner path=”deployments” relative-to=”jboss.server.base.dir” scan-interval=”5000″ deployment-timeout=”3000″/>
</subsystem>

 

Uncategorized

Simple Java Project in eclipse using Maven

Follow below steps to create simple java project using maven.

  Download the latest eclipse

2.       Install maven from eclipse market place if it not available in eclipse.

 Maven Installation

3.       Create new Maven project using Maven wizard

Selct Maven Wizard

4.       Select quickstart archetype.

Quick Start

5.       Name the project and click finish

Name Maven Artifacts

6.       Done. Check the eclipse for newly created project.

Uncategorized

QuickStart Infinispan Cache

Infinispan is an easy to configure caching mechanism for java based applications. It can be used as  stand alone and cluster modes. It can be run in a server as well  as a simple java process.  The following content will describe using infinispan as a java process. And all the dependencies will be packed as a jar file to start the cache with the help of maven.

Prerequisites: 1. Download maven and set the path in system environment variables. 2. internet connection

Use below command to create a new java project using maven

mvn archetype:generate -DgroupId=com.infinispan -DartifactId=infinispan -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

1. Create a maven simple project with following settings

<groupId>com.infinispan</groupId>
    <artifactId>infinispan</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>infinispan</name>

Simple Java Project Using Eclipse and Maven

2. Add following dependencies in pom.xml

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<infinispan-version>5.3.0.Final</infinispan-version>
</properties>

<dependencies>
<!– Infinispan Dependencies –>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-core</artifactId>
<version>5.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-client-hotrod</artifactId>
<version>5.3.0.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.infinispan.StartCache</mainClass>
<packageName>com.infinispan</packageName>
</manifest>
<manifestEntries>
<mode>development</mode>
<url>${project.url}</url>
</manifestEntries>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>

</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.infinispan.StartCache</mainClass>
<packageName>com.infinispan</packageName>
</manifest>
<manifestEntries>
<mode>development</mode>
<url>${project.url}</url>
</manifestEntries>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>

3. Write a java class to start infinispan cache container

// Get the Cache Container
EmbeddedCacheManager cacheManager = new DefaultCacheManager(
“app-infinispan.xml”);
// Get the Cache Store.
Cache<Object, Object> generalStore = cacheManager
.getCache(“generalStore”);
// Put into cache store.
generalStore.put(“email”, “me@mymail.com”);
// retrieve from cache store.
System.out.println(“Fetched fromCache:” + generalStore.get(“email”)+” Cache Size:”+generalStore.size());

System.exit(0);

4. Go to the project base folder and build the project by maven command

> mvn clean compile assembly:assembly

5. Go to BaseDirectory/infinispan/target folder and run the jar as below,

> java -jar infinispan-0.0.1-SNAPSHOT-jar-with-dependencies.jar

this will start infinisapn cache container in the a java process.

6. To start cluster environment, run the above jar file from multiple command prompts.

Infinispan automatically discover and form the cluster with all cache containers.

7. Use the infinispan client to put and get the objects.

// Get the Cache Container
EmbeddedCacheManager cacheManager = new DefaultCacheManager(
“app-infinispan.xml”);
// Get the Cache Store.
Cache<Object, Object> generalStore = cacheManager
.getCache(“generalStore”);
// Put into cache store.
generalStore.put(“email”, “me@mymail.com”);
// retrieve from cache store.
System.out.println(“Fetched fromCache:” + generalStore.get(“email”)+” Cache Size:”+generalStore.size());

System.exit(0);

For an easy start, import the project into eclipse and use the code.

Download Project

For more information on infinispan, visit http://infinispan.org/

Uncategorized

Java Threads for Browser Hits

The following java program will open an URL repeatedly through a browser.

How it works?

1. Creates a constant thread pool of size 10.

2. 15 tasks will be created and handed over to executor service to execute these task.

3. all ten thread will be used to execute 15 tasks.

4. And shut down the thread service once all thread stop execution.

a. main class for execution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* @author kvn prabhu
*
*/

/**
*
* This class will repeatedly open a URL in the browser and will close after
* 5000ms.
*
*/
public class OpenBrowser {

static int size = 0;

public static void main(String[] args) {

openBrowser();
}

/**
* 1.This method will create a Thread Pool of 10 threads. 2. 15 workers will
* be created and handled over to execute service to run the threads.
*/
private static void openBrowser() {
// Thread Pool with 10 threads.
ExecutorService service = Executors.newFixedThreadPool(10);
// create the workers and hand over to thread service.
for (int i = 0; i < 15; i++) {

BrowserWorker worker = new BrowserWorker();
service.execute(worker);
}
// shut down the pool once all thread completed execution.
service.shutdown();
// Print all running threads at any given time.
while (!service.isTerminated()) {

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

if (size != threadSet.size()) {

System.out.println(“All Running Threads:” + threadSet);
size = threadSet.size();
}

}

// Print after service termination.
while (service.isTerminated()) {
System.out.println(“Execution Completed.”);
break;
}

}

/**
*
*/

}

b. worker thread for executing a task.

/**
* This class will open 10 browsers on each run.
*
* @author kvn
*
*/
class BrowserWorker implements Runnable {

public void run() {

fire();

}

public void fire() {
for (int i = 0; i < 10; i++) {
try {
Process process = Runtime
.getRuntime()
.exec(“C:\\Program Files\\Internet Explorer\\iexplore.exe \”http://www.youtube.com/watch?v=V5Qk6oRsNmw&feature=youtu.be\””);
Thread.sleep(10000);
process.destroy();
//    System.out.println(“Status:” + process.waitFor());
} catch (Exception e) {
}
}
}
}

Result:

Note: Use any text editor to unwrap the content.

All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-1,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-9,5,main], Thread[Attach Listener,5,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-3,5,main], Thread[pool-1-thread-4,5,main], Thread[pool-1-thread-5,5,main], Thread[pool-1-thread-2,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Finalizer,8,system], Thread[Reference Handler,10,system], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-1,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-9,5,main], Thread[Attach Listener,5,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-3,5,main], Thread[pool-1-thread-5,5,main], Thread[pool-1-thread-2,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Finalizer,8,system], Thread[Reference Handler,10,system], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-1,5,main], Thread[Signal Dispatcher,9,system], Thread[Attach Listener,5,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-3,5,main], Thread[pool-1-thread-5,5,main], Thread[pool-1-thread-2,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-1,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-3,5,main], Thread[pool-1-thread-2,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-7,5,main], Thread[pool-1-thread-1,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-3,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-6,5,main], Thread[pool-1-thread-7,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-3,5,main]]
All Running Threads:[Thread[pool-1-thread-10,5,main], Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-7,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-3,5,main]]
All Running Threads:[Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-7,5,main], Thread[Signal Dispatcher,9,system], Thread[pool-1-thread-3,5,main]]
All Running Threads:[Thread[Attach Listener,5,system], Thread[Finalizer,8,system], Thread[Reference Handler,10,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main], Thread[pool-1-thread-7,5,], Thread[Signal Dispatcher,9,system]]
All Running Threads:[Thread[Signal Dispatcher,9,system], Thread[Attach Listener,5,system], Thread[Reference Handler,10,system], Thread[Finalizer,8,system], Thread[main,5,main], Thread[pool-1-thread-8,5,main]]
Execution Completed.