Featured Post

The great debacle of healthcare.gov

This is the first time in history when the president of the United States of America, or probably for any head of state around the world,...

Friday, November 30, 2007

Useful UNIX Commands

Command: grep
Description: finds text within file
Options:
-n - prepend line number into the output file
Example:
grep searches for the into the file
Variation: all

Command: ifconfig
Description: to set network connection
Options:
a - to show all options
Example:
Variation: all

Command: stty
Description: To set the terminal setting.
Options:
a - to show all options
Example: stty erase to set the backspace key to erase command line text.
Variation: all

command: uname
Description: To show the system information
Options: -snrvmapiX
-a - to show system detail
-X - to show detail
Example:
Variation: all

command: Get release version
Description:
cat /var/sadm/softinfo/INST_RELEASE OR cat /etc/release

Command:
sar
Description: Memory usage
Variation:
Solaris

Command:
psrinfo -v
Description: CPU specification
Variation: Solaris

Command:
mpstat
Description: Process Usage
Variation:
Solaris


Command:
prstat
Description: process detail
Options:
-s size
Variations: Solaris

Command:
/usr/sbin/prtconf | grep size
Description: Memory available
Variation: Solaris

Command:
swap
Description: Swap space
Options:
ls
Variations: Solaris


Command:
find /usr/local/web -size +20000 -print
Description: Find the files with minimum given size: it prints file names more than 10MB of sizes
Options:
find
-size
-print
Example: find /usr/local/web -size +20000 -print


Command:
> find . -name file-name
Description: Find a file
Options:

-name
Variation: Solaris
Example:
find . -name file-name

Command: du
Description: Disk usage
Options:
. : current directory
-s: sum of disk usage
-k: in Kilobytes
-h: human readable format
Example: du -sh *
Variation: All

Command: df
Description: Disc space occupied by the filesystem directory/files
Options:
-k: in Kilobytes
Example: du -k | grep /usr/local would show you the size and percentage of usage

Setting environment variable
C Shell
:
Setting environment: setenv PATH "${PATH}:/usr/local:/usr/local/bin"
Unsetting environment: unsetenv PATH


Re-executing the changed shell file
C-Shell: source .cshrc
Korn Shell: . .profile
Bash-Shell: . .bashrc

Check if a process is running:
ps -ef | grep
e.g. to check if apache webserver is running
ps -ef | grep httpd


Change permission and ownership of file
chmod 777 file_name/dir_name
chmod o+rwx file_name/dir_name

chown user_name file_name

Command: checkuser -n netgroup
checkuser -u username
get the detail of the user id

Resourceful Unix command site:

http://www.computerhope.com/unix.htm
http://sysunconfig.net/unixtips/solaris.html
http://www.panix.com/~elflord/unix/grep.html - Grep tutorial

Wednesday, November 28, 2007

Tips: Javascript

Adding text to the OS clipboard

function copyTextToClipboard()
{
var textElement = document.getElementById(
);
if (window.clipboardData && clipboardData.setData)
{

clipboardData.setData("key", textEelement.value);
}

}

In the onClick() event of the relevant command button would invoke this javascript function (javascript:copyTextToClipboard()). Then the text would be available in the clipboard and can be paste into any text editor.


Show page loading image

If it is a long processing in the server side, sometimes users are confused whether the page has been submitted or not. It becomes worst if the status bar is made hidden on the browser. So the user could submit the page again and again. In previous we were doing lots of hardwork to make the buttons uneditable or hidden immediatedly after clicking it or submitting the form. Now a days, the popular and smart solution of this is to showing some animated image that gives a illusion of loading the page or processing in server side. It can be achieved by a simple javascript method call.

i. Put the entire body content of your html page in a <div> tag with some name e.g. body
ii. Trap the onClick event of html button and call the below javascript method:

function submit()
{
document.forms[0].action="/submit.do";
document.forms[0].submit();
document.getElementById('body').innerHTML=
"<div style='position: absolute; left: 40%; top: 50%; '><img
src='/images/ajax-loader.gif' alt='This will display an animated GIF'/>

}


Confirmation dialogue box using Yahoo API

