Friday, October 14, 2011

Comparable vs Comparator !!!


Comparable vs Comparator !!!


There are many articles available on internet for this. But still I would write something about it.

What when and why?

A Comparable class is a class, which can be compared with the objects of its own type. Let us take an example of a book.
public class Book implements Comparable {
    String title;
    int    isbn;

    Book(String title, int isbn) {
        this.title = title;
        this.isbn  = isbn;
    }
    /* This method will be the default method used to sort Book objects in a list or Array */
    public int compareTo(Object object) {
    // It should throw NullPointerException if object passed is null
    if (object==null)
    {
        throw new NullPointerException("compareTo: Argument passed is null");
    }
        Book other = (Book) object;
        if (this.title.equals(other.title)) {
            return this.isbn - other.isbn;
        }
        return this.title.compareTo(other.title);
    }
}

The moment your class implements Comparable, you can then use

List list = new LinkedList();
        list.add(new Book("Patterns", 12345));
        list.add(new Book("Apples", 34567));
        list.add(new Book("Examples", 23456));

        Collections.sort(list);

Using this you can sort your list.

But what if now, you want to add or use another sorting criteria defined in Book class... Here comes the need of Comparator.
There are two ways listed here to use the Comparator class.

First method

We create a anonymous class that implements Comparator and overrides compare method.
Collections.sort(list, new Comparator() {
            public int compare(Object obj1, Object obj2) {
                if(obj1 == null || obj2 == null){
                    throw new NullPointerException("compareTo: Argument passed is null");
                }
                Book book1 = (Book) obj1;
                Book book2 = (Book) obj2;
                return book1.isbn - book2.isbn;
            }
        });

Second Method

You define a class that implements Comparator like as below.
class BookComparator implements Comparator{
   
    public int compare(Object book1, Object book2){
   
        int b1= ((Book)book1).isbn;        
        int b2= ((Book)book2).isbn;
       
        if(b1> b2)
            return 1;
        else if(b1< b2)
            return -1;
        else
            return 0;    
    }
   
}
And use this newly defined comparator class as an argument to Collections.sort.
Arrays.sort(list, new BookComparator ());

Good reasons to use Comparator interface

  • I do not have permissions to edit the Book class.
  • Book class already implements Comparable interface, but I want to sort the objects using a different criteria
  • I want to have more than 1 criterias to sort the objects in different orders.

Reasons to implement Comparable interface

  • I want my class to have a default sorting criteria that can be used by the users of my class
  • Usually, one would like to sort the objects based on primary key
Few good links on this topic are here http://www.javadeveloper.co.in/java-example/java-comparator-example.html http://grdurand.com/static/presentation_four/comparable.html http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

Thursday, October 13, 2011

Dynamically generate HTML elements using javascript and save them on server


Dynamically generate HTML elements using javascript and save them on server


Today while working in office, I had a requirement where I was required to generate dynamic elements in HTML form and then later on submit the form to a server and save the filled in data.

Though it was not very difficult to generate dynamic elements using javascript, but when I tried to save the data by submitting the form, i got an message from the server that the fields I had submitted are not provided.

But I had provided the fields, I was able to see the HTML elements on screen.

I tried to look on internet, might be possible that as disabled fields are not sent to server, similarly there is a chance that dynamically generated fields are also not sent to the server.
And unfortunately I found a link which was supporting my above statement. Here is the link

Actually, I converted a text box to a drop down which got populated using an ajax call. I kept the same ID for the already present textbox and the newly created drop down.
But the values of newly created dropdown were not submitted to the server. So what went wrong???

The mistake I was doing in my project was that I had set the ID of the dynamically generated dropdown, but I forgot to set the name. and in struts if you remember, Action form elements are synched with the elements of the same name in HTML form.

Map in Javascript



Source : http://www.coderanch.com/t/121097/HTML-JavaScript/Map-Javascript

Map in Javascript


