Java HTTP/HTTPs Client Example – Ignore SSL

A HTTP Client example to ignore the SSL certificates.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpUtil {
static {
try {
TrustManager[] trustAllCerts = { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}

public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} };
SSLContext sc = SSLContext.getInstance("SSL");

HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
sc.init(null, trustAllCerts, new SecureRandom());

HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception localException) {
}
}

private static HttpUtil httpUtil;

private HttpUtil() {
}

public static HttpUtil getHttpUtil() {
if (httpUtil == null)
httpUtil = new HttpUtil();

return httpUtil;
}

public String doPost(String url, String data) throws Exception {
URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.addRequestProperty("Content-Type", "application/xml");
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());

writer.write(data);
writer.flush();

String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
writer.close();
reader.close();
int status = conn.getResponseCode();
conn.disconnect();
return status + "";
}

public String doGet(String url) throws Exception {

// configure the SSLContext with a TrustManager

URL urlObj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);

String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
conn.disconnect();

return buffer.toString();
}

public static void main(String[] args) {
try {
HttpUtil.getHttpUtil().doPost("url", null);
HttpUtil.getHttpUtil().doGet("url");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Use this one, if you dont have security issue. If you really want a security, then modify the above one by accepting the certificates.

January 3, 2013 at 10:19 am 1 comment

Connection Pooling : What, Why, How ?

What ?

Connection, is a way to interact with the Database from our programming language. Mostly all of us will come across the word “Database connection is always costly“.

We also accept that statement without knowing what it really means. So just a gist of what it really makes it [ if you already knew this, please skip it and move to how it works ]

snippet of connection creation

String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
 Class.forName("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection (connUrl);

When we create a Connection Object, internally what it means it

  •  The “DriverManager” checks for the registered Driver,
  •  Since we have registered our driver as “com.mysql.jdbc.Driver”, it will call “connect(url…)” method on this Driver class.
  • com.mysql.jdbc.Driver’s connect method inturn creates a “socket connection”[with default port 3306 specified with IP (your.database.domain)] to the database we are requesting in “connUrl”.
  • The created Socket connection will be used to exchange the queries from our program to the db and what we end up is called a Resultset back to program.

Why ?

So now lets talk about the word “costly”….

If we look at the time consumption in creating a connection, socket creation takes lot of time when compared to actual query execution[which is the operation we do].

So we say that “a database connection is always costly” since its creating a socket connection everytime to talk to the DB and this socket resource is limited one.

In overcoming the above defaults, we are going for Connection Pooling.

Connection Pooling means creating the connections[while initializing] and reusing them from the pool of connections rather than creating new one every time.

How ?

Let’s see how this works and how its able to manage or reuse the existing connections ?

When we use the Connection Pool Provider, it has an internal Connection Pool Manager, when it gets initialized

  • It creates connections with default pool size(for eg.5) specified [ it means creating 5 connection objects and putting it in any collection or array with status "AVAILABLE"]

eg snippet :

...
 String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
 String driver = "com.mysql.jdbc.Driver";
 private Map<java.sql.Connection, String> connectionPool = null;

private void initPool() {
 try {
 connectionPool = new HashMap<java.sql.Connection, String>();
 Class.forName(driver);
 java.sql.Connection con = DriverManager.getConnection(dbUrl);
 for (int poolInd = poolSize; poolInd < 0; poolInd++) {
 connectionPool.put(con, "AVAILABLE");
 }

}
 ...

  • when we give connectionProvider.getConnection(), then it will fetch a connection from collections. and change the status to “NOT AVAILABLE”

eg snippet :

...
 public java.sql.Connection getConnection() throws ClassNotFoundException, SQLException
 {
 boolean isConnectionAvailable = true;
 for (Entry<java.sql.Connection, String> entry : connectionPool
 .entrySet()) {
 synchronized (entry) {
 if (entry.getValue()=="AVAILABLE") {
 entry.setValue("NOTAVAILABLE");
 return (java.sql.Connection) entry.getKey();
 }
 isConnectionAvailable = false;
 }
 }
 if (!isConnectionAvailable) {
 Class.forName(driver);
 java.sql.Connection con = DriverManager.getConnection(connUrl);
 connectionPool.put(con, "NOTAVAILABLE");
 return con;
 }
 return null;
 }
 ...

  • When we close the connection we got, ConnectionProvider wont actually close the connection. Rather, it change the status to “AVAILABLE”

eg snippet :

...
 public void closeConnection(java.sql.Connection connection)
 throws ClassNotFoundException, SQLException {
 for (Entry<java.sql.Connection, String> entry : connectionPool
 .entrySet()) {
 synchronized (entry) {
 if (entry.getKey().equals(connection)) {
 //Getting Back the conncetion to Pool
 entry.setValue("AVAILABLE");
 }
 }
 }
 }
 ...

This is how a connection pool actually works [but may use diff approach] basically.

Now you may have a question, can we create our own connection Pool mechanism ?

My recommendation is to use already existing Connection Pool mechanisms available like c3p0, dbcp etc.,

September 24, 2012 at 4:43 pm 2 comments

HelloWorld In JVM’s View – How Java Program executed internally in JVM

Every java developer come across this “Hello World” that kick start us in objectville trip. But while startup, we are more concentrating in understanding language rather than thinking how the internal works. It may be true in most case. So i thought to show Hello world in Jvm’s view.

package com.wordpress.kkarthikeyanblog;

public class HelloWorld {

public static String HELLOWORLD = "Hello World";

public void print() {
System.out.println(HELLOWORLD);
}

public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.print();
}
}

After compiled the above code using javac. I am running the HelloWorld using the following command. Now JVM triggered.

java com/wordpress/kkarthikeyanblog/HelloWorld

JVM Explanation :

hey Guys, its me JVM .. If you dont know about me, just get a heads up in link 

I am going to explain, how i(jvm) handle the class file and execute it.

As i start, BoostrapperClassLoader load the essential java.lang package and “System Class Loader” inside me find the class “Hello world” by searching the classpath given. After locating the binary class file(HelloWorld.class) , it will transfer this binary stream to Me(JVM). I(JVM) extracts the following information from the binary stream of HelloWorld.class

  • constants( like literals, constants, symbolic references to types, fields, and methods) will be stored in constant pool [in this case, symbolic reference to HelloWorld class and the fields, methods, constants associated with it]
  • package,modifiers,static variables [in this case "HELLOWORLD" attribute],
  • field information(name,type,modifiers) -
  • methods information(name,return type,method parameters,modifiers, method’s bytecode) – in this case , its [print, void, public and byte code]
  • reference to ClassLoader [ which classloader loads this class ]
  • reference to class Class

and store the above information in “Method Area“.

After loading that information, i as jvm(thread) will try to find out “public static void main(String [] args)” method.

As you know, every thread in me(JVM), apart from shared “Method area” and “Heap Space“, there will be individual “stack” and “pc register”. That will help every thread of me in execution further.

i will push that main() method in stack as one stack frame by getting those info from Method Area’s method bytecode. Program Counter(pc register) will tell me(jvm thread) which line to execute next.

so as PC instructing me, i(jvm thread) start with the line

HelloWorld helloWorld = new HelloWorld();

I will get the symbolic reference(fully qualified name) of HelloWorld from constant pool and i do the lookup in method area.From Method area ,i get the class info and create the object with default initial value in “Heap space”. After creating the object, i will feed the object reference to stack method local variable.

Now PC will point to

helloWorld.print();

i(jvm) will take the local variable “helloWorld” reference in my stack and find the method print(). After getting byte code info from Method Area, i will push method “print()” in the stack as another stack frame, now i will start executing print() method.

Once the print() method is executed as before, that method will be pop up and it continue executing main() method. Once main() method ends , that method also pops up from the stack and I am done with my execution.

In Summarizing the above, In JVM, we have

Method area – to store the class metadata [as i mentioned before]
Heap Space – to hold only the objects

Specific to each Thread :
Stack – consists of stack frames[i.e Methods] – it will also hold the local variables specific to the method
Program Counter Registers – To guide what to be executed next

Apart from these, we have “Garage Collector” to free unreferenced objects.

I hope you will get a overall idea of how “hello world” program executed internally in jvm.

August 23, 2012 at 6:49 pm 9 comments

HTTPS (SSL) Configuration : in Tomcat / Jetty / Jboss

In my earlier days of development, whenever i see “https:// ” in my webbrowser, i think its a rocket science to create one such connection in my own app.
But after some years, when i am started digging, its showing me that it is as simple as it is. I am going to share the basics of SSL & its configurations in the servers.

When you start implementing HTTPS, the first question will be

what we need to do in my application to support “Https”?
There is nothing to change in our application to support “HTTPS”. But the container we are deploying(i mean server like tomcat, jboss, etc.,) need to support HTTPS i.e., we need to enable the ssl configuration in the servers.

Before starting the configuration in the servers directly, lets know the basic of SSL

Lets take a day to day example, when we enter into the office, we have to swipe our access cards to open the door. Think our access card is a certificate(for encryption) to make the communication between us and our office in a secured way. This is called SSL. Now look at the below definition

Secure Socket Layer is a secured(encrypted) communication between web browsers and web servers.

HTTPS Communication

The above pic gives the basic idea about the SSL. Now lets Configure the SSL

For SSL to Operate, we need a certificate. The certificate can be generated by built-in java tool “keytool”.

for Windows: %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA

for Unix: $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA

while executing these commands, it will prompt for the below info’s.

SSL Configuration

The default location of the certificate is ur home directory. If you want to change it, then you can modify the path by introducing “-keystore /path/to/my/keystore”.


 HTTPS enable in Tomcat :
Now the final step is to configure our tomcat with the certificate for SSL. Uncomment the following lines in the “%TOMCAT_HOME/conf/server.xml”

<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” />

The above line contains the default SSL using JSSE with keystore path as ur “home path”, & password as “changeit”. If we have generated the certificate using someother path or password, then we have to change the above to

<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true” keystoreFile=”${custompath}/.keystore” keystorePass=”123456″
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” />

Now start your tomcat, and try to access in the port “8443″[we can change this] ,”https://localhost:8443/&#8221;. Now our SSL configuration is done. we can put our Helloworld application and access it with “https://&#8221;

Enable Https ( SSL) – Jetty Server:

we can generate the certificate with alias “jetty” and configure that for Jetty by adding the following config in “${jetty_home}/etc/jetty.xml”.

<!– Add this connector code in jetty.xml –>

<Call name=”addConnector”>
<Arg>
<Newcolor: rgb(0, 0, 0); font-family: arial; font-size: small; line-height: normal; “>server.ssl.SslSelectChannelConnector”>
<Arg><Ref id=”sslContextFactory” /></Arg>
<Set name=”Port”>8443</Set>
<Set name=”maxIdleTime”>30000</Set>
<Set name=”Acceptors”>2</Set>
<Set name=”AcceptQueueSize”>100</Set>
</New>
</Arg>
</Call>

<!– Passwords and keystore location we are specifying –>
<New id=”sslContextFactory”>
<Set name=”KeyStore”>/home/karthikeyan/.keystore</Set>
<Set name=”KeyStorePassword”>123456</Set>
<Set name=”KeyManagerPassword”>123456</Set>
<Set name=”TrustStore”>/home/karthikeyan/.keystore</Set>
<Set name=”TrustStorePassword”>123456</Set>
</New>

Now start the jetty server. Try with “https://localhost:8443/&#8221;.

Jetty SSL Https

Enable Https ( SSL) – JBoss Server:

For configuring SSL in Jboss, its as similar as tomcat. Change the “${Path}/jboss-4.2.2.GA/server/default/deploy/jboss-web.deployer/server.xml” , by uncommenting the line and adding the keystorepath & keystorepass

<Connector port=”8443″ protocol=”HTTP/1.1″ SSLEnabled=”true” keystoreFile=”${custompath}/.keystore” keystorePass=”123456″
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” />

Start the Jboss, and access it in HTTPS://

Now we have access our application with “HTTP” as well as “HTTPS”.

We can also see our created certificate in the browser as shown below.

In my next blog, we will see how to create a http and https client using java.

July 16, 2012 at 5:16 pm Leave a comment

Maven – In Real Time

Maven, a perfect dependency management tool ,which most of us had used in our projects.

//Here i would like to share some realtime problem scenarios where maven is able to address it pretty well.

Mr.Yan is working as a build management engineer. He takes care of the build an deploy environment in his company on daily basis.

After doing is routine tasks he was frustated due to the increasing work load because of multiple OS, Java versions. His entire day was gone in editing the property files and pom files.

Finally he started searching for a tool that would help make his work easier and atlast found it to be Maven…

So what is Maven and how it can easy his task ???

what is maven ?

maven is a build management tool. for detailed information about that, please look into

http://maven.apache.org/what-is-maven.html

After going through the documentation, he realized “Profiles” in maven can do it.

What a Maven Profile can do for us?

Maven Profile is used for the following:

* Package the Build in different formats
* Dynamically inject the dependencies
* choose which source files or resources to be included/excluded for build (optional java files includes & excludes)
* Activation of various JDK version/OS version/Property(only System Property)

Lets see a quick snapshot of Pom,

xmlns=”http://maven.apache.org/POM/4.0.0” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd“>
<modelVersion>4.0.0</modelVersion>

    <groupId>MyTest</groupId>
<artifactId>MyTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<profiles>
<profile>
<id>yan1</id>
<activation>
<activeByDefault>false</activeByDefault>
1.5 <!–this profile will be activated if the JDK is 1.5 –>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<includes> <!–can include/Exclude the sources based on the profile –>
<include>**/MyTest1.java</include>
<include>**/service/**</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies><!– we can tell the dependencies for this profile alone–></dependencies>
</profile>
<profile>
<id>yan2</id>
<activation>
<activeByDefault>false</activeByDefault>
<property><!–this profile will be activated when the system property hq.version is 2 –>
<name>hq.version</name>
<value>2</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
<excludes><!–can include/Exclude the sources based on the profile –>
<exclude>**/MyTest2.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies><!– we can tell the dependencies for this profile alone–></dependencies>
</profile>
</profiles>
</project> 

This made his life easier… Now Yan wants to activate a profile and he types a simple command

mvn -P profileName

and he wants to call using properties

mvn -Dprop=value

After doing all these changes, now he is enjoying his life without any manual work in build management :) :)

July 16, 2012 at 4:56 pm Leave a comment

Java Thinking …

Java Thinking …

What is java thinking ?? As I am mentioning the word java, obviously we think about oops and the other known concepts like
1. Inheritance, 2. Polymorphism, 3.Encapsulation

moreover we are very much aware of all those concepts..

To make it clear, let me relate this with the last scene of the movie “The Matrix”. In this scene, Keanu Reeves is able to visualize the world in matrix format & control the surroundings ..

Confusing uh… ??? This is what I wanted to convey… As a developer , We should be able to think of the world as an object … i mean java objects …

let me try to help you out, for eg :

myself, you, cup & saucer, sea shore, chair, sky, not the least – girl friend ;) etc.. does qualify for a java object.

Let’s start with an example,

class – Men extends Person && Men implements Human ,

some attributes – String name,
int age,
Dress dress,(Dress is another class, where i have included the attrbutes like dressType, dressColour etc.,)
int heightInCms,
int weightInKg,
String color,

some Methods – actions which we make unique and ofcourse we can override some common action Person does like eating, sleeping etc ., to specify our own style.

so now you can just extend your thinking to entire surrounding of yours as objects…

this is called java(object) thinkinggg .. Thats the most needed !!!!

June 1, 2012 at 2:42 pm Leave a comment

Hello world!

Welcome to WordPress.com! This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it.

Happy blogging!

May 20, 2012 at 8:41 am Leave a comment


Blog Stats

  • 14,234 hits

Follow

Get every new post delivered to your Inbox.