Monday, 10 August 2015

java.io.IOException: HTTPS hostname wrong

While I was testing creating a secure connection to a new REST service am integrating with & despite I made sure I imported their certificate, I was getting the exception below:

java.io.IOException: HTTPS hostname wrong:  should be <connect2.bglobale.com>
at com.ibm.net.ssl.www2.protocol.https.c.b(c.java:117)
at com.ibm.net.ssl.www2.protocol.https.c.afterConnect(c.java:138)
at com.ibm.net.ssl.www2.protocol.https.d.connect(d.java:64)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1024)
at com.ibm.net.ssl.www2.protocol.https.b.getOutputStream(b.java:51)
at temporary.test.TestConnection.main(TestConnection.java:36)


After some investigation, I found that a self signed certificate might raise this exception even if it is created with the right domain (connect2.bglobale.com in my case) & the only way around it, is to force Java to fully trust the host-name which be achieved using the "Hostname Verifier" as shown in the example below:

package temporary.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;


public class TestConnection {

public static void main (String args[]){
StringBuffer jsonString=new StringBuffer();
String line;

HostnameVerifier hv = new HostnameVerifier(){
   public boolean verify(String urlHostName, SSLSession session){
       System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
       return true;
   }
};

try{
       URL url = new URL("https://connect2.bglobale.com/Browsing/AppSettings?merchantGUID=1fccd7e5"); 
       HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
       connection.setHostnameVerifier(hv);
       connection.setDoOutput(true);
       connection.setDoInput(true);
       connection.setRequestMethod("POST");
       
       String data = "";
       connection.setRequestProperty("Content-Length",""+data.length());
   
       OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
       writer.write("" + data);
       writer.close();
       
       System.out.println("Response code: "+connection.getResponseCode());
       System.out.println("Response message: "+connection.getResponseMessage());
       
       BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
       while ((line = br.readLine()) != null) {
               jsonString.append(line);
       }
       System.out.println("JSON String = "+jsonString);
       br.close();
       connection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}

The code highlighted in red is the one required to fix the problem.

Tuesday, 28 October 2014

Setting JVM arguments for ANT Java task



Setting the JVM properties for a Java ANT task can be bit confusing and to make it clear, am showing two samples below to compare the wrong way for doing vs the right way.

Wrong way

<java classname="com.tmpl.commerce.catalog.dataload.datareader.CatalogEntryCatalogGroupRelationPreProcessor" fork="true" failonerror="true" output="${log.dir}/dataload-preprocess-${dataload.startTime}.log">
<arg value="${dataload.preprocess}"/>
<arg value="${dataload.catalogId}"/>
<arg value="${db.user}"/>
<arg value="${db.pwd.encrypted}"/>
<arg value="${db.name}"/>
<arg value="${db.server}"/>
<arg value="${db.port}"/>
<arg value="1000" />
<arg value="false"/>
<jvmarg value="-Dwc.home=/usr/WebSphere/CommerceServer70 -Djava.util.logging.config.file=logging.properties" />
<classpath>
<path refid="classpath" />
</classpath>
</java>



Right way

<java classname="com.tmpl.commerce.catalog.dataload.datareader.CatalogEntryCatalogGroupRelationPreProcessor" fork="true" failonerror="true" output="${log.dir}/dataload-preprocess-${dataload.startTime}.log">
<arg value="${dataload.preprocess}"/>
<arg value="${dataload.catalogId}"/>
<arg value="${db.user}"/>
<arg value="${db.pwd.encrypted}"/>
<arg value="${db.name}"/>
<arg value="${db.server}"/>
<arg value="${db.port}"/>
<arg value="1000" />
<arg value="false"/>
<jvmarg value="-Dwc.home=/usr/WebSphere/CommerceServer70 " />
  <jvmarg value="-Djava.util.logging.config.file=logging.properties" />
<classpath>
<path refid="classpath" />
</classpath>
</java>

Thursday, 16 June 2011

DB2 A communication error occurred ERRORCODE=-4499

Problem:
A Java program which connects to database to extract data from different tables, and after some time of operation, crashes with the stack trace shown below:

[jcc][t4][2030][11211][3.57.82] A communication error occurred during operations on the connection's underlying socket, socket input stream, or socket output stream. Error location: Reply.fill(). Message: Connection reset. ERRORCODE=-4499, SQLSTATE=08001

Resolution:
The problem was fixed once I changed the code to close the connection in final block. I was only closing the statement but not the connection itself. This is reminder of type of problems one might face if doesn't follow the simplest Java & JDBC coding best practices.

Tuesday, 14 June 2011

DB2 java.sql.SQLException: No suitable driver

Problem:
The following line of code throws the exception below:

url = "jdbc:db2//" + server + ":" + port + "/" + database;
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection(url, username, password);

java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getConnection(DriverManager.java:559)
at java.sql.DriverManager.getConnection(DriverManager.java:189)

Resolution:
1-After investigation, I realized this is not caused by missing JARs (as I already added them all) but because the url is not properly formatted. The correct one should be:
url = "jdbc:db2://" + server + ":" + port + "/" + database;

2-The same problem happens too if you omit the line of code below:
Class.forName("com.ibm.db2.jcc.DB2Driver");

So whenever you face this exception, check the syntax of the url connecton and make sure you are loading the appropriate class for your driver before establishing the connection.

For more information, check the following link http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.apdv.java.doc/doc/tjvjcccn.htm

Sample code Open DB2 type 4 database connection

public void openConnection() throws AppException {
logger.debug("Load configuration file");
try {
     Properties config = new Properties();
     config.load(new FileInputStream("c:/config.properties"));
     server = config.getProperty("DB2_SERVER");
     port = config.getProperty("DB2_PORT");
     username = config.getProperty("DB2_USERNAME");
     password = config.getProperty("DB2_PASSWORD");
     database = config.getProperty("DB2_DATABASE");     
     url = "jdbc:db2://" + server + ":" + port + "/" + database;


     Class.forName("com.ibm.db2.jcc.DB2Driver");
     connection = DriverManager.getConnection(url, username, password);
     //Perform your logic
     connection.close();

} catch (ClassNotFoundException e) {
   //Do something
    throw new AppException("Load DB2 driver class failed");
} catch (SQLException e) {
   //Do something
    throw new AppException("DB2 database connection failed");
} catch (FileNotFoundException e) {
     //Do something
    throw new AppException("Configuration file not found");
} catch (IOException e) {
    //Do something
    throw new AppException("Load configuration file failed");
}
}

Load a properties files and use one of its properties to initialize log4j DOMConfigurator

In sample code below, we assume the main application configuration (properties) file is /opt/system.properties and it contains property LOG4J_XML_PATH which holds the full path to log4j xml configuration file. Of course, the configuration file can all other parameters required by the application.

public class ConfigFileReader{ 

    private static Properties systemProperties; 
    static {
        try {
            systemProperties = new Properties();
            systemProperties.load(new FileInputStream("/opt/system.properties"));
            String log4jpath=systemProperties.getProperty("LOG4J_XML_PATH");
            DOMConfigurator.configure(log4jpath);
       } catch (Exception e) {
              e.printStackTrace();
              System.exit(1);
       }
    }
}

log4j configuration quick start

The sample below will put you on track quickly to start using log4j. Before you begin, make sure to add log4j jar file in your CLASSPATH

public class Sample{
     static {
          DOMConfigurator.configure("C:/log4j.xml");
     }
     private static Logger logger = Logger.getLogger(Sample.class);

  public Sample() {
      logger.debug("Sample version 1.0");
  }
}

log4j.xml sample content(located under C:\log4j.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<appender name="QuickStart" class="org.apache.log4j.RollingFileAppender">
<param name="Encoding" value="UTF-8" />
<param name="File" value="C:/logs/application.log" />
<param name="MaxFileSize" value="10MB" />
<param name="MaxBackupIndex" value="10" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{DATE} [%t] %-5p %c{1} - %m%n" />
</layout>
</appender>
<root>
<priority value="debug" />
<appender-ref ref="QuickStart" />
</root>
</log4j:configuration>

Saturday, 28 May 2011

Access a J2EE container-managed datasource

Conventional method using InitialContext & JNDI:

try{
Context context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/demoDS");
}catch (NamingException e){
e.printStackTrace(); 
}
try{
Connection con = ds.getConnection();
}catch(SQLException e){
e.printStackTrace();
}

New using annotation and resource injection (J2EE 5):

@Resource(name = "demoDS")
 public void setDemoDataSource(DataSource ds) {
 this.demoDataSource = ds; 
}