Not enough arguments [nsIDOMWindowInternal.alert]




function callfn()
{
alert();
}





This will give error somewhat similar to

uncaught exception: [Exception… “Not enough arguments [nsIDOMWindowInternal.alert]” nsresult: “0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)” location: “JS frame :: http://rae.us.playstation.com/raeus/ps3/index.htm :: :: line 810” data: no]

Please note that this error appears specifically in Firefox. (Not sure about other browsers).

Source : http://www.sitepoint.com/forums/showthread.php?t=182241


JSON, AJAX and jQuery

Today I was working on JSON.
1) Requirement was to get the data from a server in a JSON object. Store it into request object.
2) And on an HTML page, it was required to fire an AJAX request, get the data from the Servlet created in step 1.

3) When i fired a request to servlet directly in browser window, it used to print JSON object that it returns. But when i make a request thru AJAX call… the data is never displayed.

SOLUTION/MISTAKE:

JSON object must follow the structure of the JSON object.
You cannot add any extra println in the resulting JSP. It must ONLY and ONLY print JSON object.

You can validate your JSON from www.jsonlint.com

See more : http://api.jquery.com/jQuery.ajax/




Can singleton be broken?

Singleton pattern
The most common code for creating a singleton pattern is as follows:

Code 1:

public class SingletonSample {
private static SingletonSample instance;
private SingletonSample(){}
public static SingletonSample getInstance() {
if (instance == null) // 1
{instance = new SingletonSample();} // 2
return instance; // 3
}
}

In the above design, the constructor is declared as private and the getInstance() method ensures that only a single object is created. This program will work well for single threaded program. But however, for multithreaded programs this pattern will fail inconsistently. Let’s have a look at how and where this pattern will fail.

a) Thread 1 enters the getInstance() method and determines that instance variable is null at line // 1.
b) Thread 1 enters if block but is pre-empted by thread 2 before executing line // 2.
c) Thread 2 calls getInstance() method and determines instance variable is null at line //1.
d) Thread 2 enters the IF block and creates a new object which is assigned to instance.
e) Thread 2 then returns the Object reference at line // 3.
f) Thread 2 is pre-empted by thread 1.
g) Thread 1 starts off where it left and creates another object at line // 2 and returns the reference at // 3.

Thus two Objects of the class are created when it was required to generate only one. A “synchronized” keyword is used to make multithreaded application thread safe and hence so, if we want to use the singleton pattern in multithreaded application we must synchronized the getInstance() method as follows :

Code 2:

synchronized public static SingletonSample getInstance() {
if (instance == null) // 1
{instance = new SingletonSample();} // 2
return instance; // 3
}

The above code works fine for multithreaded access to getInstance() method but on deeper analysis we find that the ‘synchronization’ is actually required only for the first invocation as only on the first invocation will the line // 2 be actually executed, which also happens to be the line which needs to be synchronized. All other invocation apart from the first will get a not-null value and return the reference. However, it also adds up to performance issue as the complete getInstance() method is synchronized and that any other invocation will have to wait for the lock to be released to execute the getInstance().

Hence, in order improve the performance we can wrap up the line // 2 in a synchronized block instead of the complete method as follows

Code 3:

public static SingletonSample getInstance() {
if (instance == null) // 1
synchronized(SingletonSample.class){instance = new SingletonSample();} // 2
return instance; // 3
}

However, in the above code too, we face the same problem as we had in code 1.Two threads can enter the IF block after finding instance is null. Now, Thread 1 enters the ‘synchronized’ block and creates the Object. Thread 2 also enters the synchronized block after Thread 1 releases the lock and also creates one more object. Now, in this case the Thread 2 does not check for the instance==null and directly creates a second Object.
Double-checked locking
A way to fix the problem in Code 3 is to put one more check, a second check on instance variable as follows:

Code 4:

public static SingletonSample getInstance() {
if (instance == null)
synchronized(SingletonSample.class){ // 1
if(instance==null) // 2
instance = new SingletonSample(); // 3
}
return instance;
}

