Wednesday, June 25, 2014

Java/J2EE (Core Java, Spring, HIbernate, JSP, Ajax) Interview Questions

Interview Question
Core Java
Basics
  1. What do you understand by JVM.
  2. Relate JDK and JRE and its uses.
  3. How to generate class file from java file
javac Test.java

  1. If i create java file in windows and compiles in windows and run in linux .What I have to do to make it compatible.
  2. What are different ways of instantiating a class.
MyObject object = new MyObject();

            MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

           MyObject anotherObject = new MyObject();
           MyObject object = anotherObject.clone();

           ObjectInputStream inStream = new ObjectInputStream(anInputStream );
           MyObject object = (MyObject) inStream.readObject();





  1. Describe public, private and protected modifiers.
  2. Say I have Test class with main method.
Public class Tests {
public static void main(String[] args) {
testMethod();
}


private static void testMethod() {
testMethod();
}
}

Stack overflow error

  1. Interface vs abstract class
  2. Method overloading and overriding, which polymorphism works at runtime and compile time, give examples.
  3. Autoboxing and unboxing.

Exception handling
  1. What is hierarchy
  2. Try, catch and finally. Use of catch, finally
  3. What to do if I do not want to execute finally
  4. If I want to write my own exception class
  5. If I write return statement in try. Below question. Output..?? ab

public class HelloWorld{
public static void main(String []args){
String s= "";
s = getMsg();
System.out.println(s);
}
private static String getMsg(){
String a = "a";
try{
a=a+"b";
return a;
}catch(Exception e){
}finally{
a=a+"c";
System.out.println(a);
}
return "fi";
}
}
Generic
  1. What are generics and when and why were they introduced.
  2. When does generics come into play, compile time or runtime or both.
  3. What happens to generic code when you compile a class.
  4. Design a generic class which can except any type employee id.

Log4J
  1. Levels and there logging hierarchy.
Serialization
  1. What is serialization and why do we need serialization.
  2. How can I achieve serialization
  3. What are the methods present in serializable interface.
  4. What is the use of serial version id.
  5. What I will do if I do not want to serialize a particular attribute of the object.
  6. What is externalization.

Collections
  1. What are different types of collections used.
  2. Diff between hashmap and hashtable.
  3. What is concurrent hashmap
  4. How hashing and equals method works
  5. Hashset internal working – don’t add equals and hash method , then output
  6. Treeset add objects of simple class – exception occurs
  7. Comparator and comparable.
  8. Describe about collection and collections.
  9. Iterator and list Iterator
  10. Concurrent modification exception example.
  11. FailFastVSFailSafe
Threads
  1. How to implement threads
  2. Diff between booth implementation
  3. Static vs instance method calling.
//Creating new instance for every thread access.
 ExtendsThread tc1 = new ExtendsThread();

//Multiple threads share the same object.
 ImplementsRunnable rc = new ImplementsRunnable();

  1. Idea about fork joins
Java Design pattern - singleton
JSP
  1. JSP lifecycle
JSP Page Translation:
jSP Page Compilation:
Class Loading:
Execution phase:
Initialization:
jspService() execution:
jspDestroy() execution

  1. What if I write destroy method in jsp, will page destroy or show
  2. Dynamic vs static include
The syntax for static include is <%@ include file=”filename.jsp” %> and the syntax for dynamic include is <jsp:include page=”filename.jsp” />

  1. Difference between Scriptlet and Declaration
Declaration :- Used for declaring variables and methods.
example : <%!  int num =0;  %>
During translation and compilation phase of JSP life cycle all variables declared in jsp declaration become instance variables of servlet class and all methods become instance methods. Since instance variables are automatically initialized,all variables declared in jsp declaration section gets their default values.
Scriptlet:- Used for embedding java code fragments in JSP page.
example : <%  num++; %>
During translation phase of JSP Life cycle all scriptlet become part of _jspService() method. So we cannot declare methods in scriptlet since we cannot have methods inside other methods. As the variables declared inside scriptlet will get translated to local variables they must be initialized before use.

Hibernate
  1. Load V/S Get –
The get() method will return a FULL initialized object if nothing is on the session cache, that means several DB hits depending on your mappings. 

While the load() method will return a proxy (or the instance if already initialized), allowing lazy initialization and thus better performance


