Thursday, August 9, 2012

Difference between HashMap, LinkedHashMap and SortedMap in java

Hi,


All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:
  • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
  • TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order.
  • LinkedHashMap will iterate in the order in which the entries were put into the map
"Hashtable" is the generic name for hash-based maps. In the context of the Java API, Hashtable is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless).


Thanks

Rajesh Kumar Yuvaraj

Saturday, July 28, 2012

Servlet File Upload

Hi,

html
-----
    <form action="UploadForm" enctype="multipart/form-data" method="POST">
            <input type="file" name="file1"><br>
            <input type="Submit" value="Upload File"><br>
        </form>
web.xml
--------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>UploadForm</servlet-name>
        <servlet-class>UploadFormServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadForm</servlet-name>
        <url-pattern>/UploadForm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


servlet
------

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFormServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }
        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
        out.println();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            /*
             * Parse the request
             */
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                /*
                 * Handle Form Fields.
                 */
                if (item.isFormField()) {
                    out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());
                    /*
                     * Write file to the ultimate location.
                     */
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                }
                out.close();
            }
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }
}

Jars Needed

http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/commons/commons-io/1.3.2/commons-io-1.3.2.jar

http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-fileupload/commons-fileupload/1.2.1/commons-fileupload-1.2.1.jar

 


Thanks

Rajesh   Kumar Yuvaraj





Friday, July 27, 2012

use of identityHashCode() of System class

Hi,
    As we know that we can override the hashCode() method of Object class with our own representation,What if i want to get the original hashCode() of a specific object. For that jdk provides a method inside of System class. Please go through the following example.


public class HashCodeDemo {

    @Override
    public int hashCode() {
        return 20;
    }

    public static void main(String ar[]) {

        HashCodeDemo hashObj = new HashCodeDemo();
        System.out.println(hashObj);
        System.out.println(hashObj.toString());
        System.out.println(hashObj.hashCode());
        System.out.println(System.identityHashCode(hashObj));

    }
}

OutPut
--------
javaapplications.HashCodeDemo@14
javaapplications.HashCodeDemo@14
20
4072869


Thanks

Rajesh Kumar Yuvaraj

Thursday, July 26, 2012

usage of Map.Entry interface in java collections


Hi,

    
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
// TODO code application logic here
// Create a hash map
        HashMap hm = new HashMap();
// Put elements to the map
        hm.put("John Doe", new Double(3434.34));
        hm.put("Tom Smith", new Double(123.22));
        hm.put("Jane Baker", new Double(1378.00));
        hm.put("Todd Hall", new Double(99.22));
        hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
        Set set = hm.entrySet();
// Get an iterator
        Iterator i = set.iterator();
// Display elements
        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        System.out.println();
// Deposit 1000 into John Doe's account
        double balance = ((Double) hm.get("John Doe")).doubleValue();
        hm.put("John Doe", new Double(balance + 1000));
        System.out.println("John Doe's new balance: "
                + hm.get("John Doe"));
    }
}


Friday, July 13, 2012

what is SQLite ?

                                          SQLite  is a tiny, embedded RDBMS (~275kb) which is used by the most of the local/client storage in  application software such as web browsers.Simply its a embedded data base for web browsers.
Ex.  Mozilla stores the cookies information inside a cookie.sqlite  file in the location C:\Users\Mypc\AppData\Roaming\Mozilla\Firefox\Profiles\gwj7th6j.default.
 This file is encrypted internally.We can explore this data base using a firefox plug in called SQLite.

https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/

Thanks,

Rajesh Kumar Yuvaraj

Friday, June 29, 2012

Another way of System.out.println();

Hi Guys,

                         This is the another way of printing something to console.

import static java.lang.System.out;
 
public class ShortSOP {
public static void main(String[] args) {
out.println("Hello, world");
}
}

Thanks,

Rajesh Kumar yuvaraj

Performance Trade offs of System.out.println();

 Hi Guys,


                     Do you know that the more number of System.out.println(); leads to the slowness of the project, Why, The method println() is a synchronized  which leads to slowness in terms of execution.


Thanks

Rajesh Kumar Yuvaraj

