Oracle connection with JDBC – JNDI

January 14, 2009 · Posted in java, oracle · Comment 
  1. Using JNDI
    javax.naming.Context context = new
    javax.naming.InitialContext();
    javax.sql.DataSource ds =  (
    javax.sql.DataSource) context.lookup("java:comp/env/jdbc/XXXJNDINAMEXXX");
    java.sql.Connection con = ds.getConnection();

Hibernate get distinct list with Criteria

April 3, 2008 · Posted in hibernate, java · Comment 

The only way I could figure out to get the distinct list using Hibernate Criteria is by using ResultTransformer function.

eg.

List result = session.createCriteria(Order.class)
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
        -------
        .list();

The con is it fetches all the objects and then filters it. (very time consuming)

The only way to circumvent this problem is to write query using HQL.

If you find a way to do that efficiently using Criteria, let me know :)

java replaceAll error

March 12, 2008 · Posted in java · Comment 

public String replaceAll(String regex, String replacement)

This method works fine if replacement string does not contain ‘$’ or ‘/’ characters.If replacement string contains these characters, the results can be in-accurate.

Fix: Use Matcher.quoteReplacement(replacement)

public String replaceAll(String regex,
        Matcher.quoteReplacement(replacement))

java.net.SocketException: Too many open files

January 18, 2008 · Posted in java, linux · 1 Comment 

For System Wide settings
To see the settings for maximum open files for the OS level, use following command.
cat /proc/sys/fs/file-max
This should be a value from 36000 to 50000 or more. To increase the system wide maximum open files, as root edit the /etc/sysctl.conf and add the following to the end of the file.

Note: The following example will increase the maximum number of files to 49,500 on your currently running system and will persist after rebooting.

fs.file-max = 49500

Then issue the following command to activate this change to your live system.
sysctl -p

For user level setting

Also, you should update /etc/security/limits.conf for the user.

myuser hard nofile 2048
myuser soft nofile 2048

Type this to see what it’s set at:

ulimit -a

Weak References

October 24, 2007 · Posted in java · 1 Comment 

for original post go here.

Strong references

First I need to start with a refresher on strong references. A strong reference is an ordinary Java reference, the kind you use every day. For example, the code:

StringBuffer buffer = new StringBuffer();

creates a new StringBuffer() and stores a strong reference to it in the variable buffer. Yes, yes, this is kiddie stuff, but bear with me. The important part about strong references — the part that makes them “strong” — is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don’t want the garbage collector destroying objects you’re working on, this is normally exactly what you want.

When strong references are too strong

It’s not uncommon for an application to use classes that it can’t reasonably extend. The class might simply be marked final, or it could be something more complicated, such as an interface returned by a factory method backed by an unknown (and possibly even unknowable) number of concrete implementations. Suppose you have to use a class Widget and, for whatever reason, it isn’t possible or practical to extend Widget to add new functionality.

What happens when you need to keep track of extra information about the object? In this case, suppose we find ourselves needing to keep track of each Widget’s serial number, but the Widget class doesn’t actually have a serial number property — and because Widget isn’t extensible, we can’t add one. No problem at all, that’s what HashMaps are for:

serialNumberMap.put(widget, widgetSerialNumber);

This might look okay on the surface, but the strong reference to widget will almost certainly cause problems. We have to know (with 100% certainty) when a particular Widget’s serial number is no longer needed, so we can remove its entry from the map. Otherwise we’re going to have a memory leak (if we don’t remove Widgets when we should) or we’re going to inexplicably find ourselves missing serial numbers (if we remove Widgets that we’re still using). If these problems sound familiar, they should: they are exactly the problems that users of non-garbage-collected languages face when trying to manage memory, and we’re not supposed to have to worry about this in a more civilized language like Java.

Another common problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.

Because an image cache is supposed to prevent us from reloading images when we don’t absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you (just as above) to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. Once again you are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory.

Weak references

A weak reference, simply put, is a reference that isn’t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself. You create a weak reference like this:

WeakReference weakWidget = new WeakReference(widget);

and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn’t strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.

To solve the “widget serial number” problem above, the easiest thing to do is use the built-in WeakHashMap class. WeakHashMap works exactly like HashMap, except that the keys (not the values!) are referred to using weak references. If a WeakHashMap key becomes garbage, its entry is removed automatically. This avoids the pitfalls I described and requires no changes other than the switch from HashMap to a WeakHashMap. If you’re following the standard convention of referring to your maps via the Map interface, no other code needs to even be aware of the change.

Reference queues

Once a WeakReference starts returning null, the object it pointed to has become garbage and the WeakReference object is pretty much useless. This generally means that some sort of cleanup is required; WeakHashMap, for example, has to remove such defunct entries to avoid holding onto an ever-increasing number of dead WeakReferences.