If load() can’t find the object in the cache or database, an exception is 
thrown. The load() method never returns null. The get() method returns
 
null if the object can’t be found.
 


  1. Cache implementation
  2. Composite key example
  3. Mappings in hibernate
  4. Xml based or annotation based
  5. hibernate_inheritance_strategy
  6. list vs set
  7. referred and owned collections
  8. use of cascade select and orphan removal
  9. hibernate API’s, query, criteria and hql.
  10. Session factory and session
  11. transaction managers
  12. configuring datasource



Spring
  1. Explain Spring DI and IOC
  2. Life cycle of spring bean.
  3. What happens if I have two beans of same name and using in service through injection
  4. Scope of beans
  5. Application context vs bean factory
  6. Spring aop
  7. Spring transactional management and programmatic management
  8. beanPostProcesssor
  9. singletone with dependency of prototype bean
  10. spring singleton vs java singleton
  11. @Autowired
  12. Spring MVC
  13. Init binders
  14. Validators


AJAX
  1. Make ajax request
  2. Get html in response.
  3. Async example
What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?
ReadWrite Lock is an implementation of lock stripping, where two separate locks are used for read and write operation. Since read operation doesn't modify state of object, it's safe to allow multiple access of shared object to multiple reader without locking, and by splitting lock into ReadLock and WriteLock, you can easily do that. Java provides an implementation of ReadWriteLock in form of ReentrantReadWritLock, which is worth looking. Also ConcurrentHashMap doesn't use ReadWriteLock, instead it divides maps into several segments and lock them separately using different locks, which means any given time, only a portion of map is locked, instead of whole map. This question is also very popular on Senior and experienced level Java interviews, expect Interviewer to go into more detail, e.g. asking you to provided an implementation of ReadWriteLock with different policies.

  1. How to make an Object Immutable in Java? Why should you make an Object Immutable?
    Well, Immutability offers several advantage including thread-safety, ability to cache and result in more readable multithreading code. See here to learn how to make object Immutable. Once again, this question can also go into more detail and depending upon your answer, can bring several other questions e.g. when you mention Spring is Immutable, be ready with some reasons on Why String is Immutable in Java.

    11) Which design patterns have you used?
    Always expect design and patterns related question for Senior developer Core Java Interview. It's best to mention any GOF design pattern rather than Singleton or MVC, which almost every other Java developer use it. Your best bet can be Decorator pattern or may be Dependency Injection Pattern, which is quite popular in Spring Framework. It's also good to mention only design pattern, which you have really used in your project and knows it's tradeoffs. As once you mention a particular design pattern say Factory, Interviewer's next question would be, have you used in your project? So be ready with proper example and why you choose a particular pattern.
14)  How  do you prevent SQL Injection in Java Code?
This question is more asked to Java EE developers than core Java developers but still a good question to know, PreparedStatement is the way to go. PreparedStatement not only provides better performance but also shield from SQL Injection attack. If you are working more on Java EE or J2EE side, than you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them.

Why Java doesn't support multiple inheritance

1) First reason is ambiguity around Diamond problem, consider a class A has foo() method and then B and C derived from A and has there own foo() implementation and now class D derive from B and C using multiple inheritance and if we refer just foo() compiler will not be able to decide which foo() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
           A foo()
           / \
          /   \
   foo() B     C foo()
          \   /
           \ /
            D
           foo()

In my opinion even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

How do you detect deadlock in Java ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.

other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.


Why JDBC has all interfaces and no implementation classes
Securing URL parameters.
Sorting algorithms

Sunday, June 22, 2014

Empty href and src and there effects on Application

This is a problem I’ve come across frequently, and since it has come up again recently, I thought I’d explore this issue in the hope that it will save others some trouble. There are so many problems that this one issue can lead to that it’s baffling browsers still behave this way. The issue? An HTML image, either via <img> tag or JavaScript Image object, that has its src set to “” (an empty string).

The offending code

There are basically two patterns to identify. The first pattern is just straight HTML:
<img src="" >
The second pattern is JavaScript and involves the dynamic setting of the src property on either a newly created image or an existing one:

var img = new Image();
img.src = "";

