Wednesday, September 25, 2019

httpclient.4.3.x how to view http communication in client application / enable wire logs



if you are consuming any webservice for integration purpose its always useful to have ability to see http communication with server.

 it helps in finding response issue if server is not responding correctly.


if java application is using httpclient 4.3.x version to call APIs, putting following logger gives you details logs from http hand shake to actual request and response body



log4j.logger.org.apache.http.wire=TRACE,eventIntegrator



Thursday, August 20, 2015

AXIS Client Exception:org.apache.axis2.AxisFault: Received fatal alert: handshake_failure

 Exception :



org.apache.axis2.AxisFault: Received fatal alert: handshake_failure

    at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)

    at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:83)

    .

    .

    .

    at java.lang.Thread.run(Thread.java:744)

Caused by: com.ctc.wstx.exc.WstxIOException: Received fatal alert: handshake_failure

    at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:313)

    at org.apache.axiom.om.impl.MTOMXMLStreamWriter.flush(MTOMXMLStreamWriter.java:168)

    .

    .

    .

    at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:79)

    ... 120 more

Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

    at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)

    .

    .

    .

    at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:311)

    ... 131 more





Cause:


          This exception occurs when their is mismatch between   strength of crystallographic algorithms on Server and client JRE.

resolution:

The stronger cipher is not supported by JAVA by default. On oracle site they provided following reason:

“Due to import regulations in some countries, the Oracle implementation provides a default cryptographic jurisdiction policy file that limits the strength of cryptographic algorithms


If stronger algorithms are needed (for example, AES with 256-bit keys), the JCE Unlimited Strength Jurisdiction Policy Files must be obtained and installed in the JDK/JRE. ”


Reference :

http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#importlimits



we need to download JCE Unlimited Strength Jurisdiction Policy Files  and install it on client JRE.
Download location:
http://www.oracle.com/technetwork/java/javase/downloads/index.html





 P.S.   Debug SSL communication of JAVA Application you can use following option



 javax.net.debug=all


java http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/ReadDebug.html


AXIS client exception SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


While working on one of the integration that uses axis client to call SOAP web-services, I came across few errors/exceptions, to fix them i did not found good help.

This post is my attempt to document the solution



Exception :


javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

    .

    .

    .

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)

  

    ... 18 more

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)

    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)

    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)

    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)

    ... 24 more



Cause:

                                 To resolve SSL certificate client must verify child to its  immediate parent certificate path first and then up-word till root certificate.

          Above exception is thrown because your client unable to resolve the  SSL certificate chain path from server to root certificate

Resolution:


on axis client jvm/jre import SSL certificate in following sequence
            1. Import root certificate
            2. Import child certificate of root
                     this step must be repeated for all intermediate
                    certificate till server certificate
            3. Import server certificate

 example:

  take example of gmail certificate



    for above Gmail certificate correct sequence is
           1. Geo Trust Global CA
           2. Google Internet Authority G2
           3. mail.google.com

command to import certificate in keystore

$keytool -importcert -trustcacerts -keystore ..\lib\security\cacerts -storepass changeit  -alias  mail.google.com   -file  c:\ mail.google.com.cer




 

Friday, May 15, 2015

ANT build error : java.io.IOException: CreateProcess error=206, .....The filename or extension is too long


i got this error when i ran ant with verbose switch (ant -v dist)

Their are different solution provided on internet for this error.

In my case they didn't work.

In my case problem was my ant home is too long.
eg.

C:\Users\Administrator\salesforce\src_main_013700_8467\apache-ant-1.9.0

when i places ant to smaller path it fixed the problem

C:\apache-ant-1.9.0



Wednesday, October 15, 2014

Java Service Wrapper : IPv6 : server socket creation failed.



              Recently while testing windows service developed using Java Service wrapper[JWS], we faced problem that service  was not starting. The windows box was running 2012 64bit OS and IPv6 only.

when we check log for wrapper we found following doubtful lines 

  
WARN   | wrapper  | 2014/10/14 05:25:08 | Unable to query network interfaces for valid HostIds. (The operation completed successfully. (0x0))
.
.
.
DEBUG  | wrapper  | 2014/10/14 05:25:09 | Enqueue Event 'wrapper_start'
DEBUG  | wrapper  | 2014/10/14 05:25:09 | Preparing to restart with mode 1.
ERROR  | wrapperp | 2014/10/14 05:25:09 | server socket creation failed. (An address incompatible with the requested protocol was used. (0x273f))
DEBUG  | wrapper  | 2014/10/14 05:25:09 | Enqueue Event 'wrapper_stop'
STATUS | wrapper  | 2014/10/14 05:25:09 | <-- Wrapper Stopped



when i googled it first, I did not found any useful help. So I decided to put this blog entry so that if any  one faces same issue he can found it immediately