var output = {}; 

Sort of. That just creates an empty instance of a JavaScript Object. It's identical to:

var output = new Object();   

There really isn't any implementation of Map in JavaScript.

But... JavaScript objects can be assigned properties on the fly, so an Object acts a lot like a map.

For example, after declaring your variable as shown above, you could write:

output.abc = 123;    

and now the object has a property named abc that contains the value 123.

The value can be retrieved with either of:
output.abc  
   
output['abc']  
 


Tuesday, October 11, 2011

Internationalization tips -- I/O operations

I/O Operations


Whenever text is being read from / written to a file, the encoding should be specified. (Preferably as UTF-8 but need to keep in mind the OS / Language / Locale)

try
   {
            FileOutputStream fos = new FileOutputStream("test.txt");
            Writer out = new OutputStreamWriter(fos, "UTF-8");
            out.write(strInputString);
            out.close();
    } 
   catch (IOException e) 
   {
            e.printStackTrace();
    }
}

Internationalization tips for XML

In order for the XML to support Unicode, the following statement needs to be mentioned at the start of the XML:

<?xml version="1.0" encoding="UTF-8"?>


Apart from these there is BOM issue while saving the XMLs with Unicode characters. Many Windows based text editors add the bytes 0xEF,0xBB,0xBF at the start of document saved in UTF-8 encoding. These set of bytes are Unicode byte-order mark (BOM) though are not relevant to byte order. The BOM can also appear if another encoding with a BOM is translated to UTF-8 without stripping it.

The presence of the UTF-8 BOM may cause interoperability problems with existing software that could otherwise handle UTF-8, for example:

  • Older text editors may display the BOM as "" at the start of the document, even if the UTF-8 file contains only ASCII and would otherwise display correctly.
  • Programming language parsers can often handle UTF-8 in string constants and comments, but cannot parse the BOM at the start of the file.
  • Programs that identify file types by leading characters may fail to identify the file if a BOM is present even if the user of the file could skip the BOM. Or conversely they will identify the file when the user cannot handle the BOM. An example is the UNIX shebang syntax.
  • Programs that insert information at the start of a file will result in a file with the BOM somewhere in the middle of it (this is also a problem with the UTF-16 BOM). One example is offline browsers that add the originating URL to the start of the file
If compatibility with existing programs is not important, the BOM could be used to identify if a file is UTF-8 versus a legacy encoding, but this is still problematical due to many instances where the BOM is added or removed without actually changing the encoding, or various encodings are concatenated together. Checking if the text is valid UTF-8 is more reliable than using BOM. It’s better to omit the BOM while saving the Unicode files. One of the solutions and some discussion surrounding the problem can be found here

Wednesday, October 5, 2011

Forcing SaveAs using the HTTP header

Forcing SaveAs using the HTTP header


In order to force the browser to show SaveAs dialog when clicking a hyperlink you have to include the following header in HTTP response of the file to be downloaded:

Content-Disposition: attachment; filename=<file name.ext>

Where <file name.ext> is the filename you want to appear in SaveAs dialog (like finances.xls or mortgage.pdf) - without < and > symbols.

You have to keep the following in mind:
  • The filename should be in US-ASCII charset.
  • The filename should not have any directory path information specified.
  • The filename should not be enclosed in double quotes even though most browsers will support it.
  • Content-Type header should be before Content-Disposition.
  • Content-Type header should refer to an unknown MIME type (at least until the older browsers go away).
There is something more about it, you must read

THIS

before you use this header.

CLEARCASE : Quickly retrieve change set

R:\>cleartool lsactivity -l yogesh_cdg_cod_dhfl_cas3.7_2@\cascd1_datavob activity "P_1783_DocumentUploadFunctionality" > D:\Yogesh\List.txt



yogesh_cdg_cod_dhfl_cas3.7_2 --> This is the View Name
cascd1_datavob --> This is your datavob
P_1783_DocumentUploadFunctionality --> This is your activity name

