Uncategorized

Linked List with O(1) Insertion Complexity

A simple linked list program where insertion complexity is O(1) order of one i.e independent of data size.

Here is the code for the same

Here is the Node/Element/Data object of linked list

Note: This program has been written with minimum code so that users can copy and experiment with it. This is not a full fledged program, hence not recommended for production use.


public class Node {

Node previous;
T element;
Node next;

public Node(Node previous, T element, Node next) {
this.previous=previous;
this.element=element;
this.next=next;

}

@Override
public String toString() {
return “Node [element=” + element + “]”;
}

}


And here is the linked list implementation,

package java8pract.linkedlist_custom;
/**
* An implementation of linked list. Entire linked list is dependent on first element in the list.
*/
import java.util.ArrayList;
import java.util.List;

public class CustomLinkedList {

Node firstNode;
Node tempNode;
Node lastNode;
/**
* Add an element to the linked list
* +/—————————————-
* + 1. if first node is null, create a node and assign it to first node.
* + 2. and assign the newly created node to a temp Node;
* + 3. for consecutive additions, get the temp node into a middle methods level node
* + 4. Create new node and assign previous node as middle node.
* + 5.update the last node.
* + 6. middle node.next to newly created node
* + 7. and update temp node with newly created node.
* @param element
*/

public void add(T element) {
Node node = null;
if (null == firstNode) {
node = new Node(null, element, null);
firstNode = node;

} else {
Node middleNode = tempNode;
node = new Node(middleNode, element, null);
lastNode = node;
middleNode.next = node;

}
tempNode = node;
}

/**
* Get all the elements in linked list
*
* @return
*/
public List getAll() {
List list = new ArrayList();
Node temp = firstNode;
while (temp != null) {
list.add(temp);
System.out.println(temp.element);
temp = temp.next;

}
return list;
}

/**
* Get all the elements in the linked list in reverse order.
*
* @return
*/
public List getAllReverse() {
List list = new ArrayList();
Node temp = lastNode;
while (temp != null) {
list.add(temp);
System.out.println(temp.element);
temp = temp.previous;

}
return list;

}

public Node get(T t) {

Node temp = firstNode;
while (temp != null) {

if (temp.element !=null && temp.element.compareTo(t)==0) {
break;
} else {
temp = temp.next;
}
}

return temp;

}
/**
* Get the first node (HEAD) in the linked list
* @return
*/
public Node getFirstNode(){
return firstNode;
}
/**
* Get the last node in the linked list.
* @return
*/
public Node getLastNode(){
return lastNode;
}


}

Uncategorized

Easiest way to create MongoDB Cluster in MacOS

An easiest way to create mongodb cluster in MacOs environment.

These steps can be executed one after the other in Mac Terminal.
Note: Make sure that the folders paths are correct before running these commands.

Create Initial directories required for mongo db cluter

cd /Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data

mkdir replica1 replica2 replica3 replica4 replica5 replica6 replica7 replica8 replica9 config1 config2 config3

Sudo chmod –R 777 repl*

Sudo chmod –R 777 conf*

shard1

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica1 –port=27011 –bind_ip_all –replSet=replica1 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica2 –port=27012 –bind_ip_all –replSet=replica1 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica3 –port=27013 –bind_ip_all –replSet=replica1 –shardsvr

rs.initiate({_id:”replica1″,members:[{“_id”:1,”host”:”localhost:27011″}]})

rs.add(“localhost:27012”)

rs.add(“localhost:27013”)

shard2

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica4 –port=27021 –bind_ip_all –replSet=replica2 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica5 –port=27022 –bind_ip_all –replSet=replica2 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica6 –port=27023 –bind_ip_all –replSet=replica2 –shardsvr

rs.initiate({_id:”replica2″,members:[{“_id”:1,”host”:”localhost:27021″}]})

rs.add(“localhost:27022”)

rs.add(“localhost:27023”)

Shard 3

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica7 –port=27031 –bind_ip_all –replSet=replica3 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica8 –port=27032 –bind_ip_all –replSet=replica3 –shardsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/replica9 –port=27033 –bind_ip_all –replSet=replica3 –shardsvr

rs.initiate({_id:”replica3″,members:[{“_id”:1,”host”:”localhost:27031″}]})

rs.add(“localhost:27032”)

rs.add(“localhost:27033”)

config

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/config1 –port=27018 –bind_ip_all –replSet=config1 –configsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/config2 –port=27019 –bind_ip_all –replSet=config1 –configsvr

./mongod –dbpath=/Users/prabhu/Documents/softwares/mongodb-osx-x86_64-4.0.6/bin/data/config3 –port=27020 –bind_ip_all –replSet=config1 –configsvr

rs.initiate({_id:”config1″,members:[{“_id”:1,”host”:”localhost:27018″}]})

rs.add(“localhost:27019”)

rs.add(“localhost:27020”)

Start Mongos with config cluster
./mongos –configdb=”config1/localhost:27018,localhost:27019,localhost:27020″ –port=27017 –bind_ip_all

Connect to Mongos Server
./mongod –port 27017

sh.addShard(“replica1/localhost27011”)

sh.addShard(“replica2/localhost27021”)

sh.addShard(“replica3/localhost27031”)

sharding Collection

sh.enableSharding(“shoppingdb”); // enable sharding for db

sh.shardCollection(“shoppingdb.Orders”,{_id:1},true); // shard the collection

Uncategorized

DDD, Event Driven and CQRS example

There are lot of articles which talks about domain driven design, Event Driven and CQRS architectural practices. However,In this blog post, an effort to put domain driven design (DDD), Event Driven and Command Query Responsibility Segregation in a simple application which will explain all of above concepts. This application has been developed using spring boot, axon ,axon db server, java programming language, maven for build and eclipse etc.
In this application we are just trying to create an order with some order items (Command) and retrieve the same (Query) using order id. This is a very common scenario in any e commerce application and also a good example to explain above concepts.
Here is the out line of flow,

DDD,EVENT DRIVE, CQRS exampl

And here is the git hub url for code

https://github.com/prabhukvn/axon-springboot-poc.git

Uncategorized

Arrays Are Efficient in Java

Here is en example where iterating over an array is much faster than iterating over a list directly. This we can apply if we have to iterate a list over multiple time in a single thread.

private static void checkArrayList() {
ArrayList listOne = new ArrayList();

long startTime = System.nanoTime();
for (int i = 0; i <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;">&#65279;</span>&lt; 1000; i++) {
listOne.add(i);
}
// Total time taken to construct an array list with 1000 elements
System.out.println(&quot;Total Time 1:&quot; + (System.nanoTime() - startTime));

// Iterate entire list
startTime = System.nanoTime();
for (int k : listOne) {

}
// total time to iterate over 1000 elements
System.out.println(&quot;Total Time 2:&quot; + (System.nanoTime() - startTime));

Integer a[] = new Integer[1000];
// Convert list into array
startTime = System.nanoTime();
listOne.toArray(a);
// time to convert list into array
System.out.println(&quot;Total Time 3:&quot; + (System.nanoTime() - startTime));
// Iterate entire array
startTime = System.nanoTime();
for (int k : a) {

}
// total time taken to iterate over array
System.out.println(&quot;Total Time 4:&quot; + (System.nanoTime() - startTime));
}
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