Monday, November 25, 2019

Upload the Maven's artifacts to the Jfrog Artifactory

The below simple example shows how to upload the maven build artifacts to the Jfrog artifactory.

1. First download the Jfrog  OSS artifactory from https://jfrog.com/open-source/ link and download ZIP to your computer.

2. Unzip the file and run the artifactory.bat from the bin folder inside the application.

3. Once artifactory is run, then go to the browser and hit http://localhost:8080 or your customized port location

4. After the artifactory is up and running, create the artifact repository one for snapshots and one for releases. For example maven-releases for releases and maven-snapshots for snapshots repository.

5. In your maven project pom.xml put the distribution management as shown below

    <distributionManagement>
        <repository>
            <id>releases</id>
            <url>http://localhost:8080/artifactory/maven-releases</url>
            <name>maven-releases</name>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <url>http://localhost:8080/artifactory/maven-snapshots</url>
            <name>maven-snapshots</name>
        </snapshotRepository>
    </distributionManagement>

6. Now in the maven's setting ${MAVEN_HOME}/conf/settings.xml, set the credentials for the artifactory inside servers setting as:

    <server>
      <id>releases</id>
      <username>user</username>
      <password>pass</password>
    </server>

    <server>
      <id>snapshots</id>
      <username>user</username>
      <password>pass</password>
    </server>

7. Now in your maven project's root start the SNAPSHOT deployment using the command:

$ mvn clean package deploy

-this command will deploy the artifacts generated (usually the jars) to the maven-snapshots of the artifactory

8. To deploy the RELEASE we would need to do

$ mvn release:clean release:prepare release:perform

- for this to work, we would also need to hook up the source code repository in scm element in the pom.xml file as:

    <scm>
        <connection>scm:git:https://github.com/your-accountt/your-project.git</connection>
        <url>http://github.com/your-account/your-project</url>
        <developerConnection>scm:git:https://github.com/your-account/your-project.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

you can also connect to other source code repository instead of the git repository. The credential can also be provided same as for the artifactory in the maven's settings.xml file.

we would probably also need to add the following plugin inside the plugins in the pom.xml in-order to make this work

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-release-plugin</artifactId>
       <version>2.5.1</version>
        <configuration>
              <tagNameFormat>v@{project.version}</tagNameFormat>
              <autoVersionSubmodules>true</autoVersionSubmodules>
        </configuration>
</plugin>

9. If everything is OK, then the maven project should build, upload the artifacts to Artifactory's releases repository and update the source code in the scm repository.

10. We can also deploy to the Nexus Repository Manager OSS maven repository in the same way. Follow the link https://www.sonatype.com/download-oss-sonatype to download the Nexus Repository.

That's All!


Tuesday, November 12, 2019

How to SSH from one Docker Container to Other Docker Container


How to SSH from one Docker Container to Other Docker Container

I have tried to deploy the application that is build on one docker and push the final artifact to other docker container and came across the question of how to push to other docker. I searched a little bit and here is how I finally able to ssh to other docker container

Let's say we have two docker containers A and B running in the host environment and I want to do the SSH from docker A to docker B.

Here is the following things that I need in-order to do the SSH to docker B. Make sure both dockers are downloaded and running. Let say I have downloaded the nodejs docker and run as:

$docker run -it --rm -name A -p 50022:22 node /bin/bash
$docker run -it --rm -name B -p 50023:22 node /bin/bash

1. Find the docker container's ip address as below:

$docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' A
$172.17.0.1

$docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'  B
$172.17.0.2

2. Inside the docker container B
$ apt-get update
$ apt-get install ssh

3. Change the following configuration in /etc/ssh/sshd_config file
PasswordAuthentication from 'no' to 'yes'
PermitRootLogin from 'no' to 'yes'

4. Then run the ssh service inside container B as
$service ssh start

5. Change the root password as:
$passwd root
[Enter new password]: _


6. Now from docker container A just do the following:
$ssh root@172.17.0.2
[Enter the password]: _

That's all!


SSH without providing password using ssh keygen

If you want to ssh login without providing password, then following ssh key need to be generated

1. From docker container A, generate rsa key as:
$ssh-keygen -t rsa
the key will be generated by default at ~/.ssh/ folder

2. Upload or transfer the public key id_rsa.pub to container A at the location as given below:
$cat ~/.ssh/id_rsa.pub | ssh root@172.17.0.2 'cat >> ~/.ssh/authorized_keys'

3. It will as one time password to copy, after then
$ ssh root@172.17.0.2
and no password will be asked.

That's all!

Now we can even run the remote script using ssh as:
ssh root@172.17.0.2 << EOF
echo "this is from container B"
pwd
EOF

Thursday, February 28, 2019

JMeter JMS testing with IBM MQ server


Testing JMS with IBM MQ and JMeter


In order to send and receive message from IBM MQ server, you can use JMeter to test the message.  Follow the steps below to set up the JMeter to test the JMS message

1. Install latest Apache JMeter from https://jmeter.apache.org/download_jmeter.cgi


2. Copy following required IBM and other dependencies jars inside JMETER_HOME/lib/ext directory


- jmeter-jms-skip-jndi-0.0.1.jar

- com.ibm.mq.jar
- com.ibm.mqjms.jar
- connector.jar
- dhbcore.jar
- spring-core.jar
- spring-beans.jar
- javax.transaction-api.jar
- spring-jms.jar

3. Start JMeter -> create new Thread Group -> create JMS Point-to-Point from Add, Sampler


4. Add the following configuration information in the JMS Point-to-Point panel



Under JMS Properties add:

QueueConnectionFactory = CONNECTION_FACTORY
JNDI name Request queue = QUEUE_<your.request.queue.name>
JNDI name Receive queue = QUEUE_<your.response.queue.name>
Number of samples to aggregate = <1 or other value>
Communication style = <request_only/request_response>
Check both message correlation check box if needed


Initial Context Factory = <com.elega9t.jmeter.jms.InitialContextFactory>
 

Inside JNDI Properties add
hostName = <hostName>
port = <port>
channel = <channel>
queueManager = <queueManager>
transportType = 1


Inside Content text box = <your content to send to JMS>

 

JMS Point-to-Point configuration

View Result Tree and output response



Saturday, February 4, 2017

Simple Spark Streaming with Kafka in Docker

I have tried to use simple way of Data streaming in Spark from Kafka using Docker environment. For this test you would need Docker installed and has access to Internet.