You’ll note that Opera and Firefox aren’t mentioned at all. Opera behaves as you might expect: it doesn’t do anything when an empty image src is encountered; the attribute is ignored. Firefox 3 and earlier behave the same as Safari and Chrome, but Firefox 3.5 addressed this issue and no longer sends a request (related bug).
Both cases, of course, are problematic because it’s an image making a request for a document. You can easily see this behavior using an HTTP debugging proxy (I highly recommendFiddler).

The problems

There are two basic problems that this browser behavior causes. The first is a traffic spike.  Imagine that have <img src=""> on the page at http://www.example.com/. The big problem is that each instance of <img src=""> makes a request to / in all browsers, which is the homepage of the domain. Congratulations, you’ve effectively doubled your traffic to the homepage.
For small sites, this may not be that big of a deal; jumping from 10,000 to 20,000 page views probably isn’t going to raise any flags for you or your host. If you’re a page that gets millions of page views per day, and probably have a lot of machines to handle that load, doubling or tripling traffic can be crippling. You can very easily run out of capacity.
Another issue with the traffic increase is the computing power needed to generate that homepage. If the page is personalizable or is updated with some regular frequency, you could be wasting computing cycles creating a page that will never be viewed by anyone.
The second problem is user state corruption. If you’re tracking state in the request, either by cookies or in another way, you have the possibility of destroying data. Even though the image request doesn’t return an image, all of the headers are read and accepted by the browser, including all cookies. While the rest of the response is thrown away, the damage may already be done.

How does this code happen?

The first time I encountered this problem, I naively thought that it was a bad developer writing crappy code. Had this been 2000 or earlier, I probably would have been right. In today’s web development world, however, I’m mostly wrong. Today, there are so many templating engines and content management systems responsible for constructing pages on-the-fly that it’s quite possible for good developers to end up producing pages with this code. All it takes is something as simple as this PHP:

<img src="$imageUrl" >

If some other part of the code is responsible for filling in $imageUrl, and that code fails, then the offending code gets output to the browser.
In today’s web development world, we’re all doing something along these lines, whether we know it or not. Download a new WordPress theme? Make sure you’ll filled in all default arguments. Using a CMS at work? Make sure all your image URL fields are validated. It’s frightening easy to end up with this bad code on your page.

Other tags with problems

Before getting too angry at browser vendors, I think it’s fair to take a look at the HTML 4 specification, specifically the part defining images. Even though the specification indicates that the src attribute should contain a URI, it fails to define the behavior when src doesn’t contain a URI. Of course, images aren’t the only tags that reference an external resource, and so it should come as no surprise that there are other tags with the same problem.
As it turns out, Internet Explorer is the most sane browser out there. It’s problems are thankfully limited to images with an empty src attribute. It does make for this by making it a pain to detect, but that will be discussed later.
For other browsers, there are two additional problem scenarios: <script src=""> and <link href="">. Chrome, Safari, and Firefox all initiate another request.
Thankfully, no browser has a problem with <iframe src="">, as all correctly do not make another request.

What can be done?

Of course, the best thing to do is eliminate the offending code from your pages whenever possible. That’s fixing the problem at the source. If you can’t do that, though, your next best option is to attempt to detect it on the server and abort any further execution.
For browsers other than IE, it’s not too difficult to detect what’s going on from the server side. Since the request comes back to the exact same location that contains the offending code, there are two things you can do. First, you can check the request’s referrer. A request resulting from this issue coming from http://www.example.com/dir/mypage.htm will have a referrer ofhttp://www.example.com/dir/mypage.htm. Assuming that there are no valid situations under which your page links to itself, this is a fairly safe way to detect these requests on the server-side.
Internet Explorer throws a wrench into the works by sending the request to the directory of the page instead of the page itself. If you’re only using path URLs (i.e., nothing with a file extension), then the effect is the same and you can use the same referrer detect. Some sample code for use with PHP:

<?php
    //Works for IE only when using path URLs and not file URLs

    //get the referrer
    $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

    //current URL (assuming HTTP and default port)
    $url = "http://" . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI'];

    //make sure they're not the same
    if ($referrer == $url){
        exit;
    }
?>

The goal here is to detect that the page refers to itself and then exit immediately to prevent the server from doing anything additional. Another option, and probably a good idea, is to log that this has happened so it shows up on a dashboard for evaluation.
Another way to attempt to detect this type of request on the server is by looking at the HTTPAccept header. All browsers except IE send different HTTP Accept headers for image requests than they do for HTML requests. As an example, Chrome sends the following Accept header for an HTML request:

Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