Thus by implementing the second check on instance variable makes it impossible for creation of more than one SingletonSample objects.
Since, this design uses two checks it’s called as “Double-checked locking”. Consider the following scenario.

a) Thread 1 enters the getInstance() method and the synchronized block at line as instance is null.
b) Thread 1 is pre-empted by thread 2.
c) Thread 2 enters the getInstance() and tries to acquire lock at // 1 as instance is still null but fails because Thread 1 already has a lock on the Object.
d) Thread 2 is pre-empted by Thread 1.
e) Thread 1 then executes line //2 and line // 3 to create an Object as instance is still null at line // 2.
f) Thread 1 is pre-empted by thread 2 and acquires a lock at line // 1.
g) Thread 2 does a null check at line // 2 and after finding that it is not null exits the block without creating a new Object.

Now, finally we can conclude that we are able to generate a single instance at last. But can we really do that? Let us have a look at the code 4 line 3 again. The problem with this line is that instance can become non-null even before the constructor executes completely. Let’s look at the following flow.

a) Thread 1 enters the getInstance() and the synchronized block at line // 1 as instance is null.
b) Thread 1 executes the code at line // 3. Now after the fully creating the Object but BEFORE the initializing the object.
c) Thread 1 is pre-empted by thread 2.
d) Thread 2 checks to see if instance is null. Because it is not, thread 2 returns a reference to a fully constructed but partially initialized Object.
e) Thread 2 is pre-empted by thread 1.
f) Thread 1 completes the constructor and initializes the object and returning the reference.

Solution
This problem is because of the Java memory problem and hence the solution to the above problem is to use synchronized getInstance() as in Code // 2 or static as follows :

public static Singleton getInstance()
{
return instance;
}

Reading files made easy in Java

Courtesy : http://code.hammerpig.com/how-to-read-really-large-files-in-java.html

import java.util.*;
import java.io.*;

public class BigFile implements Iterable
{
private BufferedReader _reader;

public BigFile(String filePath) throws Exception
{
_reader = new BufferedReader(new FileReader(filePath));
}

public void Close()
{
try
{
_reader.close();
}
catch (Exception ex) {}
}

public Iterator iterator()
{
return new FileIterator();
}

private class FileIterator implements Iterator
{
private String _currentLine;

public boolean hasNext()
{
try
{
_currentLine = _reader.readLine();
}
catch (Exception ex)
{
_currentLine = null;
ex.printStackTrace();
}

return _currentLine != null;
}

public String next()
{
return _currentLine;
}

public void remove()
{
}
}
}

Here is how you might use it:

BigFile file = new BigFile("C:\Temp\BigFile.txt");

for (String line : file)
System.out.println(line);

How to read a file in Java

Usually such kind of function is not recommended when reading huge files. Because it is not possible for java to allocate so much contiguous memory.

As far a possible, avoid using this function.

public static String getFile(String filepath) 
{
        StringBuilder output = new StringBuilder("");
        try 
        {       
            File file = new File(filepath);
            FileReader fileReader = new FileReader(file);
            BufferedReader bfr = new BufferedReader(fileReader);
            String line ;
            while((line = bfr.readLine()) != null)
            {
                output.append(line + "n");
            } 
            bfr.close();
            fileReader.close();
        }
        catch (FileNotFoundException e) 
        {
              e.printStackTrace();
        } 
        catch (IOException e) 
        {
              e.printStackTrace();
        }   
        finally
        {
            
        }
        return output.toString();
}

How to put limitation of time on a method call

Lets say, you are reading a website, and you want that, if you get a response within 3 seconds then its ok..
otherwise, you want to give a message to user that internet is tooo slow…how will you do it…

I always wondered it…today found a solution…Not tooo complex, its just that, i was not able to develop this logic using my own knowledge of java. 🙂

This is just an example:
Declare a private Thread mainThread;

final int factorialOf = 1 + (int) (30000 * Math.random());
System.out.println("computing " + factorialOf + '!');

