Wednesday, December 21, 2011

Extract Numbers from a String

public static List extractNumsFromStr(String line) {
List numbers = new ArrayList();
Long no;
String number = null;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(line);

while (m.find()) {
number =;
no = Long.parseLong(number);
return numbers;

Thursday, November 10, 2011

Convert XML file To String object

The following code will read the XML from file specified as method argument, and will return the String object containing the XML file contents, null otherwise.

public static String convertXMLFileToString(String filePath) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(filePath));
org.w3c.dom.Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stwriter = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(document), new StreamResult(stwriter));
return stwriter.toString();
} catch (Exception e) {
return null;

Wednesday, September 28, 2011

MySql LOAD_FILE Function


It’s built in MySql String function that reads a file from server host and returns the contents of file as string. If file can’t read or doesn’t exist then this function will return NULL.

Important Points:

  • è Must pass the full path name to the file as parameter
  • è User must have the FILE privilege
  • è File must be readable
  • è Size of file must be less than max_allowed_packet in bytes. Default is (1048576 bytes). Its range is 1024 – 1073741824
  • è If system variable named secure_file_priv is set to a non empty directory, then the file must be located in the directory specified by this system variable. Its advisable to set this variable to the source directory for your file, otherwise there is a risk for LOAD_FILE Injection. If you want to check the current value for this system variable you can simply use the command:
mysql>SELECT @@secure_file_priv;


Mysql> UPDATE SET blob_column_name = LOAD_FILE(‘/tmp/picture’) WHERE id = 1;

Friday, September 16, 2011

Java Puzzle Animal Farm

Readers of George Orwell's Animal Farm may remember old Major's pronouncement that "all animals are equal." The following Java program attempts to test this pronouncement.

What does it print? and Why?

public class AnimalFarm {
public static void main(String[] args) {

final String pig = "length: 10";
final String dog = "length: " + pig.length();

System.out.println("Animals are equal: "+ pig == dog);



A superficial analysis of the program might suggest that it should print Animals are equal: true. After all, pig and dog are both final String variables initialized to the character sequence "length: 10". In other words, the strings referred to by pig and dog are and will forever remain equal to each other. The == operator, however, does not test whether two objects are equal; it tests whether two object references are identical. In other words, it tests whether they refer to precisely the same object. In this case, they do not. You may be aware that compile-time constants of type String are interned [JLS 15.28]. In other words, any two constant expressions of type String that designate the same character sequence are represented by identical object references. If initialized with constant expressions, both pig and dog would indeed refer to the same object, but dog is not initialized with a constant expression. The language constrains which operations are permitted to appear in a constant expression [JLS 16.28], and method invocation is not among them. Therefore the program should print Animals are equal: false, right?

Well, no, actually. If you ran the program, you found that it prints false and nothing else. It doesn't print Animals are equal: . How could it not print this string literal, which is right there in black and white? The + operator, whether used for addition or string concatenation, binds more tightly than the == operator. Therefore, the parameter of the println method is evaluated like this:

System.out.println(("Animals are equal: " + pig) == dog);

The value of the boolean expression is, of course, false, and that is exactly what the program prints. There is one surefire way to avoid this sort of difficulty: When using the string concatenation operator, always parenthesize nontrivial operands. More generally, when you are not sure whether you need parentheses, err on the side of caution and include them. If you parenthesize the comparison in the println statement as follows, it will produce the expected output of Animals are equal: false:

System.out.println("Animals are equal: " + (pig == dog));

Arguably, the program is still broken. Your code should rarely, if ever, depend on the interning of string constants. Interning was designed solely to reduce the memory footprint of the virtual machine, not as a tool for programmers. As this puzzle demonstrates, it isn't always obvious which expressions will result in string constants. Worse, if your code depends on interning for its correct operation, you must carefully keep track of which fields and parameters must be interned. The compiler can't check these invariants for you, because interned and noninterned strings are represented by the same type (String). The bugs that result from the failure to intern a string are typically quite difficult to detect.

When comparing object references, you should use the equals method in preference to the == operator unless you need to compare object identity rather than value. Applying this lesson to our program, here is how the println statement should look. It is clear that the program prints True when it is fixed in this fashion:

System.out.println("Animals are equal: " + pig.equals(dog));

This puzzle has two lessons for language designers. The natural precedence of string concatenation might not be the same as that of addition. This implies that it is problematic to overload the + operator to perform string concatenation. Also, reference equality is more confusing than value equality for immutable types, such as String. Perhaps the == operator should perform value comparisons when applied to immutable reference types. One way to achieve this would be to make the == operator a shorthand for the equals method, and to provide a separate method to perform reference identity comparison, akin to System.identityHashCode.

Gang of Four (GOF) Design Patterns

The Gang of four (GOF) patterns are categorized into three main categories:

  • Creational:- Deals with the creation of objects. Following are the creational patterns:
  1. Factory
  2. Abstract Factory
  3. Factory Method
  4. Builder
  5. Prototype
  6. Singleton

  • Structural:- Deals with the relationships between portion of your application. Followings are the Structural patterns:
  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Facade
  6. Flyweight
  7. Proxy

  • Behavioural:- Deals with the state and behaviour flow through the system. Followings are the behavioural patterns:
  1. Chain of Responsibility
  2. Command
  3. Interpreter
  4. Iterator
  5. Mediator
  6. Memento
  7. Observer
  8. State
  9. Strategy
  10. Template Method
  11. Visitor

Thursday, September 15, 2011

New Features in Java version 7

The new release of Java 7 introduced exciting new features in the language; following is the list of these features:

  • Strings in the Switch Statement
For details please visit:
  • Type Inference for Generic Instance Creation (diamond symbol <>)
For details please visit:
  • The try-with-resources Statement
For details please visit:

  • Catching multiple Exception Types and Rethrowing Exception with Improved Type Checking
For details please visit:
  • Enhancements in Java I/O (new package named java.nio)
For details please visit:

  • Java Virtual Machine Support for Non-Java Languages
For details please visit:

  • JLayer Pane to Decorate Components with JLayer Class
For details please visit:

Wednesday, August 10, 2011

To Check Internet Explorer (IE) version

Little helper function to return details about IE 8 and its various compatibility settings either use as it is or incorporate into a browser object. Remember browser sniffing is not the best way to detect user-settings as spoofing is very common so use with caution.

function IEVersion(){
var _n=navigator,_w=window,_d=document;
var version="NA";
var na=_n.userAgent;
var ieDocMode="NA";
var ie8BrowserMode="NA";
// Look for msie and make sure its not opera in disguise
if(/msie/i.test(na) && (!_w.opera)){
// also check for spoofers by checking known IE objects
if(_w.attachEvent && _w.ActiveXObject){
// Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7
version = (na.match( /.+ie\s([\d.]+)/i ) || [])[1];
// Its IE 8 pretending to be IE 7 or in compat mode
// documentMode is only supported in IE 8 so we know if its here its really IE 8
version = 8; //reset? change if you need to
// IE in Compat mode will mention Trident in the useragent
ie8BrowserMode = "Compat Mode";
// if it doesn't then its running in IE 7 mode
ie8BrowserMode = "IE 7 Mode";
}else if(parseInt(version)==8){
// IE 8 will always have documentMode available
if(_d.documentMode){ ie8BrowserMode = "IE 8 Mode";}
// If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions
ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode=="CSS1Compat") ? 7 : 5;//default to quirks mode IE5

return {
"UserAgent" : na,
"Version" : version,
"BrowserMode" : ie8BrowserMode,
"DocMode": ieDocMode
var ieVersion = IEVersion();
var IsIE8 = ieVersion.Version != "NA" && ieVersion.Version >= 8;

if (!IsIE8) {
alert("Please upgrade to Internet Explorer 8 or better!" ) ;

Wednesday, July 13, 2011

Masking a HTML TextField as Numeric or Float

Add these functions to your JavaScript code under <script> tag.

function getKey(evt) { // works for IE, Netscape, Firefox, Opera, Chrome

var theEvent = evt || window.event;

var key = theEvent.keyCode || theEvent.which;

return key;


function MaskNumeric(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;



function MaskFloat(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46 || key == 110 || key == 190) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;



Then use the following code in your HTML form.

For Numeric Masked Field:

<input type="text" onkeypress="return MaskNumeric(event);" />

For Float Masked Field.

<input type="text" onkeypress="return MaskNumeric(event);" />

Wednesday, February 16, 2011

Passing Variable No of Arguments to Oracle Stored Procedure

If you want to pass variable number of arguments in a Oracle stored procedure, you can use array Type as stored procedure's parameter to accomplish this. Like in Java you can pass varargs as an array.

1- Create an Oracle nested table type in the database


2- Create a procedure in the database




FOR i IN nt.FIRST .. nt.LAST


INSERT INTO nt_test(id, description) VALUES (i, nt(i));


END nt_proc;


3- Create a test table, This is just for test purposes.

CREATE TABLE nt_test (id NUMBER, description VARCHAR2(30));

4- Create a module which defines the array of values


nt nt_type := nt_type(); -- nested table variable initialized to empty


nt := nt_type('Chester','Swindon','Corby','London','Swansea','Cardiff'); -- create your string of variables here




SELECT * FROM nt_test;

Monday, February 14, 2011

Renaming Foreign Keys

There is an Oracle DDL command which will rename a Foreign Key constraint:
SQL>ALTER TABLE <tablename> RENAME CONSTRAINT <foreign_key> TO <foreign_key_new_name>;
I have written an Oracle stored procedure which shows how this can be done:
CREATE OR REPLACE PROCEDURE rename_foreign_key(p_table_name IN VARCHAR2, p_foreign_key IN VARCHAR2, p_foreign_key_new VARCHAR2)
l_action VARCHAR2(2000) := NULL;
  CURSOR c_uc(p_table_name VARCHAR2, p_fk VARCHAR2, p_fk_new VARCHAR2)
    SELECT 'ALTER TABLE ' || uc.table_name || ' RENAME CONSTRAINT ' || uc.constraint_name || ' TO ' || p_fk_new
    FROM  user_constraints uc 
    WHERE uc.table_name = p_table_name
    AND   uc.constraint_name = p_fk
    AND   uc.constraint_type = 'R';
  OPEN c_uc(p_table_name, p_foreign_key, p_foreign_key_new);
  FETCH c_uc INTO l_action;
  CLOSE c_uc;
2) Example: create a master table DEPT and a child table EMP
dname VARCHAR2(14),
loc VARCHAR2(13));

ename VARCHAR2(10),
deptno NUMBER(2),

3) Find the generated name for the foreign key in the EMP table
SELECT constraint_name FROM user_constraints WHERE table_name = 'EMP' AND constraint_type = 'R' AND generated = 'GENERATED NAME';
  --> SYS_C0017017
4) Rename SYS_C0017017 to FK_EMP_DEPT
SQL> EXEC rename_foreign_key('EMP','SYS_C0017017','FK_EMP_DEPT')