Compare this to the Accept header that is sent for an image, script, or style sheet request:
Accept: */*
Firefox, Safari, and Opera all send roughly the same Accept header for HTML requests, meaning that you can check for an individual part, such as “text/html”, to determine if the request is an HTML request or something else. Unfortunately, IE only sends the latter Acceptheader for all requests, so there is no way to differentiate this on the server. For browsers other than IE, you can use something like the following:

<?php
    //Warning: Doesn't work for IE!

    //make sure the Accept header has 'text/htmnl' in it
    if (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false){
        exit;
    }
?>

This check is a little safer than the previous, but its big downside is that it doesn’t work in IE.
Why does this happen?
The real problem is the way that URI resolution is performed in browsers. This behavior is defined in RFC 3986 – Uniform Resource Identifiers. When an empty string is encountered as a URI, it’s considered a relative URI and is resolved according to the algorithm defined insection 5.2. This specific example, an empty string, is listed in section 5.4. Firefox, Safari, and Chrome are all resolving an empty string correctly per the specification, while Internet Explorer is resolving it incorrectly, apparently in line with an earlier version of the specification, RFC 2396 – Uniform Resource Identifiers (this was obsoleted by RFC 3986). So technically, the browsers are doing what they’re supposed to do to resolve relative URIs. The problem is that in this context, the empty string is clearly unintentional.

It’s time to fix this

This is a serious flaw in browsers, and I’m not sure you can look at it in any way where it’s not considered a bug. The inconsistent behavior, from Opera completely ignoring all invalid external references, to IE falling victim only for <img> tags while others do the same for<script> and <link> as well, seem to indicate a bug in browsers. Though browsers seem to be following correct URI resolution (except IE), I think this is a case where common sense must win over the letter of the specification. There is no way that an image can possibly render an HTML page, and the same goes for <script> and <link>. This bug has cost web developers hundreds of lost hours and has potentially brought down sites, pushing servers over capacity. Enough is enough. It’s time for the browser vendors to fix this bug. I’ve taken the liberty of filing or locating bugs:
Please show support for fixing these bugs, as I don’t see any reason why we should still be dealing with this browser behavior. And if anyone can get the note to Microsoft so they can address IE, we’d all greatly appreciate it.

HTML5 to the rescue

HTML5 adds to the description of the <img> tag’s src attribute to instruct browsers not to make an additional request in section 4.8.2:

The src attribute must be present, and must contain a valid URL referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. If the base URI of the element is the same as the document’s address, then the src attribute’s value must not be the empty string.

Hopefully, browsers won’t have this problem in the future. Unfortunately, there is no such clause for <script src=""> and <link href="">. Maybe there’s still time to make that adjustment to ensure browsers don’t accidentally implement this behavior.

Avoid Empty Image src

tag: server
Image with empty string src attribute occurs more than one will expect. It appears in two form:
  1. straight HTML
    <img src="">
  2. JavaScript
    var img = new Image();
    img.src = "";
Both forms cause the same effect: browser makes another request to your server.
  • Internet Explorer makes a request to the directory in which the page is located.
  • Safari and Chrome make a request to the actual page itself.
  • Firefox 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue[bug 444931] and no longer sends a request.
  • Opera does not do anything when an empty image src is encountered.

Why is this behavior bad?
  1. Cripple your servers by sending a large amount of unexpected traffic, especially for pages that get millions of page views per day.
  2. Waste server computing cycles generating a page that will never be viewed.
  3. Possibly corrupt user data. If you are tracking state in the request, either by cookies or in another way, you have the possibility of destroying data. Even though the image request does not return an image, all of the headers are read and accepted by the browser, including all cookies. While the rest of the response is thrown away, the damage may already be done.

The root cause of this behavior is the way that URI resolution is performed in browsers. This behavior is defined in RFC 3986 - Uniform Resource Identifiers. When an empty string is encountered as a URI, it is considered a relative URI and is resolved according to the algorithm defined in section 5.2. This specific example, an empty string, is listed in section 5.4. Firefox, Safari, and Chrome are all resolving an empty string correctly per the specification, while Internet Explorer is resolving it incorrectly, apparently in line with an earlier version of the specification, RFC 2396 - Uniform Resource Identifiers (this was obsoleted by RFC 3986). So technically, the browsers are doing what they are supposed to do to resolve relative URIs. The problem is that in this context, the empty string is clearly unintentional.
HTML5 adds to the description of the  tag's src attribute to instruct browsers not to make an additional request in section 4.8.2:
The src attribute must be present, and must contain a valid URL referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. If the base URI of the element is the same as the document's address, then the src attribute's value must not be the empty string.
Hopefully, browsers will not have this problem in the future. Unfortunately, there is no such clause for <script src=""> and <link href="">. Maybe there is still time to make that adjustment to ensure browsers don't accidentally implement this behavior.

Thursday, June 19, 2014

Authentication with Client Certificate over HTTPS/SSL using Java – Handshake

Authentication with Client Certificate over HTTPS/SSL using Java – Handshake




To save somebody some time in the future, a step by step instruction is provided below:
I assume you have a valid certificate or a chain of certificates, whose root is acceptable by the server. The valid certificate contains its private key. Run the following command to verify:
keytool -list -v -keystore "your certificate file"



Entry type: PrivateKeyEntry
Import your certificate and intermediate certificates into a browser like IE or Firefox and test out the https URL. This step will validate the certificates and save you a lot of troubles down the road. Java version of the SSL implementation is not as simple/mature as the browsers'. Please make sure all the certificates have not expired.
Backup your keystore located at /your_home_directory/.keystore by default and the truststore located at somewhere similar to \Java\jre6\lib\security\cacerts
Use not-yet-commons-ssl utility to import your certificates into the Java keystore format. Sample command is:
java -cp not-yet-commons-ssl-0.3.9.jar org.apache.commons.ssl.KeyStoreBuilder
Customize the following java code, replace the static final Strings to fit in your needs. Note that this implementation forcefully use a specific alias to present the corresponding certificate/certificate chain to the server. Somehow the default KeyManager simply disqualifies my certificate to be presented to the server.

public class Main {


private static final Logger logger = Logger.getLogger(Main.class.getName());
private static final String LINE_BREAKER = System.getProperty("line.separator");


private static final String CERTIFACATE_FILE = "your keystore location";
private static final String CERTIFACATE_PASS = "changeit";
private static final String CERTIFACATE_ALIAS = "your alias";
private static final String TARGET_URL = "https://xyz.com";


public static void main(String[] args) {
String targetURL = TARGET_URL;
URL url;
HttpsURLConnection connection = null;
BufferedReader bufferedReader = null;
InputStream is = null;



try {
//Create connection
url = new URL(targetURL);
//Uncomment this in case server demands some unsafe operations
//System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
connection = (HttpsURLConnection) url.openConnection();



connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");



SSLSocketFactory sslSocketFactory = getFactory(new File(CERTIFACATE_FILE), CERTIFACATE_PASS, CERTIFACATE_ALIAS);
connection.setSSLSocketFactory(sslSocketFactory);



//Process response
is = connection.getInputStream();



bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer lines = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
lines.append(line).append(LINE_BREAKER);
}
logger.info("response from " + targetURL + ":" + LINE_BREAKER + lines);



} catch (Exception e) {
...
}
}



private static SSLSocketFactory getFactory(File pKeyFile, String pKeyPassword, String certAlias) throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");



InputStream keyInput = new FileInputStream(pKeyFile);
keyStore.load(keyInput, pKeyPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());



//Replace the original KeyManagers with the AliasForcingKeyManager
KeyManager[] kms = keyManagerFactory.getKeyManagers();
for (int i = 0; i < kms.length; i++) {
if (kms[i] instanceof X509KeyManager) {
kms[i] = new AliasForcingKeyManager((X509KeyManager) kms[i], certAlias);
}
}



SSLContext context = SSLContext.getInstance("TLS");
context.init(kms, null, null);
return context.getSocketFactory();
}



/*
* This wrapper class overwrites the default behavior of a X509KeyManager and
* always render a specific certificate whose alias matches that provided in the constructor
*/
private static class AliasForcingKeyManager implements X509KeyManager {



X509KeyManager baseKM = null;
String alias = null;



public AliasForcingKeyManager(X509KeyManager keyManager, String alias) {
baseKM = keyManager;
this.alias = alias;
}



/*
* Always render the specific alias provided in the constructor
*/
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
return alias;
}