1. Get the required yahoo .js files from the yahoo site and put it into your page:
<script src="js/event.js"></script>
<script src="js/dragdrop.js"></script>

<script src="js/container.js"></script>
<script src="js/connection.js"></script>

<script src="js/animation.js"></script>

2. set the namespace

YAHOO.namespace("test");


3. Initialize the dialogue boxes:

YAHOO.test.confirmDialog = new YAHOO.widget.SimpleDialog("dialog", {visible:false,
width: "30em", effect:[}effect: YAHOO.widget.ContainerEffect.FADE, duration:0.2}],
fixedcenter:true, modal:true, draggable: true});
YAHOO.test.confirmDialog.setHeader("Confirmation"); YAHOO.test.confirmDialog.setBody("Do you confirm?"); YAHOO.test.confirmDialog.cfg.queueProperty("buttons", [{ text: "Ok", handler:handleOk, isDefault:true}, {text: "Cancel", handler:handleCancel"}]); var keyListener = new YAHOO.util.KeyListener(document, {keys:27},
{fn:handleCancel, scope:YAHOO.text.confirmDialog, correctScope:true});
YAHOO.test.confirmDialog.cfg.queueProperty(keyListeners", keyListheners); YAHOO.text.confirmDialog.render(document.body); YAHOO.util.Event.addListener(window, "load", init);

4. Write the handler functions

var handleCancel=function() { this.hide(); } var handleOk = function() { document.forms[0].submit(); this.hide(); }

5. Call the dialogues from the form

onclick=YAHOO.test.confirmDialog.show();

Resources

http://www.htmlgoodies.com/beyond/dhtml/ Good site to get DHTML tips

Tips: CSS

Some simple but essential HTML style tips.

1. To wrap any text within a boundary use the <div>element with the word-wrap style:

<div style="WORD-WRAP: break-word">Something Something Something .........</div>

Tuesday, November 27, 2007

Kill a dangling process in Windows XP

If I stop the Rational Application Developer (RAD) Test Environment server (version 5.1), sometimes the shows the error message that the ports (9080, 9090 and 9043) are already opened by another process.



Solution:



1. See the all running processes in the console:
c:\>netstat -ao

2. Look for the process id that owns the port numbers. And kill the process(es):
c:\>taskkill /a /PID 3172

Wednesday, November 14, 2007

Datasource scope issue in j2ee application

Before jump into the issue, lets discuss how JNDI naming works.

The JNDI lookup for any resources is resolved relative to the context defined in the Initial Context (which can be created from various jndi api like InitialContext, InitialLdapContext etc.). The exception happens only if the URL string is specified to lookup any resources (which i. URL format is defined as:
scheme_id:scheme-specific-part

J2EE specification implementation provides a root URL context as java: which is made available by any vendor container supporting J2EE specification. At the root context of the namespace, 'comp' is bounded for the components like ejb, servlet and jsp. And the 'env' is bounded to the 'comp' namespace and provided to component by the container. Usually the component deployment descriptor (e.g. web.xml for servlet/jsp component) defines the requires resource references in the descriptor and are available through java:comp/env namespace.

To understand the issue more clearly, we also need to understand the scope of the jndi lookup. There are two scopes in which any resources are looking up:

i. Component scope: This scope is resolved using the 'java:comp/env' text before the jndi resource name

ii. Server scope: This scope is resolved just by using the resource jndi name.

Now come to the point. Below is the xml tag of web application configuration file.
<resource-ref id="ResourceRef_121212121" >

<description>TestDataSource</description>

<res-ref-name>jdbc/TestDataSource</res-ref-name>

<res-type<javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

In the web.xml file of web application, the above tag creates the reference of resources. The child tag declares the name for the container bound resource so that the servlet in the web application can get the resource within the component scope (java:comp/env/). If the datasource were not declared in the web.xml then the datasource couldn't be found in the java:comp/env namespace. Though the resource bound in the application server can be found in the using the JNDI name directly, but it is not portable because the JNDI binding name could be changed anytime by the Application Server administrator.


In Tomcat, the datasource can be found in the component scope without refering the datasource in the web.xml, most probably, becuase the web component is the only component that can be deployed within it. But WebSphere Application Server (WAS) restricts access to resources those are not referenced in the web.xml. Whereas, in RAD-TestEnvironment (WAS 5.1 Test Environment), the datasource can be found with lookup using the JNDI name directly (the jndi name itself) but in WAS it doesn't work. That means inorder to access datasource from web component in WAS, the lookup name must be in component scope i.e. java:comp/env scope and the resource must be referenced in web.xml, the web component deployment descriptor

Resources
http://java.sun.com/products/jndi/tutorial/beyond/misc/policy.html
http://java.sun.com/products/jndi/tutorial/beyond/url/initctx.html
http://javahowto.blogspot.com/2006/07/when-and-where-not-to-use-javacompenv.html
http://forum.springframework.org/showthread.php?t=17712
http://www.theserverside.com/discussions/thread.tss?thread_id=27675
http://forum.java.sun.com/thread.jspa?threadID=568055&messageID=2807207
http://stackoverflow.com/questions/7167212/how-do-i-connect-to-a-websphere-datasource-with-a-given-jndi-name

Tuesday, November 13, 2007

Implement Spring in a Struts project

The implementation of Spring framework in a matured project could be tricky. Following step by step progressive integration could help to ease some of the pains:

- To prepare a project for Spring, first of all, we've to ensure that Inversion of Control Design concept is followed through out the application. And for that preparation the team might need to undergo thorough refactoring and/or redesigning, depending on the existing implementation and design.

- Write or re-write the business logic and data logic (DAO) classes with DI pattern. Create the Spring context XML file for the business and DAO classes. Inject the business logic objects into the Action classes using any Spring Context.

- After refactoring the existing code enabling Dependency Injection, second step is to prepare the Struts action classes to integrate with Spring. In this case the same DI needs to be enabled in the Action classes. The Action class shouldn't be burdened with redundant logic codes other than controlling logics. Use the Delegation Proxy to create the Struts Action classes through Spring. Before that ensure that the injection of

- Remove all logging cross-cut codes from the classes and use Spring Interceptor (BeforeMethod advice) and implement the logging

- To manage the application's transaction using Spring declarative transaction, implement it through proxy. The transaction declaration needs more time to analyze rather than implement. Do the homework on transaction grouping and then implement it in the xml file. Rigorously testing requires to confirm functional and performance requirements.

Struts-Spring Integration Using Proxy

DelegatingActionProxy is the object that plays the role to create Struts Action class when the request is invoked.

1. Modify your struts-config.xml file to give the DelegatingActionProxy to play its role

path="/someAction" name="someForm"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/someOtherAction.do">


2. Add an entry for the path, in this case, '/someAction' in the spring configuration




Open View in transaction in Spring with Hibernate

1. Create a Filter to handle the transaction:


AppFilter</filter-name>
Application Transaction Filter

org.springframework.web.filter.DelegatingFilterProxy



2. Set the Filter to accept any request ends with .d0

AppFilter
*.


3. Set the Listener that loads Spring's WebAppContext


org.springframework.web.context.ContextLoader


4. set the parameter value of the configuration file that configures the Transaction Filter and Transaction Manager


contextConfigLocation

/WEB-INF/WebContext.xml



5. Configure the Filter










6. Implement the Filter class

DefaultTransactionDefinition def = new DefaultTransactionDefinition();

if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}

status = transManager.getTransaction(def);
chain.doFilter(req, res);

//commit
getTransactionManager().commit(status);
//rollback
getTransactionManager().rollback(status);

//Close the Session
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(session);


Resources:

http://springtips.blogspot.com/ - Spring tips
Spring-Struts integration - Spring integration with Struts Action
Spring transaction blog - A compact discussion of spring transaction implementation

Useful RAD keyboard shortcuts

I used Rational Application Developer (RAD 7.0) to test the below keyboard shortcuts. All of the shortcuts are for the Java/J2EE perspectives:

Editor

Ctrl+M -> Maximize/Minimize the current editor

Ctrl+W -> Close the current editor

Ctrl+E -> Show all editor

Ctrl+D -> Delete line from cursor position

Ctrl+T -> Open the Type, if on method or class then shows the available subtypes

Cntrl+O -> Open the members

Ctrl+Shift+F6 -> Show available Editors

Ctrl+Shift+F7 -> Show available views (need to check)

Ctrl+Shift+F8 -> Show available perspectives (need to check)

Alt+ Arrow keys -> move forward/backword to the last change position

F12 -> Activate the editor

F3 -> Open the declaration

Cntrl+Shift+M -> Add import statement for the Class used in the code (shows error as underline red
                            for the class used but not imported the class i.e. import statement isn't written
Cntrl+Shift+O -> Organize the import statements i.e. if you've removed some classes from your
                            code but the important statement wasn't deleted this command will clean up those
                            unused  import statements

Cntrl + F4 -> to close the currently active tab on the Editor


Search

Cntrl+Shift+R -> Search for Resources

Cntrl+Shift+T -> Search for Types

Cntrl+K -> Go to the next search result

Cntrl+Alt+H -> Show the call hierarchy of a method (highlight on the method you want to see the call trace)

Cntrl+Shift+H -> To search for Java Classes (Type)


Code structure change


Alt+Shift+R -> Rename (refactor) of class/member


Note: To change the keyboard shortcut mapping, go to Windows -> Preferences -> Workbench -> Keys

Best practices in software development

These are the compiled list of practices that I believe really help a software engineer to be efficient as well as optimally utilizing the skills and resources.

1. Write the initial plan at the beginning of the day. At the end of the day, update the status of your planned activities. It helps to:
  • Assess how effective and efficient you are.
  • Reduce the number of items (sometimes insignificant) forgotten.  [Planning]
2. Give preference to written communication instead of verbal communication. [Collaboration]

3. Keep a notebook with you. Write what you think, what you listen or what you are asked to do. [Planning]

4. Visually represent your idea. Use UML to represent your idea. This would help you to identify shortcoming of your solution and also increase your image to the team members. [Design]

5. While implementing/coding a logic, never derive the business logic from data. Even though it may look like that the change in the data is very unlikely and also controlled through your code, don't assume that it'll remain such down the line. Always use the true business indicators such as "flag", "state", "category" etc. to write your business logic. Some of the dead wrong software logic are: to identify a user as a Sales user, checking the value of  the "commission" attribute; if an employee has direct reporting employees to determine if that employee is a manager. Rather, use appropriate flag or indicator if the person is a sales person or a manager. [Coding]

6. Always document your assumptions. Never assume that people will remember your assumptions; you may yourself forget your assumptions in few weeks, if not months. [Planning]

7. When you're asked to provide a ball park figure for the effort of implementing a feature, try to provide a range of effort estimation rather a concrete number; and if you can afford, mention the assumptions that you've made to estimate the effort. [Planning]

9. Never trust that user will provide data to the application in the case (upper case or lower case) you expect. This is specially true when you use the data to compare against a database table or against string literals in the code. The bottom line is to compare in case insensitive manner.
e.g. to check a user while logs in if the user exists, compares the user id in case insensitive manner or convert into upper case on both side of the expression. It will save you days in debugging production issues. [Coding]

10. Testing of software has to be verifiable. This can be identified summarize into the simple statement: Test result should be verifiable. The soul purpose of this principle is to make sure that every steps of testing in the software are verifiable which would have profound impact on the quality of testing. This would alleviate the controversy of "this was working before" symptom. [Testing]

11. Prefer database over file to keep the application configuration. It's always easier to access and modify the database than a file within the deployed application. Some example of benefits of using database are: easy to query, easy to create report, usually doesn't need application downtime (unless designed badly), corporate production environment is less stringent to database change than application file change, etc. [Design, Coding]

12. Never hardcode the deployment infrastructure in the application. You never know what would be the next deployment infrastructure your application would get. Also, never use IP address, physical server name, database server name, etc. in your application. Always use virtual names that could be mapped to that physical environment [Design]

Wednesday, November 7, 2007

Useful vi commands

Useful vi Commands

0. :q -> quit ; :w -> write the change ; :q! -> quite anyway without saving ; :qw -> quite after saving the changes

1. yw -> yank (copy) a word
2. yy -> copy the current line
3. yG -> copy from cursor to EOF
4. 2y -> copy 2 lines from cursor
5. y2w -> copy 2 words from cursor
6. p/P -> copy before or after cursor

7. :set number -> see the line numbers
:set nonumber -> hide the line numbers
8. :set list -> show the newline character
:set nolist -> hide the newline character

9. :%s/search-text/replace-text/g -> Search and replace text with greedy option set
10. /search-text -> search any text and then press n to search next or ? to search previous

11. Ctrl+f -> to move one screen forward
12. Ctrl+b -> to move one screen backward

13. :line_number -> to go to the specified line number

14. * (Shift+8) -> Hightlight the word at the cursor position and search for next match
:noh to remove the highlight
15. :e -> Open another file to edit

16. :J -> Join the line with next line giving a space in between

17. : %s/^I/\r/g -> Replace all with ; works on gVim
: %s/
^I/^M/g -> to achieve the same in unix vi. To get '^M', use Ctrl+v first then hit enter.
: %s/\m/,/g -> insert ',' between each character. Works on gVim
: %s/\n/,\r/g -> replace the new line (\n) using ',' and carriage return (\r) . works on gVim
: %s/.*ABCD/ABCD/g -> replace words from beginning of line up to word 'ABCD' and replace that with only word 'ABCD'
e.g. "10/17/2008 11:55 AM 229,888 ABCD XY - FOO - 1.0"
becomes "ABCD XY - FOO - 1.0"
:'<, '>s/^^I/&A/g -> replace all tabs from beginning of the line with A (the selected lines only)
:%s/^^I/&A/g -> Same as above without any selection
:%s/\s*$// -> replace all trailing white spaces

18. vEU -> change from the cursor to end of word to uppercase
v$U -> change from the cursor to end of line to uppercase
vEu -> change from the cursor to end of word to lowercase
v$u -> change from the cursor to end of line to lowercase

19. u -> undo delete
U -> undo the last change
Ctrl+r -> Redo the last change

20. : -> to recall history

21.: & -> repeat last :s command
: . -> repeat last text changing command
: , -> repeat last search command. In gVim use 'n'


22.
M -> Move to the middle of the current screen
H -> Move to the top of the current screen
0 -> Beginning of current line
+/Return -> First character of next line
dL -> Delete up to last line on the screen
D -> Delete remainder of the current line
"xyy -> copy current line to buffer x
"xp -> copy the line from buffer x

23. Vertical selection and insertion
^v to start vertical selection
press 'I' or 'i' then enter any letter you want to append and finally press escape.

24. Delete lines with search result
g/string/d - Delete lines that contains the 'string'
v/string/d - Delete lines that DOESN'T contain the 'string'

25. Sort a file
:sort

26. Counting words
:%s/pattern//gn - Count the pattern
:%s/[^ ]\+//gn - Count the space delimited words

27. Recording
Hit q and register character (alphanumeric) e.g. x
Hit q again to stop recording
@x to rerun the recorded keystroke recorded

28. Find next key word
i (insert mode) -> Ctrl -> i
this would show the keywords as drop down values to be picked for


Resources:

http://www.brezeale.com/technical_notes/vim_notes.shtml
http://www.rayninfo.co.uk/vimtips.html
https://xyz.pp.se/~thnov/vi.html
http://www.lagmonster.org/docs/vi2.html
http://www.unix-manuals.com/refs/vi-ref/vi-ref.htm
http://vim.wikia.com/wiki/Vim_Tips_Wiki - Vim tips wiki

Tuesday, November 6, 2007

The simplest way to create an executable jar in java

The simplest way to create an executable jar in java.

1. Create the MANIFEST.MF file. Add the Main-Class in the manifest file:
Main-Class: Main

2. Create the jar file
jar cvfm factor.jar MANIFEST.MF *.class com gnu

3. Execute the Main class from the executable jar
java -Xms512m -Xmx512m factor.jar

Note: The Class-Path: entry doesn't work, at least in jdk 1.4 as expected i.e. it doesn't load the jar file into the classpath. The Class-Path only inform the java command to search the libraries in the relative location from the current directory. So if the jar files can be found in the location mentioned in the Class-Path: entry, then it works