The ReferenceQueue class makes it easy to keep track of dead references. If you pass a ReferenceQueue into a weak reference’s constructor, the reference object will be automatically inserted into the reference queue when the object to which it pointed becomes garbage. You can then, at some regular interval, process the ReferenceQueue and perform whatever cleanup is needed for dead references.

Different degrees of weakness

Up to this point I’ve just been referring to “weak references”, but there are actually four different degrees of reference strength: strong, soft, weak, and phantom, in order from strongest to weakest. We’ve already discussed strong and weak references, so let’s take a look at the other two.

Soft references

A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.

SoftReferences aren’t required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming.

Phantom references

A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can’t even retrieve the object — its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?

The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be “resurrected” by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to “resurrect” an almost-dead object.

What good are PhantomReferences? I’m only aware of two serious cases for them: first, they allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that. This isn’t generally that useful, but might come in handy in certain very specific circumstances like manipulating large images: if you know for sure that an image should be garbage collected, you can wait until it actually is before attempting to load the next image, and therefore make the dreaded OutOfMemoryError less likely.

Second, PhantomReferences avoid a fundamental problem with finalization: finalize() methods can “resurrect” objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was “resurrected” during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

With PhantomReference, this situation is impossible — when a PhantomReference is enqueued, there is absolutely no way to get a pointer to the now-dead object (which is good, because it isn’t in memory any longer). Because PhantomReference cannot be used to resurrect an object, the object can be instantly cleaned up during the first garbage collection cycle in which it is found to be phantomly reachable. You can then dispose whatever resources you need to at your convenience.

Arguably, the finalize() method should never have been provided in the first place. PhantomReferences are definitely safer and more efficient to use, and eliminating finalize() would have made parts of the VM considerably simpler. But, they’re also more work to implement, so I confess to still using finalize() most of the time. The good news is that at least you have a choice.

for original post go here.

How to Zip a folder in Java

September 18, 2007 · Posted in java · 1 Comment 

Using the in-built zip function of java, attached is a sample code to copy a folder and all its sub-folders into a zip file.

Java Program to Zip a folder

This program uses Commons IO – IOUtils library to copy files.

How to check GMail RSS/Atom feed

September 17, 2007 · Posted in java · 1 Comment 

Google provides a feed url to check your new mail(s) in your inbox. The url is https://gmail.google.com/gmail/feed/atom.

You would need to authenticate first with your gmail username and password and it will list the unread email(s).

I was reading about Rome and thought to write a small program utilizing its features to read my gmail feed. Attached is the java program to read the gmail feed.

Let me know if you have any comments.

ActionForm – Reset multiple list <html:select multiple=”true”>

August 17, 2007 · Posted in struts · Comment 

Struts uses ActionForm to both populate a HTML form, and then to capture the parameters when a form is submitted.

When a request is submitted, the ActionServlet matches the URI for the request against the path of an action-mapping. If there is a form-bean for that action-mapping, it looks for an ActionForm under the form-bean name. If it doesn’t find one, a new one is created. The ActionServlet then calls reset() on the new or pre-existing ActionForm and populates it from the request. If the action-mapping has validate set to true, the ActionServlet calls the validate method. If this returns any error messages, the ActionServlet forwards to the URI indicated by the action-mappings error property. This is often a JSP, but it can also be another action-mapping. The latter being needed when there are drop-down controls to populate and so forth. If there are no errors, the ActionServlet passes the (populated and validated) ActionForm to the Action indicated by the action-mapping element.

If you have a form with say a multiple select list, when you unselect items from the list and submit, the ActionForm class would not empty the collection. The easy way to fix it is by writing your own reset() method in which you simply initialize or empty the collection.

Validate e-mail address with regular expression

August 2, 2007 · Posted in java, javascript · Comment 

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

All regular expressions start and end with forward slashes to differentiate them from ordinary string expressions. Most regular expressions start matches at the first character ^ and end at the last $.

Now we try to match the mailbox name which can include periods and dashes \w+ states one or more alphanumeric must be at the start of the name. ([\.-]?\w+)* allows periods or dashes to be included in the mailbox name with the trailing \w+ ensuring that those characters can not finish the name. The @ is the mandatory separator.

The domain name can have several .xx or .xyz suffixes such as .com.uk. Once again \w+ ensures that domain starts with an alphanumeric and ([\.-]?\w+)* allows for the dashes and periods. Finally (\.\w{2,3})+ ensures that there is at least one suffix of between 2 and 3 characters preceded by a period.

Note: This is not a completely foolproof validation as it does not account for new domain names of 4 or more characters. Also not all two and three letter combinations are legitimate domains!

Displaying a wait page for a struts action

June 4, 2007 · Posted in java, struts · Comment 

I was searching google to find a way to show a wait page when a struts form is submitted and the response is loaded. Sometimes it is required when the page has to process a lot of information or get huge amount of data from the database.

I found a really clean way to do so at http://wiki.apache.org/struts/StrutsPleaseWait .

Next Page »