public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
return baseKM.chooseServerAlias(keyType, issuers, socket);
}



public X509Certificate[] getCertificateChain(String alias) {
return baseKM.getCertificateChain(alias);
}



public String[] getClientAliases(String keyType, Principal[] issuers) {
return baseKM.getClientAliases(keyType, issuers);
}



public PrivateKey getPrivateKey(String alias) {
return baseKM.getPrivateKey(alias);
}



public String[] getServerAliases(String keyType, Principal[] issuers) {
return baseKM.getServerAliases(keyType, issuers);
}
}
}






Try to set
-Dsun.security.ssl.allowUnsafeRenegotiation=true
if you get the error message like:
javax.net.ssl.SSLException: HelloRequest followed by an unexpected handshake message

Enabling SSL for AXIS2 service and client
We often encounter the satuation where requirement is to consume webservice exposed on https. In this article we will investigate how to consume webservice exposed over https using axis2. First lets see how to enable SSL for AXIS2 services:

Enabling SSL on server side for AXIS2 in tomcat:

You really don't need to do much enable SSL for services deplyed in AXIS2. Just follow how to enable SSL in tamcat.Add following in Server.xml of tamcat.
 

<Connector
 
port="8443" maxThreads="200"
scheme="https" secure="true" SSLEnabled="true"
keystoreFile="test.jks" keystorePass="test123"
clientAuth="false" sslProtocol="TLS"/>