Thread testThread = new Thread() {

public void run() {
System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf));
//Now run method has completed its execution
// so it should interrupt the main Thread
mainThread.interrupt();
}
};
mainThread=Thread.currentThread();
testThread.start();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
// If we reach here, that means sleep was interrrupted before 1000 ms.
}
testThread.interrupt();

if (testThread.isInterrupted()) {
throw new TimeoutException("the test took too long to complete");
}

PS: Though this should work, but some time is being taken by the statements which create new thread.

Some other/better methods are also given here : http://javakafunda.blogspot.in/2012/05/how-to-put-time-restriction-on-method.html


Add zooming effect to images on your website

You must have wondered, how to add zooming effect to an image.
Its pretty simple to do….

A simple attribute of has the capbility of doing it

<img src="http://www.celebrity-pictures.ca/Celebrities/Katrina-Kaif/Katrina-Kaif-i105058.jpg" 

onmousedown="this.height=450;this.width=600"

onmouseup="this.height=150;this.width=200" width=200 height=150>

Output :

Here are few of the event handlers :

Attribute Description
onabort Script to be run when loading of an image is interrupted
onclick Script to be run on a mouse click
ondblclick Script to be run on a mouse double-click
onmousedown Script to be run when mouse button is pressed
onmousemove Script to be run when mouse pointer moves
onmouseout Script to be run when mouse pointer moves out of an element
onmouseover Script to be run when mouse pointer moves over an
element
onmouseup Script to be run when mouse button is released
onkeydown Script to be run when a key is pressed
onkeypress Script to be run when a key is pressed and released
onkeyup Script to be run when a key is released

If you want a effect that gradually grows the image, you can refer to the link : http://javascript.internet.com/image-effects/growing-image.html


Rules about classpath

Source : http://mindprod.com/jgloss/classpath.html

Rules About Classpaths

  1. Simply copying or moving your jar files to the ext directory pointed to by the system property java.ext.dirs =C:Program Filesjavajre6libext automatically puts them on the classpath without having to mention them explicitly. This is a great way to prune back an overblown classpath. It is safest to put your jars in all the ext directories:
    where to look for ext directories :

    You never know for sure where your javac.exe or java.exe is going to look. Grrr. You can change the location of the

    java.exe -Djava.ext.dirs=C:mylibs mypackage.MyClass

    See the ext dirs entry for details.

  2. Class names are always fully qualified with the complete package name. There is no way to ever abbreviate the higher levels.
  3. Each element of the CLASSPATH provides a starting point to look for a fully qualified package and class name, identical to the way it appeared in the package or import statement.
  4. If the element of the CLASSPATH is the name of a directory, Java will look in that tree for directory names matching the package name structure. It looks at one place only. It does not search. The class file sought must be filed under the one and only precise fully qualified pathname, or it won’t be found. It wants to find a *.class file (or*.java file), at the precisely correct spot in the directory tree. You must get an exact match on the fully qualified name. The name of the directory specified in the CLASSPATH itself is totally immaterial in determining the package name.
  5. If the element of the CLASSPATH is a jar, Java will look in the internal directory structure of the jar for an exact match on the fully qualified name. It looks; it does not search. The class file sought must be filed under the one and only precise fully qualified pathname, or it won’t be found. The location of the jar is totally immaterial in determining the name of the package. If you peek inside the jar with WinZip you should see pathnames on each class file matching the package structure. Download and examine any of my jars and the corresponding source to see how it works.
  6. An alternative, ultimately more confusing way of looking at it, is that you specify part of the operating system’s name for a class file in the CLASSPATH and part in the package name. Java source imports and package statements, javac.exe and java.exe command lines specify only the fully qualified package name, not the higher order part handled by the CLASSPATH. The higher levels that are handled by the CLASSPATH (which could appear on the command line via -classpath option), are effectively invisible to your Java programs. However, you are not at liberty to shuffle levels of qualification between your import and classpath unless you adjust all your package statements and recompile as well.