Saturday, October 1, 2011

To Upload and insert the file into Database with Current Date and Time In JSP

Source : http://www.roseindia.net/jsp/fileupload.shtml



In this tutorial, you will learn how to upload a file through JSP and insert it into the database. For this, we have created two jsp pages page.jsp and upload_page.jsp. The page.jsp is created for presentation where a file component is created to let the user select the file to be uploaded and a button to submit the request. The action is performed on upload_page.jsp. Before proceeding further, we need table in database. We created table named 'file' for our example.


Step 1 : Create a Table structure for file (mysql for our case).

CREATE TABLE file (
id int(20) auto_increment key,
file_data text,
file_date datetime
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Step 2:Create a Page ("page.jsp") To Upload a file.

<%@ page language="java" %>
<html>
    <HEAD>
        <TITLE>Display file upload form to the user</TITLE>
    </HEAD> 
    <BODY> 
        <FORM ENCTYPE="multipart/form-data" ACTION="upload_page.jsp" METHOD=POST>
            <center>
            <table border="0" bgcolor=#ccFDDEE>
                <tr>
                        <td colspan="2" align="center"><B>UPLOAD THE FILE</B></td>
                </tr>
                <tr>
                    <td colspan="2" align="center">&nbsp;</td>
                </tr>
                <tr>
                    <td><b>Choose the file To Upload:</b></td>
                    <td><INPUT NAME="file" TYPE="file"></td>
               </tr>
               <tr>
                   <td colspan="2" align="center">&nbsp;</td>
               </tr>
               <tr>
                   <td colspan="2" align="center"><INPUT TYPE="submit" VALUE="Send File" ></td>
               </tr>
           </table>
           </center> 
       </FORM>
    </BODY>
</HTML>



Step 3: Create a page of upload_page.jsp to upload and insert the file in database with current date and time.

<%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<html>
<%
 int val =0;
 String contentType = request.getContentType();
 if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) 
        {
  DataInputStream in = new DataInputStream(request.getInputStream());
  int formDataLength = request.getContentLength();
  byte dataBytes[] = new byte[formDataLength];
  int byteRead = 0;
  int totalBytesRead = 0;

  while (totalBytesRead < formDataLength) {
   byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
   totalBytesRead += byteRead;
  }
  String file = new String(dataBytes);
  String saveFile = file.substring(file.indexOf("filename=\"") + 10);
  System.out.println("saveFile=" + saveFile);
  saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
  System.out.println("saveFile" + saveFile);
  saveFile = file.substring(file.indexOf("filename=\"") + 10);
  saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
  saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
  int lastIndex = contentType.lastIndexOf("=");
  String boundary = contentType.substring(lastIndex + 1,contentType.length());
  int pos;

  pos = file.indexOf("filename=\"");
  pos = file.indexOf("\n", pos) + 1;
  pos = file.indexOf("\n", pos) + 1;
  pos = file.indexOf("\n", pos) + 1;
  int boundaryLocation = file.indexOf(boundary, pos) - 4;
  int startPos = ((file.substring(0, pos)).getBytes()).length;
  int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

  FileOutputStream fileOut = new FileOutputStream(saveFile);
  fileOut.write(dataBytes, startPos, (endPos - startPos));
%>

<%
  Connection con=null;
  PreparedStatement pstatement = null;
  String line = null;
  String value=null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "file_upload";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  try
                {
   StringBuilder contents = new StringBuilder();
   BufferedReader input = new BufferedReader(new FileReader(saveFile));
   while (( line = input.readLine()) != null){
    contents.append(line);
   }
   value = contents.toString();
   System.out.println("Value:"+value);
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection(url+dbName,userName,password);
   java.util.Date now = new java.util.Date();
   String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
   SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
   String strDateNew = sdf.format(now) ;

   String queryString = "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'";

   //out.println(queryString);

   pstatement=con.prepareStatement(queryString);


   val = pstatement.executeUpdate();

   if(val>0)
   {
%>
<br><br>
<b>File <% out.println(saveFile); %> has been uploaded and inserted into Database at <%=strDateNew%>.</b>
<%
   }
  }
  catch(Exception e)
  {
  }
 }
