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 "";  
 }  

Import / Export full Orcale data

Using 'exp' command:

To export the entire database to a single file dba.dmp in the current directory.
- Login to server
- Use following command:
exp SYSTEM/password FULL=y FILE=dba.dmp LOG=dba.log CONSISTENT=y
or
exp SYSTEM/password PARFILE=params.dat

{oracle.home}/product/10.2.0/bin/expDB/prodDB FULL=Y FILE=forITMc.dmp LOG=export.log CONSISTENT=Y COMPRESS=Y
where params.dat contains the following information:
FILE=dba.dmp
GRANTS=y
FULL=y
ROWS=y
LOG=dba.log

To dump a single schema to disk (we use the scott example schema here)
- Login to server which has an Oracle client
- Use following command:
exp / FIlE=scott.dmp OWNER=scott

To export specific tables to disk.
- Login to server which has an Oracle client
- Use following command:
exp SYSTEM/password FIlE=expdat.dmp TABLES=(scott.emp,hr.countries)
- The above command uses two users : scott and hr

exp / FILE=scott.dmp TABLES=(emp,dept)
the above is only for one user

Using 'imp' command:

To import the full database exported in the example above.
imp SYSTEM/password FULL=y FIlE=dba.dmp

To import just the dept and emp tables from the scott schema
imp SYSTEM/password FIlE=dba.dmp FROMUSER=scott TABLES=(dept,emp)

To import tables and change the owner
imp SYSTEM/password FROMUSER=someUser TOUSER=scott FILE=someUser.dmp TABLES=(unit,manager)

To import just the scott schema exported in the example above
imp / FIlE=scott.dmp

{oracle.home}/product/10.2.0/bin/impDB/pwd4NewDB FILE=forITMc.dmp

Monday, May 4, 2009

Setting and echoing the classpath information using Ant

Setting classpath is a must (although not 'required' by default) to get anything useful done with Ant's javac/java tasks. One way of setting classpath is by using the 'path' element as follows:
 <path id="application.classpath">  
      <pathelement path="${java.class.path}"/>  
      <fileset dir=".">  
           <include name="lib/*.jar"/>  
      </fileset>  
 </path>  
Then comes situations where you want to see the list of jars files contained in this classpath. Following simple Ant target will echo the content of the classpath variable ('application.classpath'):
 <target name="printClassPath">  
      <property name="appClasspath" refid="application.classpath"/>  
      <echo message="classpath= ${appClasspath}"/>  
 </target>