skip to main | skip to sidebar

Thursday, November 15, 2012

Creating java.awt.Color instance using hex color codes

Most of you are familiar with java.awt.Color constructor which takes the RGB values to create its instance, but java.awt.Color class also allows one to create its instances using hex color codes through very less known static method ‘Color.decode(String)’.

 
Color obj = Color.decode("#006699");
 

Very simple isn’t it.
Read more »»

Tuesday, June 12, 2012

Changing Style tag content using JQuery & IE8

Generally you might not need/want to do this, in fact you’ll rarely change elements of ‘head’ tag using Java script. But this is for those who are left with no other choice. It is really simple, JQuery provides a methods ‘text() / html()’ which will allow you to change content of any DOM element. To change the ‘Style’ tag content we can use ‘text()’ method, sample code is provided below.

<html>
   <head>
      <style id="myStyles" type="text/css">
         .header {
            color: blue;
         }
      </style>
      <script type="text/javascript">
         $("#myButton").click(function(e) {
            $("#myStyles").text(".header { color: green }");
         });
      </script>
   </head>
   <body>
      <h2 class="header">My Page Heading</h2>
      <input type="button" id="myButton" value="Click Me"/>
   </body>
   </html>
 
Ideally you’d expect this code to work, but this code will not work in IE8; for some reason it seems you can not use ‘text()’ method to change ‘style’ tag contents in IE8. So work around for it - remove the ‘style’ completely and add it again with new content as shown below


<html>
   <head>
      <style id="myStyles" type="text/css">
         .header { color: blue; }
      </style>
      <script type="text/javascript">
         $("#myButton").click(function(e) {
            // $("#myStyles").text(".header { color: green }");
            var headerEl = $("#myStyles").parent();
            $("#myStyles").remove();
            $(headerEl).append("<style id='myStyles' type='text/css'> .header {color: green;}</style>");
         });
      </script>
   </head>
   <body>
      <h2 class="header">My Page Heading</h2>
      <input type="button" id="myButton" value="Click Me"/>
   </body>
</html>


To test follow this link: http://jsfiddle.net/tM96J/1/
Read more »»

Thursday, November 17, 2011

File Copy Using Java NIO

I wanted to post this small piece of code for those who are looking for it. Copying file contents using Streams is old way of doing, Java New IO is the way to go; using Java NIO is better in terms of performance.
Following is the code to do file copy using Java NIO.

public static void copyFile(File src, File dest) throws IOException {
    if (!src.exists()) {
        // either return quietly OR throw an exception
        return;
    }
    if (!dest.exists()) {
        dest.createNewFile();
    } 

    FileChannel source = new FileInputStream(src).getChannel();
    try {
        FileChannel destination = new FileOutputStream(dest).getChannel();
        try {
            source.transferTo(0, source.size(), destination);
            // destination.transferFrom(source, 0, source.size());
        } finally {
            if (destination != null) {
                destination.close();
            }
        }
    } finally {
        if (source != null) {
            source.close();
        }
    }
} 

By using NIO classes, we don’t need to create those byte buffers, loop through and copy in chunks, etc. NIO code is clean and simple, below line of code is the one responsible for copying file content.

source.transferTo(0, source.size(), destination); 

Quite simple isn’t it. It gets even simpler in Java7, all we need is one line of code as given below

Files.copy(src, dest);

// OR

Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

In the above line of code ‘src’ and ‘dest’ are not instances of java.io.File class, but they are of type "java.nio.file.Path". You can get Path object instance either by calling "toPath()" method on "java.iolFile" class object, OR creating one by calling the "getPath()" method on "java.nio.file.FileSystem" object.

FileSystems.getDefault().getPath("logs", "access.log");

The above line of code will give you an instance of ‘java.nio.file.Path’, which points to a file ‘access.log’ available in ‘logs’ directory, path is relative to current directory ["./logs/access.log"]. You can find more information @ http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html
Read more »»

Monday, July 18, 2011

JVM Heap Fragmentation

Recently I read about this topic and wanted to share it, I couldn’t recollect the source where I read it first to give a reference link, so just writing it here.
When JVM requires memory, Operating System always allocates continuous memory blocks. When objects get created and destroyed frequently, JVM allocates memory where ever available. Think of a situation where 1000 [each of size 5bytes] objects got allocated in some ‘x’ time span and only 500 of them are killed/de-allocated. Memory occupied by these 500 objects might not be continuous, the de-allocated memory might me scattered across heap memory. Each de-allocated block is of size 5bytes – so, you might be having free memory block of size 5bytes across heap, if JVM wants to allocate a 10byte memory block it cannot use these 5bytes blocks, it has to find a continuous 10byte free space in heap and allocate it. This situation is called as "Heap Fragmentation" [same as ‘Disk Fragmentation’], where the heap memory is fragmented. This results JVM not to release the continuous memory to Operating System.
Well, that is about the problem – how can we avoid it, here it is.
  • Identify places and avoid them where the objects are unnecessarily getting created and destroyed frequently.
  • Keep the maximum Heap memory Size setting to as close as possible to the maximum memory required by your JVM.
  • You can compact the Heap memory, using the JVM option "-compactGc", but remember that this option might result performance reduction.
That is all for now :)
Read more »»

Friday, July 15, 2011

Ant Script to make Executable JAR