The "Best Ever " example for Synchronization !!!!!!!

Hi Guys,
          
              As you know that  we can discuss half of the J2SE using the statement which is executed most number of times in this Universe, that is

                    i.e: System.out.println("");

Using this statement we can explain the concept of Synchronization in this way.

  • System is a final class which can not be extended.
  • out is a static variable in side the System class of type PrintStream.
  • println() is a method if PrintStream class.
  • We have totally 10 println() methods inside of this PrintStream class.
  • each and every println() method is synchronized.
 i.e    public void println(String x) {
        synchronized (this) {
        print(x);
        newLine();
     }
    } 

Q)      why sun micro systems designed println() method in this way?
 Ans)  Because at any point of time only one thread can be inside of this block,
                                     
Q)     Then what is the use?
Ans)   To prevent form the deadlock.If multiple thread access the same code it becomes a scrap.

In this way the println() method is a best example of Synchronization.

Thanks,

Rajesh Kumar Yuvaraj



Redirecting the output of System.out.println()

Hi Guys,

Using the below example we can redirect the out put of the System.out.println().

public class ChangeOut {
  public static void main(String args[]) {
    try {
      System.setOut(new PrintStream(new FileOutputStream("log.txt")));
      System.out.println("Now the output is redirected!");
    } catch(Exception e) {}
  }
}

Thanks

Rajesh Kumar yuvaraj

Wednesday, June 27, 2012

I Frame with javascript Example

Hi Guys,

           Here is a sample iFrame example.



<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <title>Untitled 1</title>

        <script >
            function go(loc){
                alert(loc);
                document.getElementById('calendar').src = loc;
            }
        </script>
    </head>

    <body>
        <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="2" scrolling="no"></iframe>

        <form method="post">
            <input name="calendarSelection" type="radio" onclick="javascript:go('https://google.com')"/>Day
        </form>

    </body>

</html>


Thanks,


Rajesh Kumar Yuvaraj

Tuesday, June 12, 2012

Allow only Alphabets in the textfield

