Friday, May 14, 2010

Varargs methods

Varargs methods have been introduced in Java 5, but they currently don’t have a wide diffusion and most part of the Java developers are not aware of their existence.

The vararg notation allows methods to accept a variable number of arguments and packs them into an array. This notation is not as convenient as you might like, because the arrays it creates suffer from the same issues involving reification as other arrays.

A Varargs methods is a standard Java method that can be invoked using a different number of objects as parameters. Example:
 // Method declaration  
 public void print(String... strs) {  
      for (int i = 0; i < strs.length; i++) {  
           System.out.println(strs[i]);  
      }  
 }  
 // Method call  
 print(null, "Hello", "World", "!");  
The syntax "String…" stands for "any number of objects of type string". You can manage this “strange” object as a normal array inside the method body. From the method writer point of view, a Varargs method is just a method with an array as its last argument. The real difference between this method and a standard one becomes evident when it is invoked. Note that the first argument is ignored in the declaration of the print method and if you desire you can write a method using just a Varargs parameter and nothing else.
The compiler translates
 return arithmetic.add(x, x, x);  
to
 return arithmetic.add(x, new Object[] {x, x});  
when the type is given in the method call. It is, as if it was doing the translation before making the decision of the T type.
 int testMethod (int x, int y, int z, int ... n) {}  
A method can accept "normal" parameters along with variable length parameter lists. To do this you must ensure that the variable length parameter list is declared last. Also, a method can't declare more than one varargs parameter.
SYNTAX:
 methodName (type t1, type t2, type t ... arguments) {}  
NOTE: Statements/Snippets taken from multiple posts purely for my understanding as well as jotting different experiences at a single place.

Thursday, May 13, 2010

Spring Transaction Management Facts

Spring Transaction Management Facts: (we may call it as business transactions as opposed to db transactions):

1. One of the most compelling reasons to use the Spring Framework is the comprehensive transaction support. Without a transaction, Spring can use a different connections between the two queries back-to-back.

2. Transactions are declared on the method level, but are actually bound to the running thread. It means that once you declare a method as transactional that transaction can span a called method tree of unlimited depth. That's why DAO layer is, normally, not declared as transactional.

3. Transaction is bound to the thread once you start a method declared as transactional. It stays bound to the thread until the method is finished or transaction is suspended. Non-transactional methods do not suspend transactions. Any method in the call tree that knows how to lookup the transaction bound to the thread can do it, no matter if method is marked as transactional or not.

4. Spring does not change autocommit mode or execute commits or rollbacks or do anything to your connection unless explicitly told.

5. Transactional behavior cannot work when autocommit is on.

6. Spring has capability of rollback the transaction in case of checked exceptions also but for that we need to configure the spring beans.xml accordingly.

7. For more details, please refer the link:
http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

NOTE: Sincere thanks to all the posts that I referred to when I implemented, experienced the above important points.

Monday, May 10, 2010

Database Basics

Something everyone wants to have quick access to ....

1. Catalog: A relational database contains a catalog that describes the various elements in the system. The catalog divides the database into sub-databases known as schemas. Within each schema are database objects -- tables, views and privileges.
The catalog itself is a set of tables with its own schema name - definition_schema. Tables in the catalog cannot be modified directly. They are modified indirectly with SQL-schema statements.
2. Schema: It is a collection of named objects used to provide a logical classification of database objects. It may contain objects such as tables,
views, aliases, indexes, triggers, and structured types.
3. Table: It is a logical structure maintained by database manager which is made up of columns and rows.
4. View: It is a parsed SQL statement which fetches record at the time of execution. It may be thought of as a virtual table that doesn't really exist in its own right but is instead derived from one or more underlying base tables.
5. Alias: The alias names are local synonyms given to certain database object.
6. Index: It is a type of data structure that allows for (potentially) faster access by providing the database with quick jump points on where to find the full reference (or to find the database row).
7. Function: It is a subprogram written to perform certain computations and return a single value.
8. Stored Procedure: It is collection of SQL statments compiled as a program which reside in the database.
9. Trigger: It is procedural code that is automatically executed in response to certain events on a particular table or view in a database.
10. Synonym: It is an object in Oracle that basically allows you to create a pointer to an object that exists somewhere else.
11. Sequence: It is an object in Oracle that is used to generate a number sequence.
12. JOIN: Return rows when there is at least one match in both tables.
13. LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table.
14. RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table.
15. FULL JOIN: Return rows when there is a match in one of the tables.
16. SELF JOIN: Querying for the result set of join with the same table.

Thursday, April 29, 2010

Power of Log4j

Recently, while working on a client project I came across following factual power of log4j:

1. Log4j has its own class loaders for loading its Appenders.

2. To avoid the log statements mix-in for scenarios when a servlet is serving more than one clients at the same time [NOTE: This would be especially tedious to trace and debug if any processing error occurred in servlet life cycle]; log4j provides an excellent way called as MDC or Mapped Diagnostic Context.

So, how do we make MDC to differentiate logging statements from multiple clients? Simple: Before starting any business process in your code, get the user name (for our Servlet, we can get it from request object) and put that into MDC. Now the user name will be available to the further processing. In your log4j.properties while defining the ‘conversionPattern’, add a pattern %X{key} to retrieve the values that are present in the MDC. The key will be ‘userName’ in our example. It's like getting a value from a Session object.

3. Each log statement throws-up an event called as LoggingEvent which is listened by the registered listeners and/or appenders.