Recently I observed search patterns about Ant script to make executable JAR files, many end up on wrong pages of my blog. This blog post is for those who are searching for it. Its fairly easy and simple to use Ant Script, to make an executable JAR file, see the script below.
<jar destfile="_dist/my-executable-jar.jar">
    <fileset dir="_bin" />
    …     <manifest>         <attribute name="Main-Class" value="com.mypackage.ClassWithMain" />     </manifest>
</jar>
As you can see, we usee the ‘jar’ ant task to create a JAR file, we want to create the JAR file with the name ‘my-executable-jar.jar’ – which is given as ‘destfile’ attribute value of ‘jar’ task and we wanted to include all the compiled classes which are available at ‘_bin’ directory – which is provided using ‘fileset’ tag in the second line of the script.
Then comes the important part – the ‘manifest’ tag. If you want to make a JAR file executable – you’ve to add a ‘Main-Class’ attribute to the MANIFEST file of your JAR file. As we wanted to specify an attribute of MANIFEST file – that is why the ‘manifest’ tag. In this tag we’ve a ‘attribute’ tag with ‘name’ and ‘value’ tag attributes. ‘name’ attribute says which attribute of the MANIFEST file you want to set and with which value, value is provided using ‘value’ attribute. In the above sample script we mentioned ‘Main-Class’ as attribute name and the value for this attribute as ‘com.mypackage.ClassWithMain’ – by this we are saying that the class which need to be used when we execute the JAR file is ‘com.mypackage.ClassWithMain’ [which means this class has the main() method and is the starting point for execution].
That is all – Happy Scripting :)
Read more »»

Wednesday, July 13, 2011

JAR Dependency and Ant Jar Task [Merging Archives]

Ever had a situation where you are using Ant to build a JAR file and this JAR uses classes from other JAR OR needs few other JAR files to be in class path. Placing dependent JARs in class path manually is one way of doing it, but what if you want to generate/deliver/use only one JAR [may be executable] which includes all the dependent JARs in it. ‘zipfileset’ attribute of the ‘jar’ ANT task is the one to use.
Say, you are trying to generate a JAR file with name ‘my-application.jar’, which needs/depends on another JAR with the name ‘some-dependency.jar’. Assuming all the compiled classes are available under ‘_bin’ directory, the dependent JAR is available under ‘lib’ directory and you want to place the generated JAR under ‘_dist’ directory, ANT script might look as given below
<jar destfile="_dist/my-application.jar">
    <fileset dir="_bin" />
    <zipfileset src="lib/some-dependency.jar" includes="**/*.class" excludes="META-INF/**/*" />
</jar>
That is all you need, only extra line you’ve is ‘zipfileset’ attribute. This attribute takes the JAR file [some-dependency.jar] to be added to the target JAR. You can mention what files from this JAR need to included OR excluded using the ‘includes’ and ‘excludes’ attributes. The above code says to include all ‘.class’ files and exclude all files under ‘META-INF’ directory.
What if you have more than one JAR to include, say all the JAR files under ‘lib’ directory, one way is to add multiple ‘zipfileset’ tag for each of those JAR files, if you’ve a big list of JARs under your ‘lib’ directory then, you can use the ANT script given below
<unjar dest="_unjar" overwrite="false">
    <fileset dir="lib" includes="**/*.jar"/>
</unjar>
<jar destfile="_dist/my-application.jar">     <fileset dir="_bin" />     <fileset dir="_unjar" includes="**/*.class"/> </jar>
What we did here is, we un-jared all the JAR files under ‘lib’ directory to a temporary directory ‘_unjar’, and include all the ‘.class’ files using the ‘fileset’ tag, simple isn’t it!
Read more »»

Tuesday, March 29, 2011

Java Communications API – Configuration How To

Java Communication API is an extension from Sun to program for Serial/Parallel ports. Sun’s implementation of this specification can be found at "http://java.sun.com/products/javacomm", there is also a third party Open Source implementation available at "http://rxtx.qbang.org/wiki/index.php/Main_Page". Java is platform Independent, but you need some platform specific implementation to access Serial/Parallel ports, and that is why you need to do some extra work to use Java Communication API.
First download the API binaries from "http://rxtx.qbang.org/wiki/index.php/Download" page. Extract it and follow the steps given below for Windows platform.
If you are just trying execute programs already written using just JRE, then
  • Copy rxtxParallel.dll to JRE_HOME\bin\
  • Copy rxtxSerial.dll to JRE_HOME\bin\
  • Copy RXTXcomm.jar to JRE_HOME\lib\ext\
If you are writing you own applications/programs, compiling and executing them, then
  • Copy rxtxParallel.dll to JDK_HOME\jre\bin\
  • Copy rxtxSerial.dll to JDK_HOME\jre\bin\
  • Copy RXTXcomm.jar to JDK_HOME\jre\lib\ext\
You can skip the last step of copying "RXTXcomm.jar" to "..\jre\lib\ext" directory and adding it to your CLASSPATH yourself and bundling it with your application itself.
That is it, you can find more information about RXTX implementation at "http://rxtx.qbang.org/wiki/index.php/Main_Page" and about installation for different platforms like Linux, Mac at "http://rxtx.qbang.org/wiki/index.php/Installation".
Simple example about using Java Communications API will follow soon.
Read more »»