Hi,



       function AllowAlphabet(e)
            {
                isIE=document.all? 1:0
                keyEntry = !isIE? e.which:event.keyCode;
                if(((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry=='46') || (keyEntry=='32') || keyEntry=='45' )
                    return true;
                else
                    return false;
            }
Usage :
 <input type="text" onkeypress="return AllowAlphabet(event)">

Struts 2 examples

Hi,

http://shivasoft.in/blog/java/struts/step-by-step-simple-login-application-in-struts-2/

Monday, June 11, 2012

Numbers Only logic


Hi,

Usage : onkeypress ="return  numbersonly(event);"

function numbersonly(e) {
 var keynum
 var keychar
 var numcheck


 if(window.event) { // IE
  var code = window.event;
    keynum = code.keyCode
 } else if(e.which) {// Netscape/Firefox/Opera
  keynum = e.which
 }

 if (keynum == 99) return true;
 if (keynum == 118) return true;
 //if (keynum == 42) return true;
 if (keynum == 8 || keynum == 13 ) return true;
 if (keynum < 48 || keynum > 57 ) return false;
}

Saturday, June 9, 2012

How to get the session contents of a web applications.

Hi Guys,

            Here is a sample code which is used to get the session contents of any web container.

<!-- Displays the session content in any of the web application.
@author  : Rajesh
-->
<body >
<style>
    body{ font-family:Tahoma, sans-serif, Verdana, Arial, Helvetica, sans-serif; font-size:12px; margin:0px; padding:0px; background-color:#A7C71A; color:#FFFFFF;}
    .actionButton{border:1px solid #d7e3ef;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;background: -moz-linear-gradient(top,  #fbbc79,  #f98f15);background: -webkit-gradient(linear, left top, left bottom, from(#fbbc79), to(#f98f15));filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fbbc79', endColorstr='#f98f15');display:inline-block;color:#333;padding:4px 10px;font-weight:700;text-shadow:1px 1px #f1f1f1;text-decoration:none;margin:2px;font-size:13px;}
</style>
<center>
    <u>
        <h2>
        </h2>
    </u>
    <table><tr><td>
                <form name="frm1" method="POST" action="./test.jsp?clearsession=true">
                    <input class="actionButton" type=submit value="Clear Session">
                </form>

            </td>
            <td>
                <form name="frm2" method="POST" action="./test.jsp">
                    <input class="actionButton" type=submit value="Get Session">
                </form>
            </td>
        </tr>
    </table>


</center>
<%@page import= "java.util.*" %>
<%
            if (request.getParameter("clearsession") != null && request.getParameter("clearsession").equals("true")) {
                session.invalidate();
                return;
            }
            String[] keys = (String[]) session.getValueNames();
            int i = 1;
%>
<table border="1" align="center" cellpadding="4" cellspacing="4">
    <tr>
        <th> Sl.No </th>
        <th> Attribute Name </th>
        <th> Attribute Value </th>
    </tr>
    <% for (String key : keys) {
    %>
    <tr>
        <td> <%=i%></td>
        <td><%=key%></td>
        <td><%=session.getAttribute(key)%></td>
    </tr>
    <%
                    i++;
                }
    %>
</table>

Thanks,

Rajesh Kumar Yuvaraj

Thursday, May 24, 2012

Tuesday, May 1, 2012

JAVA XML Parser Program

Hi Guys,
            Here is a sample Java XML Perser Program.


Knowledge Base: http://www.rgagnon.com/javadetails/java-0573.html


import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;

public class ParseXMLString {

  public static void main(String arg[]) {
     String xmlRecords =
      "<data>" +
      " <employee>" +
      "   <name>John</name>" +
      "   <title>Manager</title>" +
      " </employee>" +
      " <employee>" +
      "   <name>Sara</name>" +
      "   <title>Clerk</title>" +
      " </employee>" +
      "</data>";

    try {
        DocumentBuilderFactory dbf =
            DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xmlRecords));

        Document doc = db.parse(is);
        NodeList nodes = doc.getElementsByTagName("employee");

        // iterate the employees
        for (int i = 0; i < nodes.getLength(); i++) {
           Element element = (Element) nodes.item(i);

           NodeList name = element.getElementsByTagName("name");
           Element line = (Element) name.item(0);
           System.out.println("Name: " + getCharacterDataFromElement(line));

           NodeList title = element.getElementsByTagName("title");
           line = (Element) title.item(0);
           System.out.println("Title: " + getCharacterDataFromElement(line));
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    /*
    output :
        Name: John
        Title: Manager
        Name: Sara
        Title: Clerk
    */    
    
  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
       CharacterData cd = (CharacterData) child;
       return cd.getData();
    }
    return "?";
  }
}

Monday, April 30, 2012

Can we Zoom in / Zoom out a web page using Java Script and HTML

Hi,

               A lot of websites on internet provide users with an option to increase the font size of the page for better reading experience. Although nowadays almost all the web browsers supports zoom in/out functionality using mouse wheel scroll or other shortcut keys, it is sometimes a good idea to give user a way to increase/decrease the font size of web page.
Let us implement a simple zoomer code in JavaScript that will increase/decrease the font size of the web page at client side without reloading the page from server. A small JavaScript snippet will be used to change the font size of the web page at client side.

Knowledge Base:

http://viralpatel.net/blogs/2009/03/implement-simple-font-zoomer-in-javascript-html.html

JavaScript code

Let us check the following JavaScript code.










var fontSize = 1;
function zoomIn() {
    fontSize += 0.1;
    document.body.style.fontSize = fontSize + "em";
}
function zoomOut() {
    fontSize -= 0.1;
    document.body.style.fontSize = fontSize + "em";
}
In the above JavaScript code, a global variable fontSize is defined with value 1. This variable’s value will be changed whenever user tries to increase or decrease the font size. Then we have two functions zoomIn() and zoomOut() to perform zoom in and zoom out respectively. The font size of the web page is changed by changing the attribute fontSize in document.body.style.

Calling JavaScript from HTML

You can place simple icons to zoom in and zoom out the text and call the zoomIn() and zoomOut() methods on click event. Or can place buttons to zoom in/out.



<input type="button" value="+" onClick="zoomIn()"/>
<input type="button" value="-" onClick="zoomOut()"/>
 
Thanks,
 
Rajesh Kumar yuvaraj

Open A New Window without Back Button

Hi Guys,

              Following are few tricks that can be used to disable the back button in browser. Please note that we do not literally “disable” the back button, but just nullify its effect is some case and hide it altogether in others.

Knowledge Base: http://viralpatel.net/blogs/2009/11/disable-back-button-browser-javascript.html


window.open ("http://viralpatel.net/blogs/","mywindow","status=1,toolbar=0");
Also it is possible to disable the right click on any webpage using Javascript. Add following code in the webpage.

1
<body oncontextmenu="return false;">
 

Disable Back functionality using history.forward

This is another technique to disable the back functionality in any webpage. We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page

<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">
The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.
 

Thursday, April 26, 2012

Convert Arrays to Set in Java

Here is a example which demonstrates conversion of Array to Set in Java

Example: Java Array to Set





String [] countires = {"India", "Switzerland", "Italy"};
Set<String> set = new HashSet<String>(Arrays.asList(countires));
System.out.println(set);
 Output:
[Italy, Switzerland, India]

Creating a ZIP file using JavaScript

Hi Guys,
             We have 'n' number of tools which generates  ZIP files but creating the ZIP files using JavaScript is different. To create a ZIP file using Java script we need to download the jszip.js and include it to your html file.


Knowledge Base : 




Sample Code:
            http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html

Step 1. Import jszip JavaScript

Include the jszip javascript file in the HTML document where you want to generate ZIP files. You can download the jszip package and include it in HTML or directly include the jszip javascript through git repository.

<script type="text/javascript"
        src="https://raw.github.com/Stuk/jszip/master/jszip.js"></script>

Step 2. Generate Hello world ZIP

Following code snippet is HTML file which contains Javascript code to generate ZIP file.





















<HTML>
<HEAD>
    <script type="text/javascript" src="jszip.js"></script>
</HEAD>
 
<BODY>
 
    <input type="button" onclick="create_zip()" value="Create Zip"></input>
 
</BODY>
<SCRIPT>
 
function create_zip() {
    var zip = new JSZip();
    zip.add("hello1.txt", "Hello First World\n");
    zip.add("hello2.txt", "Hello Second World\n");
    content = zip.generate();
    location.href="data:application/zip;base64," + content;
}
 
</SCRIPT>
</HTML>
In above code snippet, we have a button “Create Zip” which calls javascript function create_zip(). This function calls jszip API to generate ZIP file.

Create/Manipulate PDF files using JAVA

Hi Guys,

              Do you know that we can generate the PDF files on the fly in JAVA. To achieve this we need to use the iText.jar file. Just set the iText.jar file to your class path and use below program to generate a PDF file.
Knowledge Base : http://www.lowagie.com/iText/download.html.
Download Link  : http://sourceforge.net/projects/itext/files/

Sample Program
-----------------
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class GeneratePDF {
    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 A Test.pdf file will be generated in " C:\\" drive.

Friday, January 13, 2012

Java Script Associates Arrays

Hi Guys,
              It is always good to have a associated  arrays instead of plain arrays in java java script. The below sample code demonstrates the use of java script associated arrays.
 
 var gameNdPlayesr= new Array();
 gameNdPlayesr["cricket"]="Sachin";
 gameNdPlayesr["football"]="Maradona";
 gameNdPlayesr["golf"]="Woods";
 
 var sport=confirm("Please enter your favourite sport");
 alert( "The king of "+ sport+" is "+gameNdPlayesr[sport]);


Thanks,
Rajesh Kumar Yuvaraj



Thursday, January 12, 2012

JavaScript random string of specific length

Hi Guys,
             The below java script code generates a random string of specific length.

function getRandomByLength(randomStrLength) {

       var chars =        "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
      var randomstring = '';
      for (var i=0; i<randomStrLength; i++) {
      var rnum = Math.floor(Math.random() * chars.length);
      randomstring += chars.substring(rnum,rnum+1);
    }
        return randomstring;
}