1. First start the docker (I am using boot2docker in Windows environment) as:
$ docker-machine start default
$ docker-machine ssh default or ssh docker@localhost -p 23

2. Inside docker environment load the Spark docker images (for this example I have used sequenceiq/spark)
$ docker pull sequenceiq/spark

3. his will pull the latest docker images to your docker environment. Once pull is complete run the following command in docker
$ docker run -it -p 4040:4040 -p 2181:2181 -p 9092:9092 -v /<some_path_to_share>:/data sequenceiq/spark:1.6.0 /bin/bash

following this command the spark image console is appear.

4. Now download the Apache Kafka from (https://kafka.apache.org/downloads) page. Choose suitable kafka version. For this example purpose, I downloaded kafka_2.10-0.10.1.0.tgz for Scala version 2.10

5. Unzip the file as:
$ tar -xvf kafka_2.10-0.10.1.0.tgz
$ mv kafka_2.10-0.10.1.0 /usr/local/kafka
$ cd /usr/local/kafka/bin

5. Now after download and unpack and move to suitable folder, start zookeeper and kafka from bin folder as below:
$ ./zookeeper-server-start.sh /usr/local/kafka/config/zookeeper.properties
$ ./kafka-server-start.sh /usr/local/kafka/config/server.properties

6. After the zookeeper and kafka sucessfully started, create the topic for streaming as:
$ ./kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic spark-topic
- this will create topic

7. Next thing is to create the sample Spark application as:
import kafka.serializer.StringDecoder
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}

object KafkaReceiver {

  def main(args: Array[String]): Unit = {

    val conf = new SparkConf().setMaster("local[*]").setAppName("Kafka Receiver")

    val kafkaParams = Map("metadata.broker.list" -> "localhost:9092")

    val topics = List("spark-topic").toSet

    val ssc = new StreamingContext(conf, Seconds(5))

    val lines = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](ssc, kafkaParams, topics).map(_._2)

    println("printing Streaming data.......")

    lines.print()

    ssc.start()
    ssc.awaitTermination()
  }
}

8. Package this with required libraries as in build.sbt below

name := "SparkExample"

version := "1.0"

val sparkVersion = "1.6.0"

scalaVersion := "2.10.4"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion,
  "org.apache.spark" %% "spark-streaming" % sparkVersion,
  "org.apache.spark" %% "spark-streaming-kafka" % sparkVersion
)


9. Run the jar after packaging from spark-submit as:
$ spark-submit --master local[*] --class KafkaReceiver --packages org.apache.spark:spark-streaming-kafka_2.10:1.6.0 /sparkexample_2.10-1.0.jar

once it start running check the console

10. Finally run the kafka producer to produce the data for streaming as:
$ ./kafka-console-producer.sh --broker-list localhost:9092 --topic spark-topic
Hello Spark Streaming

In Spark console you will see something like:

17/02/04 21:55:50 INFO executor.Executor: Running task 0.0 in stage 11.0 (TID 11)
17/02/04 21:55:50 INFO kafka.KafkaRDD: Beginning offset 1000011 is the same as ending offset skipping spark-topic 0
17/02/04 21:55:50 INFO executor.Executor: Finished task 0.0 in stage 11.0 (TID 11). 915 bytes result sent to driver
17/02/04 21:55:50 INFO scheduler.TaskSetManager: Finished task 0.0 in stage 11.0 (TID 11) in 13 ms on localhost (1/1)
17/02/04 21:55:50 INFO scheduler.DAGScheduler: ResultStage 11 (print at KafkaReceiver.scala:27) finished in 0.012 s
17/02/04 21:55:50 INFO scheduler.DAGScheduler: Job 11 finished: print at KafkaReceiver.scala:27, took 0.063248 s
-------------------------------------------
Time: 1486263350000 ms
-------------------------------------------
Hello Spark Streaming

17/02/04 21:55:50 INFO scheduler.JobScheduler: Finished job streaming job 1486263350000 ms.0 from job set of time 1486263350000 ms
17/02/04 21:55:50 INFO scheduler.JobScheduler: Total delay: 0.115 s for time 1486263350000 ms (execution: 0.079 s)
17/02/04 21:55:50 INFO rdd.MapPartitionsRDD: Removing RDD 21 from persistence list
17/02/04 21:55:50 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 11.0, whose tasks have all completed, from pool
17/02/04 21:55:50 INFO storage.BlockManager: Removing RDD 21
17/02/04 21:55:50 INFO kafka.KafkaRDD: Removing RDD 20 from persistence list
17/02/04 21:55:50 INFO scheduler.ReceivedBlockTracker: Deleting batches ArrayBuffer()
17/02/04 21:55:50 INFO scheduler.InputInfoTracker: remove old batch metadata: 1486263340000 ms
17/02/04 21:55:50 INFO storage.BlockManager: Removing RDD 20




Wednesday, February 11, 2015

Simple Secure websocket backend server connection with Apache SSL Proxy

BROWSE <-----SSL connection-----> APACHE PROXY SERVER (SSL Enabled) <----Regular plain text----> TOMCAT WEB SOCKET SERVER

1. Enable following modules:
LoadModule ssl_module modules/mod_ssl
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so

2. Create self-signed digital certificate for testing as follow using openssl
> openssl genrsa -out server.key 2048 (generate private key)
> openssl req -new -key server.key -out server.csr (generate CSR)
> openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt (generate self-signed certificate from CSR)

and copy the crt and key file at: C:/Apache24/conf/ folder

3. Enable the httpd-ssl.conf in the httpd.conf file as:
Include conf/extra/httpd-ssl.conf

4. Open httpd-ssl.conf file and update the following (comment Listen 443 line if starting server gives error about the port already used by 443)
SSLCertificateFile "${SRVROOT}/conf/server.crt" and
SSLCertificateKeyFile "${SRVROOT}/conf/server.key"

5. Start the server using ./httpd.exe and see if there is any issue, if no issue then access the page using https://localhost, this will launch the secure page

6. Add the Proxy in the httpd.conf file for the Tomcat as:
ProxyRequests Off
ProxyPreserveHost On
ProxyPass /test http://tomcat-host-ip:8090/test
ProxyPassReverse /test http://tomcat-host-ip:8090/test

Here Tomcat is running at 8090 port and Proxy is set up as http, i.e. from apache to tomcat, the data is passes as plain text.

7. To automatically change the http to https when user access http, add following line in the httpd.conf file just above the ProxyPass set up as:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