Use axis2 1.5.3 in which axis2.xml has https transportReceiver enabled by default, listening on 8443 port so you don't need any configuration change in axis2.xml.
 
<transportReceiver name="https"
class="org.apache.axis2.transport.http.AxisServletListener">
<parameter name="port">8443</parameter>
</transportReceiver>

Prior to this version of axis2 was using org.apache.axis2.transport.nhttp.HttpCoreNIOSSLListener as transportReceive which was having issues and not generating https endpoint correctly.

SSL on client side:

Axis2 uses http commons to transfer SOAP message over http. Apache http common uses JSSE(java secure socket extension) library for SSL.
 
JSSE is integrated with JDK since version 1.4.
 

Ideally if we just provide end point URL starting with https, SSL connection will be started and we don’t need any additional configuration. Creation of secure connection will be taken care by JSSE. But then trust store and keystore used by the JSSE would be default keystores shipped with JDK.

In the practical/production scenarios user should have capability to choose his truststore/keystore.
 
user may decide to trust a self signed certificate and keep it his local truststore or different applications may use different keystore/truststore.
Above can be achieved by two ways:
Approach 1:
We can set truststore, password etc in system properties. This will be picked by JSSE in SSL handshake.
Ex.
System.setProperty("javax.net.ssl.trustStore","Your truststore path");
System.setProperty("javax.net.ssl.trustStorePassword","your trust store password");
This approach will not be appropriate for tooling since it sets keystore on JVM level. We should have flexibility where we could attach different keystore/truststore for different axis2 clint running in same JVM.

Approach 2:
Apache commons provide facility which allows us to customize the SSL socket factory responsible for creation of secure socket. By customization I mean ability to use user truststore/keystore in SSL handshake. To achieve it we need to extend SecureProtocolSocketFactory interface. In our custom socket factory implementation user refer its Keystore/Truststore against default keystores.
Apache commons provide a reference implementation class named AuthSSLProtocolSocketFactory for this purpose.

This class takes Truststore/Keystore as argument to constructor which will be referred later while initiating SSLContext. SSLContext is used to create SSL Socket Factory.
In your axis2 client code you need to add following:
Protocol authhttps = new Protocol ("https", new AuthSSLProtocolSocketFactory (new url("keystore URL"), "pwd", newURL("truststore URL"), "pwd"), 443);
Protocol.registerProtocol("https", authhttps);


package bo.socket;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.util.Hashtable;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.axis.components.net.JSSESocketFactory;
import org.apache.axis.components.net.SecureSocketFactory;

public class MyCustomSSLSocketFactory extends JSSESocketFactory implements SecureSocketFactory
 

{ public MyCustomSSLSocketFactory(Hashtable attributes) {
super(attributes);
}

protected void initFactory() throws IOException {

try {
SSLContext context = getContext();
sslFactory = context.getSocketFactory();
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
}
System.out.print(e.getMessage());
throw new IOException(e.getMessage());
}
}

