Pages

Saturday, November 12, 2011

JDBC Driver URL Format for connection with Oracle


I got the idea of testing my connectivity through JDBC with Oracle, when my attempt to connect through Hibernate in a Struts application failed.
Really I wonder like any one else about what one’s mind can do to one. In my case here it was constructive. Atleast I got to learn something J

jdbc:oracle:thin:[user/password]@[host][:port]:SID
jdbc:oracle:thin:[user/password]@//[host][:port]/SID

  user - The login user name defined in the Oracle server.

  password - The password for the login user.

  host - The host name where Oracle server is running.
         Default is 127.0.0.1 - the IP address of localhost.

  port - The port number where Oracle is listening for connection.
         Default is 1521.

  SID  - System ID of the Oracle server database instance.
         SID is a required value. By default, Oracle Database 10g Express
         Edition creates one database instance called XE.

Here are some example connection URLs:

jdbc:oracle:thin: Herong/TopSecret @localhost:1521:XE
jdbc:oracle:thin:Herong/TopSecret@:1521:XE

jdbc:oracle:thin:Herong/TopSecret@//localhost:1521/XE
jdbc:oracle:thin:Herong/TopSecret@//:1521/XE
jdbc:oracle:thin:Herong/TopSecret@//localhost/XE
jdbc:oracle:thin:Herong/TopSecret@///XE

You can find more details about the same in http://www.herongyang.com/JDBC/Oracle-JDBC-Driver-Connection-URL.html. Seems to be a real nice site

The host, port and SID details can be found in tnsNames.ora file. Following is an illustration of the same


Hence the URL formats for me were like

jdbc:oracle:thin:Karthick/Password@10.106.50.250:1521:AGH
jdbc:oracle:thin: Karthick/Password @//10.106.50.250:1521/AGH


Hope this helps some one seeking for this out there :)

"java.sql.SQLException: Io exception: The Network Adapter could not establish the connection" - A simple way to handle it


Following is a most common exception that one would face if connection to Oracle server is denied for some reason.

java.sql.SQLException: Io exception: The Network Adapter could not establish the connection


All you got to do is ensure that you add classes12.jar to the Java build path of you Java project. You can navigate to this point by right clicking on your project and clicking on properties



Following is a sample class that I used to connect to Oracle

import java.sql.*;

public class OracleConnectionUrl {
       public static void main(String[] args) {
              Connection con = null;

              System.out.println("about to load");
              // Load the Oracle JDBC driver
              try {
                     Class.forName("oracle.jdbc.OracleDriver");
              } catch (ClassNotFoundException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Oracle JDBC driver loaded ok.");

              try {
                     con = DriverManager
                                  .getConnection("jdbc:oracle:thin:karthick/password@10.116.51.215:1521:XHF");
                     con.close();
              } catch (SQLException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
}
}

Hope this helps :)

Format Number in Java


Formatting number is something that u might always require in scenarios like, when you are trying to create a sequence number or a unique ticket number, math calculations that would require scientific notations etc. Every technology would have a provision for this. The one found is java is sophisticated.

// The 0 symbol shows a digit or 0 if no digit present
NumberFormat formatter = new DecimalFormat("000000");
String s = formatter.format(-1234.567);  // -001235
// notice that the number was rounded up

// The # symbol shows a digit or nothing if no digit present
formatter = new DecimalFormat("##");
s = formatter.format(-1234.567);         // -1235
s = formatter.format(0);                 // 0
formatter = new DecimalFormat("##00");
s = formatter.format(0);                 // 00


// The . symbol indicates the decimal point
formatter = new DecimalFormat(".00");
s = formatter.format(-.567);             // -.57
formatter = new DecimalFormat("0.00");
s = formatter.format(-.567);             // -0.57
formatter = new DecimalFormat("#.#");
s = formatter.format(-1234.567);         // -1234.6
formatter = new DecimalFormat("#.######");
s = formatter.format(-1234.567);         // -1234.567
formatter = new DecimalFormat(".######");
s = formatter.format(-1234.567);         // -1234.567
formatter = new DecimalFormat("#.000000");
s = formatter.format(-1234.567);         // -1234.567000


// The , symbol is used to group numbers
formatter = new DecimalFormat("#,###,###");
s = formatter.format(-1234.567);         // -1,235
s = formatter.format(-1234567.890);      // -1,234,568

// The ; symbol is used to specify an alternate pattern for negative values
formatter = new DecimalFormat("#;(#)");
s = formatter.format(-1234.567);         // (1235)

// The ' symbol is used to quote literal symbols
formatter = new DecimalFormat("'#'#");
s = formatter.format(-1234.567);         // -#1235
formatter = new DecimalFormat("'abc'#");
s = formatter.format(-1234.567);         // -abc1235

String pre=”xx”;
String post=”yy”;
formatter = new DecimalFormat(pre+"'abc'000000"+post);
s=formatter.format(12.3);           // xxabc000012yy

In addition to this you can also print formatted output ot the console by using System.out.format command
System.out.format("%5s", Integer.toString(n));  //     n  (- including 5 white spaces)

Hope this helps J

Wednesday, November 9, 2011

Interceptors with Struts 2


Well another mile stone to me and learning all by yourself is such a pain. Now I understand the interceptors better. After all I was having a lot of issues with them

An interceptor as the name signifies gets triggered when an action is invoked provided the action is associated with the interceptor