4. NDC vs MDC - Which one should I use?
=> a. NDC has been part of the log4j framework longer than MDC.
b. NDC implements a "stack" onto which context information can be pushed and popped (ie "nested") while MDC implements a "map" into which key/value pair information can be stored.
c. NDC would work even with JDK1.1 but MDC requires JDK 1.2 or later. Under JDK 1.1 the MDC will always return empty values but otherwise will not affect or harm your application.
d. NDC use can lead to memory leaks if you do not periodically call the NDC.remove() method.
e. The MDC is managed on a per thread basis. A child thread automatically inherits a copy of the mapped diagnostic context of its parent.

... there are few more which I will add to this post shortly - So!! Keep Watching!!

Tuesday, December 15, 2009

Attaching the Accelerator Key Bindings to the RCP Application

After a tricky way I explored how to attach the Accelerator Key Bindings to the RCP Application. Following were the steps to do it:
1. An action to invoke => For eg. any of the actions like showF1HelpAction, undoAction, etc.
2. A command that invokes the action => this has to be done in plugin.xml => An example is as follows:
 <command category="com.somedomain.someproduct.commands.category" categoryId="com.somedomain.someproduct.commands.category"  
 defaultHandler="com.somedomain.someproduct.ui.handlers.UndoHandler" id="com.somedomain.someproduct.commands.undo" name="Undo">  
 </command>  
3. A handler optionally to handle the command => this has to be done in plugin.xml => An example is as follows:
 <handler class="com.somedomain.someproduct.ui.handlers.UndoHandler" commandId="com.somedomain.someproduct.commands.undo">  
 </handler>  
4. A key binding that invokes the command (that invokes the action) => this has to be done in plugin.xml => An example is as follows:
 <key commandId="com.somedomain.someproduct.commands.undo" schemeId="com.somedomain.someproduct.commands.key.binding.scheme" sequence="M1+Z">  
 </key>  
5. Your own scheme which inherits from org.eclipse.ui.defaultAcceleratorConfiguration and overwriting the defaults like Ctrl+S, Ctrl+C, Ctrl+V, etc. => this has to be done in plugin.xml => An example is as follows:
 <scheme id="com.somedomain.someproduct.commands.key.binding.scheme" name="com.somedomain.someproduct.commands.key.binding.scheme"  
 parentId="org.eclipse.ui.defaultAcceleratorConfiguration">  
 </scheme>  
6. A plug-in configuration file that enables your key bindings. => if not previously present, create a new file plugin_customization.ini and enable the key binding as follows as follows: a. Find your product extension under the org.eclipse.core.runtime.products extension point in the plugin.xml file. b. Right click your product extension and select New > property. c. In the name* field, enter preferenceCustomization. When RCP starts up your application, it will look up this property to identify the plug-in configuration file to apply. d. In the value* field, enter the name (and path, if appropriate) of your plug-in configuration file. e. In the plugin_customization.ini file add an entry to enable key bindings as: org.eclipse.ui/KEY_CONFIGURATION_ID=com.somedomain.someproduct.commands.key.binding.scheme
7. Register the actions to be invoked using key bindings for their own unique command identifiers as follows: a. Use a unique identifier string representing the command in the constructor of your action. Call the setId(), setActionDefinitionId() methods and pass this unique command identifier. b. In ApplicationActionBarAdvisor.makeActions(), register your action. When the command is invoked, RCP will look for a registered actions having the unique command identifier in action definition ID, and invoke it.

Tuesday, May 19, 2009

Invoking external program from Java

To invoke the external programs from Java, the simplest way is to use the capabilities of the Runtime class. Following sample program should illustrate the same:
 import java.io.*;  
 public class Main {  
   public static void main(String args[]) {  
    try {  
    Runtime rt = Runtime.getRuntime();  
    //Process pr = rt.exec("cmd /c dir");  
    Process pr = rt.exec("c:\\helloworld.exe");  
    BufferedReader input = new BufferedReader(new   
     InputStreamReader(pr.getInputStream()));  
    String line=null;  
    while((line=input.readLine()) != null) {  
     System.out.println(line);  
    }  
    int exitVal = pr.waitFor();  
    System.out.println("Exited with error code "+exitVal);  
    } catch(Exception e) {  
     System.out.println(e.toString());  
     e.printStackTrace();  
    }  
   }  
While hunting for this solution, I came across a very elaborate link regarding the same.
http://www.rgagnon.com/javadetails/java-0014.html

Tuesday, May 5, 2009

Converting the exception stracktrace to string

Method 1 (using log4j):
 logger.error(ex, ex);  
Method 2 (without log4j):
 public String stackTraceString(Exception e) {  
      StringBuffer s = new StringBuffer();  
      StackTraceElement[] frames = e.getStackTrace();  
      for (int i=0; i < frames.length; i++) s.append(frames[i].toString()+"\n");  
      return new String(s);  
 }  
Method 3 (without log4j):
 /** Converts the exception stracktrace to string. */  
 public StringBuffer getExceptionStackTrace(Exception ex) {  
 StringWriter strWriter = new StringWriter();  
      if (null != ex) {  
           PrintWriter out = new PrintWriter(strWriter);  
           ex.printStackTrace(out);  
      }  
      return strWriter.getBuffer();  
 }  
 /** May be used to set the exception as fault content. */  
 public String getExceptionAsXmlText(Exception ex) {  
      if (null != ex) {  
           String message = ex.getMessage();  
           String stackTrace = getExceptionStackTrace(ex).toString();  
           String exXmlText = "<exception>" + 
           "<message>" + message + "</message>" +  
           "<stack-trace>" + stackTrace + "</stack-trace>" +  
           "</exception>" ;  
           return exXmlText;  
      }  
      return "";  
 }