protected SSLContext getContext() throws Exception
 
{
 
try
{
String keystore_type = KeyStore.getDefaultType(); // "JKS"

KeyStore keyStore = KeyStore.getInstance(keystore_type);
KeyStore trustStore = KeyStore.getInstance(keystore_type);

char[] keystore_password = "DemoIdentityKeyStorePassPhrase".toCharArray();
keyStore.load(new FileInputStream("C:\\bea103\\wlserver_10.3\\server\\lib\\DemoIdentity.jks"), keystore_password);

char[] trusstore_password = "DemoTrustKeyStorePassPhrase".toCharArray();
trustStore.load(new FileInputStream("C:\\bea103\\wlserver_10.3\\server\\lib\\DemoTrust.jks"), trusstore_password);

String algorithmTrust = TrustManagerFactory.getDefaultAlgorithm(); // PKIX

TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithmTrust);
tmf.init(trustStore);

String algorithmKey = KeyManagerFactory.getDefaultAlgorithm(); // "SunX509"
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithmKey);

char[] key_password = "DemoIdentityPassPhrase".toCharArray();

kmf.init(keyStore, key_password);

SSLContext sslctx = SSLContext.getInstance("SSL");

sslctx.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);

return sslctx;
}
catch (Exception e)
{ e.printStackTrace();
throw new Exception("Error creating context for SSLSocket.", e);
}
}
}

And in the main call of a WS from Client I set the new SSLSocketFactory Class:
AxisProperties.setProperty("axis.socketSecureFactory","bo.socket.MyCustomSSLSocketFactory"); 


openssl

generate a new private key and matching Certificate Signing Request (eg to send to a commercial CA)
openssl req -out MYCSR.csr -pubkey -new -keyout MYKEY.key
add -nodes to create an unencrypted private key
add 
-config <openssl.cnf> if your config file has not been set in the environment
decrypt private key
openssl rsa -in MYKEY.key >> MYKEY-NOCRYPT.key
generate a certificate siging request for an existing private key
openssl req -out MYCSR.csr -key MYKEY.key -new
generate a certificate signing request based on an existing x509 certificate
openssl x509 -x509toreq -in MYCRT.crt -out MYCSR.csr -signkey MYKEY.key
create self-signed certificate (can be used to sign other certificates)
openssl req -x509 -new -out MYCERT.crt -keyout MYKEY.key -days 365
sign a Certificate Signing Request
openssl x509 -req -in MYCSR.csr -CA MY-CA-CERT.crt -CAkey MY-CA-KEY.key -CAcreateserial -out MYCERT.crt -days 365
-days has to be less than the validity of the CA certificate




convert DER (.crt .cer .der) to PEM
openssl x509 -inform der -in MYCERT.cer -out MYCERT.pem
convert PEM to DER
openssl x509 -outform der -in MYCERT.pem -out MYCERT.der
convert PKCS#12 (.pfx .p12) to PEM containing both private key and certificates
openssl pkcs12 -in KEYSTORE.pfx -out KEYSTORE.pem -nodes
add -nocerts for private key only; add -nokeys for certificates only
convert (add) a seperate key and certificate to a new keystore of type PKCS#12
openssl pkcs12 -export -in MYCERT.crt -inkey MYKEY.key -out KEYSTORE.p12 -name "tomcat"
convert (add) a seperate key and certificate to a new keystore of type PKCS#12 for use with a server that should send the chain too (eg Tomcat)
openssl pkcs12 -export -in MYCERT.crt -inkey MYKEY.key -out KEYSTORE.p12 -name "tomcat" -CAfile MY-CA-CERT.crt -caname myCA -chain
you can repeat the combination of "-CAfile" and "-caname" for each intermediate certificate




check a private key
openssl rsa -in MYKEY.key -check
add -noout to not disclose the key
check a Certificate Signing Request
openssl req -text -noout -verify -in MYCSR.csr
check a certificate
openssl x509 -in MYCERT.crt -text -noout
check a PKCS#12 keystore
openssl pkcs12 -info -in KEYSTORE.p12
check a trust chain of a certificate
openssl verify -CAfile MYCHAINFILE.pem -verbose MYCERT.crt
trust chain is in directory (hash format): replace -CAfile with -CApath /path/to/CAchainDir/
to check for server usage: 
-purpose sslserver
to check for client usage: 
-purpose sslient
check if public key matches the private key
openssl rsa -in MYKEY.key -modulus -noout | openssl md5; /
openssl x509 -in MYCERT.crt -modulus -noout | openssl md5
This should return the same two md5-hashes