This problem was occurred because the wrapper  communicate with JVM of application via socket.JWS by default used ipv4 address to bind socket. As my machine is Ipv6 only it was failing.

The solution to this problem is to change the communication way to PIPE, which can be done by adding following property in wrapper.conf


   wrapper.backend.type= PIPE 
 
 
you can refer the link  http://wrapper.tanukisoftware.com/doc/english/prop-backend-type.html
Thanks to JWS support they are pretty quick, and ready to help.
 
 
 
 
 
 

Tuesday, May 8, 2012

Ant task to find all java files in dir

                     

                   Some time we need to identify all file names in our project. For documentation purpose or for creating modification estimate etc. Following is the ant target that you can use to do the job. here the list of file name will be printed with semi colon ; as delimiter.
  
 
  
   
    
   
   
    list of files: 
   ${prop.javafiles}
  
                     
                   In above snippet:  ${dir.src} will be the location of source code Output will look like following
  
list:

  [echo]  list of files: 

  [echo]com\test\listproject\AdapterController.java;com
\test\listproject\cleanup\BppmDifferenceData.java;com\
test\listproject\cleanup\CleanupException.java; 
com\test\listproject\cleanup\CleanupManager.java

BUILD SUCCESSFUL

Total time: 0 seconds

Friday, May 4, 2012

JAVA Reflection : Reading method by reflection

Hi Folks,

      Last week while writing mapping utility, I came across requirement to invoke method on object using method name obviously I decided to use reflection. While using reflection  I came across two methods in java.lang.Class viz.:
    public Method getMethod(String name, Class... parameterTypes)
    public Method getDeclaredMethod(String name, Class... parameterTypes)
   
Though both the methods can be used to retrieve method information dynamically, they behave differently while searching

getMethod
  public Method getMethod(String name,Class... parameterTypes)
              throws NoSuchMethodException, SecurityException
           This method return Method object represented by parameter. The algorithm used for Searching method name, will search the method in Class passed as argument, if the method was not found inside it the search is carried out on all its super classes.

getDeclaredMethod      
 public Method getDeclaredMethod(String name,
                                 Class... parameterTypes)
                throws NoSuchMethodException, SecurityException 
             This method return Method object represented by searching in Class only which is provided as argument.

Note: If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods.

Reference:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/

Saturday, February 19, 2011

Configure Hibernate Application to use multiple database

Hi folks,

                In last couple of weeks, My team was working on configuring our application's Hibernate layer to use multiple database schema. Following are the steps we followed:
  1.  created hibernate.properties and hibernate.cfg.xml  for every database schema with different name eg. for schema zMRDB, we have created hibernatezMRDB.properties and hibernatezMRDB.cfg.xml files.
  2. don't use hibernate.properties and hibernate.cfg.xml  default files for any schema
  3. Finally at the time of Session Factory creation use following code
  4. public static SessionFactory getSessionFactory() {
         if (sessionFactory == null) {
       try {
        final Configuration cfg = new Configuration();
        Properties connectionProperties = new Properties();
        InputStream inStream = ThreadLocalUtil.class.getClassLoader().getResourceAsStream("hibernatezMRDB.properties");
        connectionProperties.load(inStream);
        cfg.setProperties(connectionProperties);
        sessionFactory = cfg.configure("hibernatezMRDB.cfg.xml").buildSessionFactory();
        
       
       } catch (Throwable ex) {
        ex.printStackTrace();
       }
      }
      return sessionFactory;
        } 
    
  5. Use SessionFactory returned by method in STEP 3 to open and use session with specific Database.

Tuesday, February 1, 2011

Easy Way to iterate Over Map

public void displayMapContaint(Map<String, String> data) {
  for (Map.Entry<String, String> pair : data.entrySet()) {
   System.out.println("Key: " + pair.getKey() + " Data: "+ pair.getValue());
  }
 }

Friday, January 7, 2011

Utility class to findout Message Digest checksum for downloded file.

hi,

lot of time after downloading/uploading some file we required some utility to verify integrity of file. This class will be useful for that times. You can generate Message Digest checksum for different algorithem. eg. MD5,SHA1 etc.

package com.blogspot.pravingole;


import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "D:/baretailpro.exe"; 
 /*
  * Supported Algorithms are 
  * 
  * MD2,MD5,SHA1,SHA256,SHA384,SHA512
  * 
  */
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) {
     sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}

Friday, October 29, 2010

Static Import

Hi ,

     While learning JUnit 4 , I came across  Static Imports of JAVA quite useful feature. Its syntax looks like

import static org.junit.Assert.*; 

    This allows the importing class to access static public members of Assert package without class name.

fail("Not yet implemented"); 

          The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.


       The static import can also import individual static member of class .