and all set, run the Apache and Tomcat and access the Tomcat page from Apache as https://localhost/text. This will be Proxied to Tomcat as desired.

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

FOR TOMCAT AJP CONNECTOR

1. Enable tomcat AJP1.3 in server.xml in Tomcat's configuration directory
2. Load the module
mod_proxy and mod_proxy_ajp in httpd.conf file in Apache 2.4
3. Set the Proxy setup as:
ProxyPass /test ajp://tomcat-host-ip:8090/test
ProxyPassReverse /test ajp://tomcat-host-ip:8009/test

Simple unsecured Apache Proxy for Tomcat Web Socket Application

BROWSE <===> APACHE PROXY SERVER <===> TOMCAT WEB SOCKET SERVER

This is tested for the Apache Haus v 2.4.10 with Tomcat v 7 in the Windows development environment.

1. Install Apache Haus 2.4.10 in Windows Environment.
2. Install Tomcat 7 in the Windows Environment either in same machine or different machine.
3. To create websocket proxy for the Apache load following module by removing LoadModule comments in httpd.conf file:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so

For further, please refer Apache documentation at: http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html and add following ProxyPass setup in httpd.conf configuration file

ProxyRequests Off
# If tomcat is in same machine (for websocket)
ProxyPass /websocket/echo ws://localhost:8090/websocket/echo          -> look for the trailing "/"
ProxyPassReverse /websocket/echo ws://localhost:8090/websocket/echo             -> look for the trailing "/"

# For other http request
ProxyPass /test http://localhost:8090/test
ProxyPassReverse /test http://localhost:8090/test

# If Tomcat is in different/remote machine
ProxyPass /websocket/echo ws://remote-host:8090/websocket/echo
ProxyPassReverse /websocket/echo ws://remote-host:8090/websocket/echo

# For other http request
ProxyPass /test http://remote-host:8090/test
ProxyPassReverse /test http://remote-host:8090/test

This configuration assume that Apache use port 80 and Tomcat use port 8090 and servlet context deployed in tomcat /test. Now the http or ws call to Apache will automatically redirect to corresponding Tomcat Server once it find the Proxy setting. Also take special look at the trailing "/". If you add trailing "/" for /websocket/echo/, then you need to add trailing "/" for ws://localhost:8090/websocket/echo/ too or vice-versa.

Also the ProxyPass has to be set up in specific order (take a look at the Apache documentation for this).

Here is how someone in Stack Overflow did (very useful): http://stackoverflow.com/questions/17649241/reverse-proxy-with-websocket-mod-proxy-wstunnel

4. Create simple websocket application in Tomcat as:
@ServerEndpoint("/echo")
public class EchoWebSocket {
    private Logger logger = Logger.getLogger(this.getClass().getName());
    @OnOpen
    public void onOpen(Session session) {
        logger.info("Connected .... " + session.getId());
    }
    @OnMessage
    public String onMessage(String message, Session session) {
        switch (message) {
        case "quit":
            try {
                session.close(new CloseReason(CloseCodes.NORMAL_CLOSURE,
                        "Connection is closed."));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            break;
        }
        return message;
    }
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        logger.info(String.format("Session %s closed because of %s",
                session.getId(), closeReason));
    }
}

*Remember when deploying the Tomcat application, don't put websocket-api.jar library in the application classpath. Since this library is already included in the Tomcat library, adding this in application class-path may not work (At least for me it didn't work).

5. Add the JavaScripts HTML5 WebSocket API script as:

function wsocket() {
    var ws = null;
    var wsProtocol = (window.location.protocol === "https:" ? "wss" : "ws");
    var target =  wsProtocol + "://" + window.location.host + "/dwrdemo/echo";
    if ("WebSocket" in window) {
        ws = new WebSocket(target);
    } else if ("MozWebSocket" in window) {
        ws = new MozWebSocket(target);
    } else {
        alert('WebSocket is not supported by this browser.');
    }

    ws.onopen = function() {
        console.log("WebSocket has been opened!");
    };

    ws.onmessage = function(message) {
       console.log("WebSocket message is: " + message.data);
    };

    ws.onerror = function() {
        console.log("WebSocket connection has error!");
    }
   
    ws.onclose = function() {
        console.log("WebSocket is closed.");
    }
}


6. Add the Tomcat deployable war file in the Tomcat Server and test to make sure it is working. Once working access the page using the Apache web server.
7. The Request and response header for the websocket look something like as shown below if connection is established successfully

URL: http://localhost/websocket/echo

Request Headers:
    Accept    text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Encoding    gzip, deflate
    Accept-Language    en-US,en;q=0.5
    Cache-Control    no-cache
    Connection    keep-alive, Upgrade
    Cookie    JSESSIONID=3CD55817617CA29EF8F133721A1E1388
    Host    localhost
    Origin    http://localhost
    Pragma    no-cache
    Sec-WebSocket-Key    2cWlxhpbtE0dO1ijeaocaA==
    Sec-WebSocket-Version    13
    Upgrade    websocket
    User-Agent    Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

Response Headers:
    Cache-Control    private
    Connection    upgrade
    Date    Fri, 06 Feb 2015 15:15:01 GMT
    Expires    Wed, 31 Dec 1969 19:00:00 EST
    Sec-WebSocket-Accept    jMl5aXuuLM8xJ35XDGAY8uncIWk=
    Server    Apache-Coyote/1.1
    Upgrade    websocket

Take a look at the Connection Upgrate, the regular http request is updated to websocket for the websocket connection. This is how the websocket work by upgrading the current protocol in the initial handshake.

Testing using JConsole as:

var ws = new WebSocket("ws://localhost/websocket/echo");
ws.readyState

Tuesday, January 27, 2015

Mutual-Authentication with Client Self Signed Digital Certificate with Tomcat SSL Configuration

MUTUAL-AUTHENTICATION WITH CLIENT DIGITAL CERTIFICATE AND TOMCAT SSL CONFIGURATION (FOR DEV and TEST):

In Order to authenticate server and client certificate using mutual authentication in Tomcat SSL configuration, we need to create the pair of keys in server, client. The client certificate is then added to the server trustStore.
1. First generate the server-cert using keytool utility as:
> keytool -genkeypair -alias servercert -keyalg RSA -dname "CN=Your Server DNS,OU=ORG,O=COM,L=NYC,S=NY,C=US" -keypass <password> -keystore server.jks -storepass <password>