debug an SSL connection [server doesn't require certificate authentication]
openssl s_client -connect idp.example.be:443
debug an SSL connection with mutual certificate authentication
openssl s_client -connect idp.example.be:8443 -CAfile MY-CA-CERT.crt -cert MYCERT.crt -key MYKEY.key
trust chain is in directory (hash format): replace -CAfile with -CApath /path/to/CAchainDir/
send the starttls command (smtp or pop3 style): 
-starttls smtp or -starttls pop3

keytool

keytool does not support management of private keys inside a keystore. You need to use another tool for that. If you are using the JKS format, that means you need another java-based tool. extkeytool from the Shibboleth distribution can do this. 
Create an empty keystore
keytool -genkey -alias foo -keystore truststore.jks
keytool -delete -alias foo -keystore truststore.jks
Generate a private key and an initial certificate as a JKS keystore
keytool -genkey -keyalg RSA -alias "selfsigned" -keystore KEYSTORE.jks -storepass "secret" -validity 360
you can also pass the data for the DN of the certificate as command-line parameters: -dname "CN=${pki-cn}, OU=${pki-ou}, O=${pki-o}, L=${pki-l}, S=${pki-s}, C=${pki-c}"
Generate a secret key that can be used for symmetric encryption. For this to work, you need to make use of a JCEKS keystore.
keytool -genseckey -alias "secret_key" -keystore KEYSTORE.jks -storepass "secret" -storetype "JCEKS"
Generate a Certificate Signing Request for a key in a JKS keystore
keytool -certreq -v -alias "selfsigned" -keystore KEYSTORE.jks -storepass "secret" -file MYCSR.csr
Import a (signed) certificate into a JKS keystore
keytool -import -keystore KEYSTORE.jks -storepass "secret" -file MYCERT.crt
add a public certificate to a JKS keystore, eg the JVM truststore
keytool -import -trustcacerts -alias "sensible-name-for-ca" -file CAcert.crt -keystore MYSTORE.jks
If the JVM truststore contains your certificate or the certificate of the root CA that signed your certificate, then the JVM will trust and thus might accept your certificate. The default truststore already contains the root certificates of most commonly used sommercial CA's. Use this command to add another certificate for trust:
keytool -import -trustcacerts -alias "sensible-name-for-ca" -file CAcert.crt -keystore $JAVA_HOME/lib/security/cacerts
the default password of the Java truststore is "changeit".
if $JAVA_HOME is set to the root of the JDK, then the truststore is it $JAVA_HOME/jre/lib/security/cacerts
keytool does NOT support adding trust certificates to a PKCS12 keystore (which is very unfortunate but probably a good move to promote JKS)
delete a public certificate from a JAVA keystore (JKS; eg JVM truststore)
keytool -delete -alias "sensible-name-for-ca" -keystore $JAVA_HOME/lib/security/cacerts
the default password of the Java truststore is "changeit".
if $JAVA_HOME is set to the root of the JDK, then the truststore is it $JAVA_HOME/jre/lib/security/cacerts
List the certificates inside a keystore
keytool -list -v -keystore KEYSTORE.jks
-storetype pkcs12 can be used
Get information about a stand-alone certificate
keytool -printcert -v -file MYCERT.crt
Convert a JKS file to PKCS12 format (Java 1.6.x and above)
keytool -importkeystore -srckeystore KEYSTORE.jks -destkeystore KEYSTORE.p12 -srcstoretype JKS -deststoretype PKCS12 -srcstorepass mysecret -deststorepass mysecret -srcalias myalias -destalias myalias -srckeypass mykeypass -destkeypass mykeypass -noprompt




certutil




Add a PKCS12 to a windows certificate store
certutil -p secret -importpfx KEYSTORE.p12


Important Exceptions



1.) Unconnected sockets not implemented
    2.) SSL Handshake failure error

3.) org.apache.axis2.AxisFault: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target