package com.blogspot.pravingole.demo;

import static java.lang.Math.PI;
import static java.lang.Math.*;

public class TestStaticImport {

 public static void main(String[] args) {
  float r = 5.1f;
  System.out.println("Circle area is : "+ (PI*r*r));
 }
}


 for more details click here

P.S. :  This static import don't  become member of importing class, so subclass can't access them without import.

Friday, October 22, 2010

What is JAR ,WAR and EAR . How to build them using ANT

HI,
In JEE, application modules are packaged as EAR, JAR and WAR based on their functionality.Each type of file (.jar, .war, .ear) is processed uniquely by application servers. I am just collecting the stuff for my reference.  :)

JAR:
       Jar file (file with a .jar extension) is the normal Java Application archive and intended to hold generic libraries of Java classes, resources, auxiliary files, etc.This can be added in classpath for compilation and to run java program. Generally in web applications we keep these files in lib directory of the application.
Ex: ojdbc14.jar – This contains all the classes to connect the oracle database
Servlet-api.jar – contains servlet related classes

Ant Task for JAR

 
for ant task details click here. 

WAR:
           Web modules which contains Servlet class files,JSP Files,supporting files, GIF and HTML files are packaged as JAR file with .war( web archive) extension. War files (files with a .war extension) are intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context.

 Ant Task for WAR


   
  
  
  
  
  
 

for ant task details click here.


EAR:
        All above files(.jar and .war) are packaged as JAR file with .ear ( enterprise archive) extension and deployed into Application Server.  Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web application.

Ant Task for EAR



      
    
 
for ant task details click here.

 Thanks.

Thursday, October 14, 2010

My favrite Vim commands

  • search - /
  • ignore case search - /\c
  • search for pattern
 /word1\(.*word2\)\@=