 First of all following is my action class

import com.opensymphony.xwork2.ActionSupport;

public class TestLoggerAction extends ActionSupport{

       public String execute()    {
      
              System.out.println("new Inside Action");
              return SUCCESS;
             
       }
}


Following is a my interceptor class. I have imported Action support class here as well in order to overrule the return value of the action. You would understand the same when you uncomment a specific code indicated in the following block of code

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyLoggingInterceptor extends ActionSupport implements Interceptor  {

       private static final long serialVersionUID = 1L;


       public String intercept(ActionInvocation invocation) throws Exception {
      
             
              System.out.println("Finishing execution stack for action //TestLogger");

                     //----------  Un comment this line and you will see the result of the prevention of action
                     //----------  from being executed

                     //if(true) return ERROR;  


                     //----------------------------------------------------------------------------------

              String result = invocation.invoke();
              // Post processing
      
              System.out.println("Finishing execution stack for action //TestLogger");
              return result;
       }

          //called during interceptor destruction
              public void destroy() {
                     System.out.println("CustomInterceptor2 destroy() is called...");
              }
        
              //called during interceptor initialization
              public void init() {
                     System.out.println("CustomInterceptor2 init() is called...");
              }

}

Finally my struts file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
       <package name="default" extends="struts-default">

              <interceptors>
                     <interceptor name="logger"
                           class="MyLoggingInterceptor">
                     </interceptor>

                     <interceptor-stack name="loggingStack">
                           <interceptor-ref name="logger" />
                           <interceptor-ref name="defaultStack" />
                     </interceptor-stack>

              </interceptors>

              <action name="TestLogger" class=" TestLoggerAction">
                     <interceptor-ref name="loggingStack" />
                     <result name="error">/InterceptorFailure.jsp</result>
                     <result name="success">/InterceptorSuccess.jsp</result>
              </action>

       </package>
</struts>
             
Be very very precise with the characters you type in. Case sensitivity is hell lot of issue for me. L

You will get the following page if you un comment the block of code I have indicated in the interceptor class



And the following line page if you proceed as such



And your console would contain the following info


Hope this helps  :)

Working with s:bean in Struts 2 - Beware Begineers


Well well... this simple silly stuff gave me a head ache for a while. Because I broke the rules and so paid the price.
I was wondering why s:bean won’t work for me while I was able to work with other stuffs like controls, context params, stream processing, Ajax etc….
My Eclipse IDE kept telling that it was not able to recognize what s:bean is. Neither did it realize s:param and s:property.

I was puzzled. Even a few java guys felt that it was a problem with the IDE. How demoralizing. I stopped toying with it for a while and later after a couple of days, I found the culprit.

It was so simple. I got a bit comfortable with basic JSPs and Struts that I did not notice this.

The following was my jsp page’s content

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bean Tag Example</title>
</head>
<body>
<s:bean name="currencyConverter">
 <s:param name="dollars" value="100" />
 100 Dollars = <s:property value="rupees" /> Rupees
</s:bean>

</body>
</html>

And the issue was I did not add the following code to the top of that page

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

God bless me…. I just want to cry now. How could I ever forget to miss it … bummer

Hope this saves some one else at least :)

Thursday, November 3, 2011

Configuring Struts.xml for Interceptors

Well learning curve is quite breath taking with java technologies. I got curious about the interceptors feature in Struts 2 and eventually I ended up trying to sample them out for my reference and understanding. I am not yet successful on it, but at least I have had some progress on the same.


The first wall I had to jump over was that whenever I added the interceptors tag in struts.xml, I was having a heap of issues and my page/ project wont load up on the browser.


I searched through out the innernet and all spoke about how to use them and what tags to add and I was so puzzeled that I followed them exactly as per my understanding and it wouldn’t work.


Gosh…. I found the culprit at last. It was the way in which these  tags needs to be ordered in the xml file.


The interceptors tag needs to be present on top of all other action tags. So much to my observation !!!!!  It was always there and yet it took me an hour to find it. L So much to experience with the RAD technology I am associated with, for the past 4 yrs… I never had to think about these silly stuffs


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
             
       <package name="default" extends="struts-default">
             
             
              <interceptors>
                     <interceptor name="logger" class="interceptor.MyLoggingInterceptor">
                     </interceptor>
                     <interceptor-stack name="loggingStack">
                           <interceptor-ref name="logger" />
                           <interceptor-ref name="defaultStack" />
                     </interceptor-stack>
                    
              </interceptors>           
             
              <!-- <constant name="struts.devMode" value="true" /> -->
             
              <action name….>
                     <result ….">/index.jsp</result>
              </action>

              <action name….>
                     <result ….>
                           ……
                     </result>
              </action>

              <action name="TestLogger" class="TestLoggerAction">
                     <interceptor-ref name="loggingStack" />
                     <result name="success">/InterceptorSuccess.jsp</result>
              </action>
             
       </package>   
</struts>
             
       Hope this xml interpretation gives you an idea of how to configure em…

Hope this helps some one J