usually the keypass, and storepass is kept same. The above keytool command create the server.jks keystore with servercert as alias. The command creates server Private Key and other information and protect the Private key with the password supplied.
To view the content, type the command as:
> keytool -list -v -keystore server.jsk -storepass <password>

2. Next create client keypair as:
> keytool -genkeypair -alias clientStore -keystore clientStore.p12 -storetype pkcs12 -keyalg RSA -dname "CN=Your Client,OU=ORG,O=COM,L=NYC,S=NY,C=US" -keypass <password> -storepass <password>

This will also create the clientStore like the one in 1 with Private Key and certificate.

3. Now export the certificate that is created in keystore as in the step 2 using the command as:
> keytool -exportcert -alias clientStore -file clientStore.cer -keystore clientStore.p12 -storetype pkcs12 -storepass <password>

This command will export the client certificate clientStore.cer file and import this file to trustStore as given below:

4: importing the certificate to trustStore as:
> keytool -importcert -keystore server.jks -alias clientStore -file clientStore.cer -v -trustcacerts -noprompt -storepass <password>

5. Once you have imported the client certificate to the trustStore, you can view the content using the following command as:
> keytool -list -v -keystore server.jks -storepass <password>

6. Now the server-cert keystore can be dropped in the Tomcat {CATALINA_HOME}/config/ directory and enable the SSL authentication using the following Connector configuration:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
    maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
    clientAuth="true" sslProtocol="TLS" keystoreFile="{CATALINA_HOME}/config/server.jks" keystorePass="password"
    truststoreFile="{CATALINA_HOME}/config/server.jks" truststorePass="password" truststoreType="JKS"/>

For the server as well as client certification authentication use clientAuth="true" and required to add trustStoreFile, trustStorePass and trustStoreType. The trustStoreType is by default JKS.

7. Now download the clientStore.p12 file in the client end and install in the browser as client certificate. The certificate will as password, provider the password and it will be all set for the mutual SSL communication.
Now connect the secure page using https and if certificate exception occurs (which will be in Firefox, since this is self-signed certificate), add the exception and you should be able to go to the secure page.
This way the SSL connection established using Mutual Certificate Authentication. For production environment, the certificate need to be verified by CA (Certificate Authority).

8. To create more client certificates, repeat step 2, 3, and import to step 4. This way multiple client certificate can be created for multiple clients for client authentication.


For more information, refer following resources:
http://stackoverflow.com/questions/1180397/tomcat-server-client-self-signed-ssl-certificate
http://docs.oracle.com/middleware/1213/edq/DQSEC/ssl_tomcat.htm#DQSEC164
https://twoguysarguing.wordpress.com/2009/11/03/mutual-authentication-with-client-cert-tomcat-6-and-httpclient/
http://java-notes.com/index.php/two-way-ssl-on-tomcat
http://docs.geoserver.org/latest/en/user/security/tutorials/cert/index.html

Sunday, January 25, 2015

Apache Proxy for Tomcat

ADDING APACHE WEB SERVER AS PROXY FOR TOMCAT
1. Configure the copy of Apache so that it includes the mod_proxy module. In httpd.conf file enable these:
LoadModule proxy_module {path-to-module}/mod_proxy.so and
LoadModule proxy_http_module {path-to-module}/mod_proxy_http.so

2. Next Add Two Directives in the httpd.conf file for each web application that need to forward to the Tomcat as:
ProxyPass /myapp http://tomcat-ip:8081/myapp
ProxyPassReverse /myapp http://tomcat-ip:8081/myapp

More on: http://tomcat.apache.org.tomcat-6.0-doc/proxy-howto.html#Apache_2.0_Proxy_Support

Configuring SSL in Tomcat