%>
</html>


This file upload and insert into database with current date and time using JDBC database. This can be done

(i). To import java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat packages. Java.io Packages is used to read and write the file uploaded having classes like DataInputStream, FileOutputStream etc. java.util.*,java.text.*,java.text.SimpleDateFormat is used to retireve the current Date and Time.
(ii). Prepared Statement is used to insert the data into database having used pstatement=con.prepareStatement(queryString);
(iii). Using a Query "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'" to insert the data into database.

Step 4: Output when file upload and insert into database with current date and time.

Table Structure after file Upload :



A message has been displayed on the browser.

The file is inserted into the database with current date and time.



Saturday, September 24, 2011

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

The jsp page gives the following error : The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

Even if you include this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

in your jsp page, it still gives the error.

The reason is that it depends upon the web app version. The web app version is defined in the web.xml file as follows:

Here’s an example of what to look for in web.xml:
<?xml version="1.0" encoding="UTF-8"?>

  web-app-25
...

You can see the version="2.5" designation in here. This means that within this web application, we will be able to use JSP 2.1 and JSTL 1.2 features.


Here, the web app version is 2.3.

So, if you are using web app version 2.3, then we should use :

<%@taglib prefix="c" uri="http://java.sun.com/jsp/core" %>

For Web app versions 2.4 & 2.5, you should use:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


Complete Error Trace:


WARNING: /SpringDemo/customer.htm:
org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:50)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:114)
at org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:316)
at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:147)
at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:423)
at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:492)
at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1552)
at org.apache.jasper.compiler.Parser.parse(Parser.java:126)
at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211)
at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
at org.mortbay.jetty.servlet.WebApplicationHandler.dispatch(WebApplicationHandler.java:473)
at org.mortbay.jetty.servlet.Dispatcher.dispatch(Dispatcher.java:286)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:171)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:239)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1072)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:808)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:726)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:636)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:556)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:616)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
at org.mortbay.jetty.servlet.WebApplicationHandler.dispatch(WebApplicationHandler.java:473)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:568)
at org.mortbay.http.HttpContext.handle(HttpContext.java:1530)
at org.mortbay.jetty.servlet.WebApplicationContext.handle(WebApplicationContext.java:633)
at org.mortbay.http.HttpContext.handle(HttpContext.java:1482)
at org.mortbay.http.HttpServer.service(HttpServer.java:909)
at org.mortbay.http.HttpConnection.service(HttpConnection.java:820)
at org.mortbay.http.HttpConnection.handleNext(HttpConnection.java:986)
at org.mortbay.http.HttpConnection.handle(HttpConnection.java:837)
at org.mortbay.http.SocketListener.handleConnection(SocketListener.java:245)
at org.mortbay.util.ThreadedServer.handle(ThreadedServer.java:357)
at org.mortbay.util.ThreadPool$PoolThread.run(ThreadPool.java:534)


Reference : http://www.mularien.com/blog/2008/04/24/how-to-reference-and-use-jstl-in-your-web-application/

Friday, September 23, 2011

java.lang.UnsupportedClassVersionError: Bad version number in .class file

java.lang.UnsupportedClassVersionError: Bad version number in .class file

[at java.lang.ClassLoader.defineClass1(Native Method)]

is an error that you may face in running a compiled java class file.

So as you can see from the stack trace, a class has not been loaded. But which class?

The problem is this error message does not show the name of the failed .class, isn't it?

No, it is not. This error is caused when you compile a .java file with one version of JDK and running the .class file with a different version of JVM.