/.*Word1.*word2  
  • replace :   %s/word1/replaceword/gc 
  • to append at end of line  :   %s/$/word/gc
  • to append at begin of line  :  %s/^/word/gc
  • to append newline character at end of line  :  %s/$/\r/gc
  • to remove new line character  :  %s/\r//gc
  • to enable Hex editing :%!xxd
  • to go back in binary mode :%!xxd -r
  • To remove all lines not having getDisplayName

  1. replace othr lines with blank
    :%s#^\(.*getDisplayName.*\)\@!.*$##gc

    2.  remove blank lines 
        :v/\S/d
        3.  to remove all lines having getDisplayName

                  just remove @! FROM SEARCH QUERY

      • :vsp      " Vertically split the window

      • " Changing Case use with
      •  lowercase line guu
      •  uppercase line gUU
      •  lowercase line Vu
      •  uppercase line VU
      •  flip case line g~~
      •  Upper Case Word vEU
      •  Flip Case Word vE~
      •  lowercase entire file ggguG
      • buffer commands
      :bn (next buffer),
      :bp (previous buffer)
      :buffers (list open buffers)
      :b (open buffer n)
      :bd (delete buffer).
      :e will just open into a new buffer
      • Grep Command
        • :vim[grep][!] /{pattern}/[g][j] {file} ... 
        • :lvim /\<\(house\|home\)\>/gj *.txt 
        • :lw list selected buffers in grep

      Apache ANT : Learning path

      Hi folks,

             This is not another blog post about using famous build tool Apache Ant. In this post , I am going to list the resources that i found useful while learning ANT.


      Thanks

      Tuesday, October 12, 2010

      How to setup JAVA_HOME environment variable on Windows 7

      Please follow the instructions to set up JAVA_HOME environment variable in your Windows 7 PC. First find out the installation folder of Java development kit (JDK) in your machine.Let's assume it is installed in the folder "C:/jdk6"

      1. Go to Control Panel 
      2. If Control Panel is viewed by Category then select "System & Security " and here select "System" link,otherwise System link is directly inside Control Panel.
      3. On System screen select "Advanced system setting" link in left panel. This will open "System Properties" dialog box with "Advanced" tab preselcted.
      4. Click the Environment Variables button
      5. Under System Variable, click New
      6. Enter the variable name as JAVA_HOME
      7. Enter the variable value as the install path for the Development Kit.  (Eg. C:/jdk6)
      8. Click OK
      9. Click Apply Changes

      Tuesday, October 5, 2010

      Getting executing directory for Servlet web application

      Hi ,

      Some time we need to know the directory in which our web-app is running.In servlet this can be done using following code.

      String webAppPath = req.getSession().getServletContext().getRealPath("//");
      
      

      This is useful when you need to generate some file for other application.

      Tuesday, August 24, 2010

      Sql query to list rowcount for all table in schema

      Some times we face problems that require to find no. of rows in all tables in schema .

      Following are sql queries that list table name and their row count,

      For Microsoft SQL Server:
      SELECT distinct(t.name) AS table_name,i.rows
      FROM sys.tables AS t
      INNER JOIN sys.sysindexes AS i ON t.object_id = i.id
       

      For Oracle
      select table_name,num_rows counter
      from dba_tables 
      where owner = 'XXX'
      order by table_name;
      

      Tuesday, August 17, 2010

      Hotdeployment of properties file

      Hi,
           In last month we faced another Internationalization problem with properties file hot deployment. Hot deployment is commonly used to deploy updates for live web-application.
          The problem was when we hot deployed web-app the messages of  new screen are not pulled from corresponding properties file. ResourceBundle unable to find new keys ,leading to all labels are showing keys. But when we restarted server the messages are shown perfectly.
           After analyzing we realized that the properties file are not reloaded after hot deployment while all other classes are reloaded properly.This is because of ResourceBundle class, it caches properties file on read and returns retrieve strings from cache. When the class redeployed this cache remain untouched.
           The solution to this to clear this cache. we added static block in our class to clear ResourceBundle cache.
      following is the code we currently using :

      Monday, May 31, 2010

      Remove lines from log not matching search criteria

      Hi folks,

          In last week I am walking through our application log file for performance enhancement. Where I was continuously needed to find some method logs (like time consumed etc ). The log file i retrieved from test server is almost 80 MB . As I was only interested in to the retrieval of particular method logs ,to analyse the trend. So what I needed was to remove all other lines from log file which don't contain my method. I have done this using my favorite editor VIM . For that i Just needed  to fire 2 commands. I found this is very easy and useful.let's see,

      Suppose I have to find all logs for method getUiControls the commands will be
      • Search The string 'getUiControls' in vim
              /\c^.*getUiControls

                here you can confirm whether the highlighted lines shows your selection criteria (For Advanced VI          users : you can build any search queries to get intended selection)

      • Delete all lines not selected in previous search ,This command must follow 1st .
                  :v//d



      Thanks

      Saturday, May 1, 2010

      InternationalizationJava JEE Application

      In last few months I have been working on I18N. During this project activity I realized need to document the I18N experience. Most of the time programs are not written considering internationalized distribution. So we get in to the task of defining what can be internationalized (Scope). There is good link which provides checklist for this task

      http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html

      There are lots of tutorials available on net for implementing I18N for java app. listing few of them that I referred,

      For I18N of java Application

      http://java.sun.com/docs/books/tutorial/i18n/index.html

      For I18N of JSF application

      http://www.javabeat.net/tips/102-implement-internationalization-and-localizati.html

      Eclipse provide plug-in to externalize messages from java application have a look at this url

      http://www.eclipse.org/articles/Article-Internationalization/how2I18n.html

      Sorting String

      http://java.sun.com/docs/books/tutorial/i18n/text/collationintro.html

      http://w3hjava.com/?p=3

      For handling number formatting

      http://www.ibm.com/developerworks/java/library/j-numberformat/

      In rest of the post I will be writing about the problems we faced while doing Internationalization.

      • Alphabets are shown incorrectly in Japanese, German language messages.

      Though the properties files contain proper translation the messages shown incorrectly with BOM characters. This problem occurred because Java compiler and other Java tools can only process files which contain ASCII character-set. So we need to convert our properties files in non English languages so that the Non-ASCII characters should be converted in to ASCII “\u####“ notation. For that java provides native2ascii Converter, please refer the link

      http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/native2ascii.html

      In our project we used native2ascii ant task for this purpose

      http://ant.apache.org/manual/OptionalTasks/native2ascii.html

      • {0} placeholders in parametrized messages are not replaced in French language .

      This problem caused because of MessageFormat Class that we used to replace placeholders . This class treat single quote (‘) as delimiter. In French some word contain single quote this lead to the problem. For us we replaced single quote (‘) with double single quote (‘’) for parametrized messages before passing them to message format.

      • Resource bundle returns English messages though other language locale is configured.

      We have all our properties as per locale and converted using native2ascii tool still our other language messages are messed up. This problem was caused because of properties file. While adding new messages we used different editors like notepad, editplus, etc. These editors add some header at the beginning of file so that they can identify file encoding while opening it in future. This cause problem as some of our properties file contains messages from first line. So the resource bundle was unable to load those properties. So we added some commented messages at the beginning of properties file and our problem was solved.

      • Storing and sorting strings in database

      For this we need to change the column type from varchar to nvarchar. Also sorting of strings requires the sorting algorithm to be aware of the language of the strings being sorted. Since sorting is done differently in different languages. For this reason, even the DB needs to be informed of the collation setting so that ORDER BY queries return data in the correct order.

      http://msdn.microsoft.com/en-us/library/aa174903%28SQL.80%29.aspx