CONFIGURE SIMPLE SSL USING TOMCAT
1. Create simple KeyStore file in your machine using following command:

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA
(default it stores in your \Users directory as .keystore file

OR

%JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA \
  -keystore \path\to\my\keystore
 
2. Once the keystore file is created, add the following line in your Tomcat Server.xml file as:
       
<!-- Define a SSL HTTP/1.1 Connector on port 8443
     This connector uses the BIO implementation that requires the JSSE
     style configuration. When using the APR/native implementation, the
     OpenSSL style configuration is required as described in the APR/native
     documentation -->

<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
        maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
        clientAuth="false" sslProtocol="TLS" keystoreFile="\path\to\my\keystore\.keystore" keystorePass="your_password"/>
       

3. Add Security setting in your application's web.xml file as:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>your_app_name</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

4. Access your app using https://localhost:8443/your_app_name
if you access using http://localhost:8080/your_app_name, it will redirect to https because of the web.xml configurations

5. For more information check the Apache Tomcat Document Page

URL REWRITING in TOMCAT

TOMCAT URL REWRITE USING URLREWRITEFILTER BY TUCKEY.ORG
In order to rewrite URL directly from the TOMCAT ROOT context:

1. Copy the urlrewritefilter-4.0.3.jar file to {TOMCAT_HOME}/lib folder

2. Add urlrewrite.xml file in the {TOMCAT_HOME}/webapps/ROOT/WEB-INF folder and write your own rule something like:

<urlrewrite>
    <rule>
        <from>^/([a-z]+)/some_app</from>
        <to type="redirect">/other_app/LoginServlet?param1=$1</to>
    </rule>
</urlrewrite>

3. If you are redirecting the url from your app, then add these line at the top of the web.xml file's Servlet mapping, for ROOT redirect, add these to ROOT/WEB-INF/web.xml file as:
<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

4. Now access the page using http://localhost:8090/abc/some_app, this will redirect the page to http://localhost:8090/other_app/LoginServlet?param1=abc

More information and tutorials on: http://www.tuckey.org/urlrewrite/

Friday, October 4, 2013

Lambda in Python (Map, Reduce and Filter)

Map, Reduce and Filter using Lambda in Python

1. Map
>>>map(lambda x:x*x, range(1,10))
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Reduce
>>>reduce(lambda x,y: x+y, range(1,10))
>>>45

3. Filter
>>>filter(lambda x: x % 2 != 0, range(1,20))
>>>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

ex1: Add sum of all even number from 1 to 20
>>>reduce(lambda x,y: x+y, filter(lambda x: x % 2 == 0, range(1,20)))
>>>90

ex2: lambda as return function
>>>g = lambda x: x**2
>>>print g(2)
>>>4

ex3: like partial function
>>>def increament(n):
>>>    return lambda x: x + n
>>>f = increment(10)
>>>print f(6)
>>>16
or
>>>print increament(6)(10)
>>>16

ex4: prime numbers between 1-100
>>>nums = range(2,100)
>>>for i in range(2,8):
>>>    nums = filter(lambda x: x == i or x % i, nums)
>>>print nums
>>>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

ex5: Letter count
>>>print map(lambda w: len(w), 'It has been raining since this morning'.split())
>>>[2, 3, 4, 7, 5, 4, 7]

ex6: Functional Style of adding
>>> from operator import add
>>> expr = "28+32+++32++39"
>>> print reduce(add, map(int, filter(bool, expr.split("+"))))
>>> 131

Wednesday, September 4, 2013

Creating Simple 'Hello World' Django web application

Creating Simple Hello World Django/python web application

# Download the Django from: https://www.djangoproject.com/download/

# untar the application tar
$ tar xvf Django-1.5.2.tar

$ cd Django-1.5.2

# Setup django
$ python setup.py install
- this will install django web framework

# Create the new site using following command
$ django-admin.py startproject mysite
- after you run this command, it will create the following folder structure
- mysite
--- manage.py
--- mysite
------ urls.py
------ __init__.py
------ wsgi.py
------ settings.py
------ views.py (add new file as shown below)

# Create new python file in mysite/ directory as views.py and add following line
#!/usr/bin/python
from django.http import HttpResponse
def hello(request):
    html = "<html><body><b>Hello World!</b></body></html>"
    return HttpResponse(html)

# Update the urls.py file in mysite/ directory as
#!/usr/bin/python
from django.conf.urls import patterns, include, url
from mysite.views import hello
urlpatterns = patterns('',
    url(r'^$', hello),
)

# Finally from inside mysite/ directory run this command
$ python manage.py runserver

# Open the browser and type this url http://localhost:8000

Friday, August 23, 2013

Hot Deployment/Republishing the JSF Facelet in Tomcat/Eclipse Environment

Today I was trying to update/republish the JSF pages without redeploying in the tomcat server again and again but couldn't get success.

After few minutes of google, I figured what was the issue. In my web application web.xml file, the FACELETS_REFRES_PERIOD is set as -1 as:

    <context-param>
      <param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
      <param-value>-1</param-value>
    </context-param>

I changed it to '1' and also changed
    <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Production</param-value>
    </context-param>



to

    <context-param>
      <param-name>javax.faces.PROJECT_STAGE</param-name>
      <param-value>Development</param-value>
    </context-param>

and VOILA! it worked and I am happy. Now I can change the static resources without module redeploy.




Tuesday, August 20, 2013

Configure ssh login information in config file

How to configure the ssh login information in Config file

Usually we connect the remote host using ssh by giving following command in terminal

$ssh -i filename.pem user@ipaddress 

(if there is the pem file for the security key)

Or

$ssh user@ipaddress

Instead of doing this we can add these information in Config file and just type in

$ssh <host>

The config file reside in .ssh/ folder as .ssh/config and add the following:
Host <HostName/AnyName>
HostName <ipaddress>
User <username>
IdentityFile <if there are any pem file> (Optional)

eg:
Host MyHost
HostName 192.168.1.101
User user

Thursday, March 14, 2013

Setting tomcat server in debug mode

To set up tomcat server in debug mode add the following line in the VM argument

Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

In eclipse configuration you can add the Edit configuration window as shown below:



Setting Maximum Perm Size for JVM

Maximun Perm Memory is the memory where most of the classes and class loader reside. To adjust or increment the maximum perm gen size, just add the following line as VM arguments when starting server.

XX:MaxPermSize=256m

Where 256 is the memory MB, you can adjust this value as per your application requirement.

Sunday, July 15, 2012

Reading file in Java

Following is an example how to read the file and display using System.out.println()

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileReader {
    public static void main(String[] args) {
        String file = "C:\\Users\\test.csv";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            while (reader.readLine() != null) {
                System.out.println(reader.readLine());
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Upload File using JSF 2.0 and Richfaces

Given below is a simple application how we can upload file using JSF 2.0. The example contain three files
1. The main FileUploadController which has much of the funtionalities for uploading saving files
2. The UploadedText is the bean containing information about the file and
3. The upload.xhtml JSF page.
First Create FileUploadController
1:  import java.io.File;  
2:  import java.io.FileOutputStream;  
3:  import java.io.IOException;  
4:  import java.io.OutputStream;  
5:  import java.io.Serializable;  
6:  import java.util.ArrayList;  
7:  import org.apache.log4j.Logger;  
8:  import org.richfaces.event.FileUploadEvent;  
9:  import org.richfaces.model.UploadedFile;  
10:  import org.springframework.context.annotation.Scope;  
11:  import org.springframework.stereotype.Component;  
12:  import com.jsf.app.client.vo.UploadedText;  
13:  // spring managed bean  
14:  @Component("fileUploadController")  
15:  @Scope("session")  
16:  public class FileUploadController implements Serializable {  
17:       private static final long serialVersionUID = -4664762090820133359L;  
18:       private static final Logger logger = Logger.getLogger(FileUploadBean.class  
19:                 .getName());  
20:       private static final String fPath = "C:\\Users\\";  
21:       private ArrayList<UploadedText> files = new ArrayList<UploadedText>();  
22:       public void paint(OutputStream stream, Object object) throws IOException {  
23:            stream.write(getFiles().get((Integer) object).getData());  
24:            stream.close();  
25:       }  
26:       public void listener(FileUploadEvent event) throws Exception {  
27:            UploadedFile item = event.getUploadedFile();  
28:            UploadedText file = new UploadedText();  
29:            file.setLength(item.getData().length);  
30:            file.setName(item.getName());  
31:            file.setData(item.getData());  
32:            files.add(file);  
33:       }  
34:       public String clearUploadData() {  
35:            files.clear();  
36:            return null;  
37:       }  
38:       public int getSize() {  
39:            if (getFiles().size() > 0) {  
40:                 return getFiles().size();  
41:            } else {  
42:                 return 0;  
43:            }  
44:       }  
45:       public long getTimeStamp() {  
46:            return System.currentTimeMillis();  
47:       }  
48:       public ArrayList<UploadedText> getFiles() {  
49:            return files;  
50:       }  
51:       public void setFiles(ArrayList<UploadedText> files) {  
52:            this.files = files;  
53:       }  
54:       public void writeFile() {  
55:            FileOutputStream fop = null;  
56:            File file;  
57:            UploadedText contain = files.size() > 0 ? files.get(0) : null;  
58:            if (contain == null) {  
59:                 return;  
60:            }  
61:            try {  
62:                 file = new File(fPath + contain.getName());  
63:                 fop = new FileOutputStream(file);  
64:                 if (!file.exists()) {  
65:                      file.createNewFile();  
66:                 }  
67:                 fop.write(contain.getData());  
68:                 fop.flush();  
69:                 fop.close();  
70:                 if (logger.isDebugEnabled()) {  
71:                      logger.debug("File Creation Completed Successfuly.");  
72:                 }  
73:            } catch (IOException e) {  
74:                 e.printStackTrace();  
75:            } finally {  
76:                 try {  
77:                      if (fop != null) {  
78:                           fop.close();  
79:                      }  
80:                 } catch (IOException e) {  
81:                      e.printStackTrace();  
82:                 }  
83:            }  
84:       }  
85:  }  

Next Create the UploadText file:
1:  import java.io.Serializable;  
2:  public class UploadedText implements Serializable {  
3:       private static final long serialVersionUID = -3957467715082208719L;  
4:       private String name;  
5:       private String mime;  
6:       private long length;  
7:       private byte[] data;  
8:       public String getName() {  
9:            return name;  
10:       }  
11:       public void setName(String name) {  
12:            int extDot = name.lastIndexOf('.');  
13:            if (extDot > 0) {  
14:                 String extension = name.substring(extDot + 1);  
15:                 if ("txt".equals(extension)) {  
16:                      mime = "text/plain";  
17:                 } else if ("csv".equals(extension)) {  
18:                      mime = "text/csv";  
19:                 } else {  
20:                      mime = "text/unknown";  
21:                 }  
22:            }  
23:            this.name = name;  
24:       }  
25:       public String getMime() {  
26:            return mime;  
27:       }  
28:       public void setMime(String mime) {  
29:            this.mime = mime;  
30:       }  
31:       public long getLength() {  
32:            return length;  
33:       }  
34:       public void setLength(long length) {  
35:            this.length = length;  
36:       }  
37:       public byte[] getData() {  
38:            return data;  
39:       }  
40:       public void setData(byte[] data) {  
41:            this.data = data;  
42:       }  
43:  }  

Finally Create the JSF file:
1:  <?xml version='1.0' encoding='UTF-8' ?>  
2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
3:  <html xmlns="http://www.w3.org/1999/xhtml"  
4:       xmlns:f="http://java.sun.com/jsf/core"  
5:       xmlns:h="http://java.sun.com/jsf/html"  
6:       xmlns:ui="http://java.sun.com/jsf/facelets"  
7:       xmlns:a4j="http://richfaces.org/a4j"  
8:       xmlns:rich="http://richfaces.org/rich">  
9:  <h:body>  
10:       <ui:composition template="template/common/commonLayout.xhtml">  
11:            <ui:define name="content">  
12:                 <h:form>  
13:                      <h:panelGrid columns="2" columnClasses="top,top">  
14:                           <rich:fileUpload fileUploadListener="#{fileUploadController.listener}"  
15:                                id="upload" acceptedTypes="txt,csv"  
16:                                ontyperejected="alert('Only Text and CSV files are accepted');"  
17:                                maxFilesQuantity="1">  
18:                                <a4j:ajax event="uploadcomplete" execute="@none" render="info" />  
19:                           </rich:fileUpload>  
20:                      </h:panelGrid>  
21:                      <h:panelGroup id="info">  
22:                           <rich:dataGrid columns="1" value="#{fileUploadController.files}"  
23:                                var="file" rowKeyVar="row">  
24:                                <rich:panel bodyClass="rich-laguna-panel-no-header">  
25:                                     <h:panelGrid columns="2">  
26:                                          <a4j:mediaOutput element="img" mimeType="image/jpeg"  
27:                                               createContent="#{fileUploadController.paint}" value="#{row}"  
28:                                               style="width:100px; height:100px;" cacheable="false">  
29:                                               <f:param value="#{fileUploadController.timeStamp}" name="time" />  
30:                                          </a4j:mediaOutput>  
31:                                          <h:panelGrid columns="2">  
32:                                               <h:outputText value="File Name:" />  
33:                                               <h:outputText value="#{file.name}" />  
34:                                               <h:outputText value="File Length(bytes):" />  
35:                                               <h:outputText value="#{file.length}" />  
36:                                          </h:panelGrid>  
37:                                     </h:panelGrid>  
38:                                </rich:panel>  
39:                           </rich:dataGrid>  
40:                           <a4j:commandButton action="#{fileUploadController.clearUploadData}"  
41:                                render="info, upload" value="Clear Uploaded Data"  
42:                                rendered="#{fileUploadController.size>0}" />  
43:                           <a4j:commandButton action="#{fileUploadController.writeFile}"  
44:                                value="Write file to Disk" rendered="#{fileUploadController.size>0}" />  
45:                      </h:panelGroup>  
46:                 </h:form>  
47:            </ui:define>  
48:       </ui:composition>  
49:  </h:body>  
50:  </html>  

Thursday, June 28, 2012

How to Download File using JSF

Following is the simple example how to download file from Server using JSF application

1. Create new JSF bean, either ManageBean or Component Bean using Spring framework

1:  package com.jsf.app.managedbean;  
2:  import java.io.BufferedInputStream;  
3:  import java.io.BufferedOutputStream;  
4:  import java.io.File;  
5:  import java.io.FileInputStream;  
6:  import java.io.IOException;  
7:  import javax.faces.context.FacesContext;  
8:  import javax.servlet.http.HttpServletResponse;  
9:  import javax.faces.bean.ManagedBean;  
10:  @ManagedBean(name="fileDownloadBean")  
11:  public class FileDownloadBean {  
12:       private static final int DEFAULT_BUFFER_SIZE = 10240;  
13:       private String filePath = "c:\\download\\test.txt";  
14:       public void downLoad() throws IOException {  
15:            FacesContext context = FacesContext.getCurrentInstance();  
16:            HttpServletResponse response = (HttpServletResponse) context  
17:                      .getExternalContext().getResponse();  
18:            File file = new File(filePath);  
19:            if (!file.exists()) {  
20:                 response.sendError(HttpServletResponse.SC_NOT_FOUND);  
21:                 return;  
22:            }  
23:            response.reset();  
24:            response.setBufferSize(DEFAULT_BUFFER_SIZE);  
25:            response.setContentType("application/octet-stream");  
26:            response.setHeader("Content-Length", String.valueOf(file.length()));  
27:            response.setHeader("Content-Disposition", "attachment;filename=\""  
28:                      + file.getName() + "\"");  
29:            BufferedInputStream input = null;  
30:            BufferedOutputStream output = null;  
31:            try {  
32:                 input = new BufferedInputStream(new FileInputStream(file),  
33:                           DEFAULT_BUFFER_SIZE);  
34:                 output = new BufferedOutputStream(response.getOutputStream(),  
35:                           DEFAULT_BUFFER_SIZE);  
36:                 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
37:                 int length;  
38:                 while ((length = input.read(buffer)) > 0) {  
39:                      output.write(buffer, 0, length);  
40:                 }  
41:            } finally {  
42:                 input.close();  
43:                 output.close();  
44:            }  
45:            context.responseComplete();  
46:       }  
47:  }  

2. Now Access the file using the JSF link as shown below:

1:                      <h:form>  
2:                           <h:commandLink id="getDownload" value="Download Files"  
3:                                     action="#{fileDownloadBean.downLoad}">  
4:                                </h:commandLink>  
5:                      </h:form>  

3. Create web.xml something like:
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:       xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
4:       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
5:       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
6:       id="WebApp_ID" version="2.5">  
7:       <listener>  
8:            <listener-class>com.sun.faces.config.ConfigureListener</listener-class>  
9:       </listener>  
10:       <context-param>  
11:            <param-name>javax.faces.PROJECT_STAGE</param-name>  
12:            <param-value>Development</param-value>  
13:       </context-param>  
14:       <context-param>  
15:            <param-name>javax.faces.CONFIG-FILES</param-name>  
16:            <param-value>WEB-INF/faces-config.xml</param-value>  
17:       </context-param>  
18:       <context-param>  
19:            <param-name>com.sun.faces.expressionFactory</param-name>  
20:            <param-value>com.sun.el.ExpressionFactoryImpl</param-value>  
21:       </context-param>  
22:       <servlet>  
23:            <servlet-name>Faces Servlet</servlet-name>  
24:            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
25:            <load-on-startup>1</load-on-startup>  
26:       </servlet>  
27:       <servlet-mapping>  
28:            <servlet-name>Faces Servlet</servlet-name>  
29:            <url-pattern>/faces/*</url-pattern>  
30:       </servlet-mapping>  
31:       <servlet-mapping>  
32:            <servlet-name>Faces Servlet</servlet-name>  
33:            <url-pattern>*.jsf</url-pattern>  
34:       </servlet-mapping>  
35:       <servlet-mapping>  
36:            <servlet-name>Faces Servlet</servlet-name>  
37:            <url-pattern>*.faces</url-pattern>  
38:       </servlet-mapping>  
39:       <servlet-mapping>  
40:            <servlet-name>Faces Servlet</servlet-name>  
41:            <url-pattern>*.xhtml</url-pattern>  
42:       </servlet-mapping>  
43:  </web-app>  

Now after deploying this in the servlets container, you will see the dialog box for Save the File/Open.


Sunday, June 17, 2012

How to create generic Repository Dao in JPA.

Repository Dao is an interface to interact with the low level database operation, specially CRUD operations. The Repository Dao interface is usually designed to hide the implementation details and provide the uniform API to the client of the Dao usually Service classes.
In the below example, I will create the basic domain, Dao Interface, Implementation and Test class for JPA implementation.

1. First Create the database schema as shown below:
 create table login_user(uuid varchar2(40), user_name varchar2(40), password varchar2(100), first_name varchar2(100), last_name varchar2(100));  


2. Create the domain class for the data model shown above:

PersistableId Class
1:  package com.jsf.app.persistence.model;  
2:  import java.io.Serializable;  
3:  import javax.persistence.Column;  
4:  import javax.persistence.Id;  
5:  import javax.persistence.MappedSuperclass;  
6:  import javax.persistence.PrePersist;  
7:  import com.jsf.app.utils.UUIDGenerator;  
8:  @MappedSuperclass  
9:  public class AbstractIdPersistable implements Serializable {  
10:       private static final long serialVersionUID = -2722115269874427565L;  
11:       @Id  
12:       @Column(name = "UUID")  
13:       private String id;  
14:       public String getId() {  
15:            return id;  
16:       }  
17:       public void setId(String id) {  
18:            this.id = id;  
19:       }  
20:       public boolean isNew() {  
21:            return null == getId();  
22:       }  
23:       @PrePersist  
24:       public void assignUUID() {  
25:            this.setId(UUIDGenerator.getUUID());  
26:       }  
27:  }  

Persistable User Class map to LOGIN_USER table.
1:  package com.jsf.app.persistence.model;  
2:  import javax.persistence.Column;  
3:  import javax.persistence.Entity;  
4:  import javax.persistence.NamedQueries;  
5:  import javax.persistence.NamedQuery;  
6:  import javax.persistence.Table;  
7:  @Entity  
8:  @Table(name = "LOGIN_USER")  
9:  @NamedQueries({  
10:            @NamedQuery(name = "user.findAll", query = "from User"),  
11:            @NamedQuery(name = "user.findByUserName", query = "from User u where u.userName = ?") })  
12:  public class User extends AbstractIdPersistable {  
13:       private static final long serialVersionUID = -6103795542566301215L;  
14:       @Column(name = "USER_NAME", nullable = false)  
15:       private String userName;  
16:       @Column(name = "PASSWORD", nullable = false)  
17:       private String password;  
18:       @Column(name = "FIRST_NAME", nullable = false)  
19:       private String firstName;  
20:       @Column(name = "LAST_NAME", nullable = false)  
21:       private String lastName;  
22:       public String getUserName() {  
23:            return userName;  
24:       }  
25:       public void setUserName(String userName) {  
26:            this.userName = userName;  
27:       }  
28:       public String getPassword() {  
29:            return password;  
30:       }  
31:       public void setPassword(String password) {  
32:            this.password = password;  
33:       }  
34:       public String getFirstName() {  
35:            return firstName;  
36:       }  
37:       public void setFirstName(String firstName) {  
38:            this.firstName = firstName;  
39:       }  
40:       public String getLastName() {  
41:            return lastName;  
42:       }  
43:       public void setLastName(String lastName) {  
44:            this.lastName = lastName;  
45:       }  
46:       @Override  
47:       public String toString() {  
48:            return "[" + this.getId() + ", " + this.getFirstName() + ", "  
49:                      + this.getLastName() + "]";  
50:       }  
51:  }  

3. Now create a generic persistence dao interface:
1:  package com.jsf.app.persistence.dao;  
2:  import java.util.Collection;  
3:  public interface AbstractPersistenceDao<Entity> {  
4:       public Entity findById(String id);  
5:       public void save(Entity e);  
6:       public void remove(Entity e);  
7:       public Collection<Entity> findByNamedQuery(String nameQuery);  
8:       public Collection<Entity> findByNamedQueryAndParams(String nameQuery,  
9:                 Object... params);  
10:  }  

4. Now create an abstract implementation of the generic persistence dao:

1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.lang.reflect.ParameterizedType;  
3:  import java.util.Collection;  
4:  import javax.persistence.EntityManager;  
5:  import javax.persistence.PersistenceContext;  
6:  import javax.persistence.Query;  
7:  import com.jsf.app.persistence.dao.AbstractPersistenceDao;  
8:  public abstract class AbstractPersistenceDaoImpl<Entity> implements  
9:            AbstractPersistenceDao<Entity> {  
10:       @PersistenceContext  
11:       private EntityManager entityManager;  
12:       public AbstractPersistenceDaoImpl() {  
13:       }  
14:       @SuppressWarnings("unchecked")  
15:       public Class<Entity> returnEntityClass() {  
16:            ParameterizedType genericSuperclass = (ParameterizedType) getClass()  
17:                      .getGenericSuperclass();  
18:            return (Class<Entity>) genericSuperclass.getActualTypeArguments()[0];  
19:       }  
20:       @Override  
21:       public Entity findById(String id) {  
22:            return entityManager.find(returnEntityClass(), id);  
23:       }  
24:       @Override  
25:       public void save(Entity e) {  
26:            this.entityManager.persist(e);  
27:       }  
28:       @Override  
29:       public void remove(Entity e) {  
30:            this.entityManager.remove(e);  
31:       }  
32:       @Override  
33:       @SuppressWarnings("unchecked")  
34:       public Collection<Entity> findByNamedQuery(String query) {  
35:            Query q = this.entityManager.createNamedQuery(query);  
36:            return (Collection<Entity>) q.getResultList();  
37:       }  
38:       @Override  
39:       @SuppressWarnings("unchecked")  
40:       public Collection<Entity> findByNamedQueryAndParams(String nameQuery,  
41:                 Object... params) {  
42:            Query q = entityManager.createNamedQuery(nameQuery);  
43:            int i = 1;  
44:            for (Object o : params) {  
45:                 q.setParameter(i, o);  
46:            }  
47:            return (Collection<Entity>) q.getResultList();  
48:       }  
49:  }  

5. We can now create our customized Dao Interface and Implementation for our Domain Objects. In this case for our User domain object as shown below:

1:  package com.jsf.app.persistence.dao;  
2:  import java.util.Collection;  
3:  import com.jsf.app.persistence.model.User;  
4:  public interface UserDao extends AbstractPersistenceDao<User> {  
5:       public Collection<User> getAllUser();  
6:       public void persistChange(User user);  
7:  }  

and Implementation:
1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.util.Collection;  
3:  import org.springframework.stereotype.Repository;  
4:  import org.springframework.transaction.annotation.Transactional;  
5:  import com.jsf.app.persistence.dao.UserDao;  
6:  import com.jsf.app.persistence.model.User;  
7:  @Repository("userDao")  
8:  public class UserDaoImpl extends AbstractPersistenceDaoImpl<User> implements  
9:            UserDao {  
10:       public UserDaoImpl() {  
11:            super();  
12:       }  
13:       @Override  
14:       @SuppressWarnings("unchecked")  
15:       public Collection<User> getAllUser() {  
16:            return findByNamedQuery("user.findAll");  
17:       }  
18:       @Override  
19:       @Transactional  
20:       public void persistChange(User user) {  
21:            save(user);  
22:       }  
23:  }  

6. Finally create the test case to test the Dao and Implementation:

1:  package com.jsf.app.persistence.dao.impl;  
2:  import java.util.Collection;  
3:  import java.util.List;  
4:  import org.junit.After;  
5:  import org.junit.Assert;  
6:  import org.junit.Before;  
7:  import org.junit.Ignore;  
8:  import org.junit.Test;  
9:  import org.junit.runner.RunWith;  
10:  import org.springframework.beans.factory.annotation.Autowired;  
11:  import org.springframework.test.context.ContextConfiguration;  
12:  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
13:  import org.springframework.test.context.transaction.TransactionConfiguration;  
14:  import org.springframework.transaction.annotation.Transactional;  
15:  import com.jsf.app.persistence.dao.UserDao;  
16:  import com.jsf.app.persistence.model.User;  
17:  @RunWith(SpringJUnit4ClassRunner.class)  
18:  @ContextConfiguration(locations = { "classpath*:applicationContext.xml" })  
19:  @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)  
20:  public class UserDaoTest {  
21:       @Autowired  
22:       private UserDao userDao;  
23:       @Before  
24:       public void before() {  
25:       }  
26:       @After  
27:       public void after() {  
28:       }  
29:       @Test  
30:       @Transactional  
31:       @Ignore  
32:       public void testSaveAllUsers() {  
33:            User u = new User();  
34:            u.setFirstName("Joy");  
35:            u.setLastName("Steward");  
36:            u.setUserName("joy");  
37:            u.setPassword("password");  
38:            userDao.persistChange(u);  
39:       }  
40:       @Test  
41:       public void testGetAllUser() {  
42:            List<User> users = (List<User>) userDao.getAllUser();  
43:            Assert.assertNotNull(users);  
44:            Assert.assertEquals(1, users.size());  
45:       }  
46:       @Test  
47:       public void testNamedQueryAndParam() {  
48:            Collection<User> users = userDao.findByNamedQueryAndParams(  
49:                      "user.findByUserName", "joy");  
50:            Assert.assertNotNull(users);  
51:            Assert.assertEquals(1, users.size());  
52:       }  
53:       @Test  
54:       public void testFindUserById() {  
55:            User u = userDao.findById("E5429C88F74F4A8C6B13399485587401");  
56:            Assert.assertNotNull(u);  
57:            Assert.assertEquals("joy", u.getUserName());  
58:       }  
59:  }