Confused? You may say; same version is not required to compile and run.

Yes, that is true. But you can not run .class files that are compiled with a newer version than the JVM.

Say;

javac (compile) - version: X
java  (run)     - version: Y

If X is newer than Y; then you may face this issue at runtime.


Reference : http://lkamal.blogspot.com/2008/04/javalangunsupportedclassversionerror.html

Here is the supporting example.

Set the path to 1.6 for compilation
C:\Users\Yogi\Desktop>set PATH="C:\Program Files\Java\jdk1.6.0_10\bin";%PATH%

C:\Users\Yogi\Desktop>javac test.java

Now run the class using 1.5 jre
C:\Users\Yogi\Desktop>set PATH="C:\Program Files\Java\jre1.5.0_06\bin";%PATH%

C:\Users\Yogi\Desktop>java test
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version n
umber in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)


Friday, September 16, 2011

Javascript : How do I open a new browser window?

Source : http://www.javascripter.net/faq/openinga.htm

Question: How do I open a new browser window?

Answer: To open a new browser window, use the window.open() method. For example, the following code opens this page in a new window.
myRef = window.open(''+self.location,'mywin', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');


The general syntax of the window.open() method is as follows:

winRef = window.open( URL, name [ , features [, replace ] ] )

The return value, stored in the variable winRef, is the reference to your new window. You can use this reference later, for example, to close this window (winRef.close()), give focus to the window (winRef.focus()) or perform other window manipulations.

The parameters URL, name, features, replace have the following meaning:

URL String specifying the location of the Web page to be displayed in the new window. If you do not want to specify the location, pass an empty string as the URL (this may be the case when you are going to write some script-generated content to your new window).


name String specifying the name of the new window. This name can be used in the same constructions as the frame name provided in the frame tag within a frameset <frame NAME=name ...>. For example, you can use hyperlinks of the form <a target=name href="page.htm">, and the hyperlink destination page will be displayed in your new window.


If a window with this name already exists, then window.open() will display the new content in that existing window, rather than creating a new one.



features An optional string parameter specifying the features of the new window. The features string may contain one or more feature=value pairs separated by commas.
replace An optional boolean parameter. If true, the new location will replace the current page in the browser's navigation history. Note that some browsers will simply ignore this parameter.


The following features are available in most browsers:
toolbar=0|1	 Specifies whether to display the toolbar in the new window.
location=0|1	 Specifies whether to display the address line in the new window.
directories=0|1	 Specifies whether to display the Netscape directory buttons.
status=0|1	 Specifies whether to display the browser status bar.
menubar=0|1	 Specifies whether to display the browser menu bar.
scrollbars=0|1	 Specifies whether the new window should have scrollbars.
resizable=0|1	 Specifies whether the new window is resizable.
width=pixels	 Specifies the width of the new window.
height=pixels	 Specifies the height of the new window.
top=pixels	 Specifies the Y coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)
left=pixels	 Specifies the X coordinate of the top left corner of the new window. (Not supported in version 3 browsers.)

JS Beautifier

I wish someone could format the unformatted javascript code

Here it comes true...


http://jsbeautifier.org

Check this out....Its Free and Amazing...

Another very useful site for javascript is

http://jsbin.com


How to disable touchpad in Lenovo Z560 touchpad

How to disable touchpad in lenovo ideapad Z560?


I know this post is not related to Java/J2ee, but I wanted to note down this solution somewhere. So storing it here.

Actually, the shortcut key for disabling touchpad (Fn+F6) is not working for me, because, F6 button of my keyboard is damaged.

I struggled for a week to find a solution of how to disable touch pad.

On google I saw various posts which say that there is an option of disabling touch pad in Control Panel -> Mouse -> Touch pad Tab

But I didn't find any such Tab.

After that I installed the touch pad driver from

Touchpad Driver for ideapad Z560

And I got that option in Control Panel -> Mouse.

Now I am happy....