Showing posts with label J2EE. Show all posts

How to setup cookie free or cookie less sub domain in java?

Before we start tutorial about creating cookie free or cookie less domain in java. You'll need to setup sub domain. To setup sub domain in java + tomcat7 read the article : http://www.javaquery.com/2013/05/how-to-configure-subdomain-in-tomcat-7.html

Why should i create cookie free or cookie less sub domain for static content? 
    Below image helps you to understand the real time scenario. Lets say you set your cookie's domain ".domain.com". Browser use this cookies when you request content from static.domain.com and creates network traffic. Read more about cookie free domain : http://developer.yahoo.com/performance/rules.html#cookie_free


Cookies
Cookies
Solution: To get over this problem you must set domain of cookie like www.domain.com .We can forcefully insert www in URL. If URL contains www then cookies will created for domain "www.domain.com".

Scenario: I'll demonstrate the example where i forcefully insert WWW for home page. So on each login cookies create only for www.domain.com . I'll also demonstrate URL redirect when there is request for webpage don't have WWW in URL (i.e: http://domain.com/message/view.jsp?id=125) and request for cookies.

Insert below code in your index.jsp (i.e: home page) at the start of the page.
// index.jsp
    String referer = request.getParameter("url");

    if (referer == null && !request.getHeader("host").contains("www")) {
        response.sendRedirect("http://www.domain.com");
    } else if (referer!=null && !referer.equals("index.jsp") && (referer.indexOf("www")<0 referer.indexof="" www="">10)) {
        referer = referer.substring(referer.indexOf("//") + 2, referer.length());
        referer = "http://www." + referer;
        response.sendRedirect(referer);
    }

We use the else if code when there is a request come for other page except home page (i.e: http://domain.com/message/view.jsp?id=125). So...

Now we must check each page's URL for WWW in it. Insert below code in every page or create one checkURL.jsp page and include it in every page.
        boolean login = true;
        ...
        ...
        /* Read cookies for www.domain.com
         * if you can read it then okay but you can't then set login = false;
         * It'll be redirected to index.jsp and insert WWW in its URL and redirect to that page again.
         */
        if(!login){ 
        StringBuffer requestURL = request.getRequestURL();
        if (request.getQueryString() != null) {
            requestURL.append("?").append(request.getQueryString());
        }
        String completeURL = requestURL.toString();
        response.sendRedirect("index.jsp?url="+completeURL);
        }

So now on cookies created only for www.domain.com . Browser no more sends cookie in request for static.domain.com .

Java - How to insert www in naked domain?


Lets consider you want to insert www in url forcefully for certain reasons. Its easy task you can handle by simple script that I'm gonna give you. Keep in mind you need to change the below code for your domain as per your need.

Scenario: I'm considering the home page domain.com will be redirected to www.domain.com . If you want your page domain.com/forum/view.jsp?thread=124 will be redirect to www.domain.com/forum/view.jsp?thread=124 then you must add this code to every page. Simple idea is make checkURL.jsp and paste the code in this page and include checkURL.jsp in every page.
    StringBuffer requestURL = request.getRequestURL();
    if (request.getQueryString() != null) {
         requestURL.append("?").append(request.getQueryString());
    }
    String completeURL = requestURL.toString();

    if (completeURL.indexOf("www")<0 || completeURL.indexOf("www")>10) {
        String referer = completeURL.substring(referer.indexOf("//") + 2, referer.length());
        referer = "http://www." + referer;
        response.sendRedirect(referer);
    } 
Now when user comes to the page it'll check the URL and if there is not www in URL it'll append and redirect it to desired page.

How to configure Subdomain in Tomcat 7?


Before we jump to solution let me write search queries used by users to do same so they will also get the solution.

  • Configure subdomain in apache tomcat 7.
  • Configuring Virtual Hosts.
  • Configure subdomain in server.xml
  • Configure subdomain in DNS.
  • Configure subdomain for java.
  • Configure subdomain step by step.
  • Configure subdomain on www.eatj.com 

There is no perfect solution available to configure subdomain. I walk through 200-300 webpages and article to get the solution. I prefer the solution must be understandable. I'll show you how you can configure subdomain(s).

In this example we'll configure subdomain m.domain.com . You can also have your subdomain like a4apple.domain.com . [Note : subdomain name must be lower case you can't give subdomain name as M.domain.com So keep in mind it won't work.]

Step 1: You need to modify the server.xml file available in ${catalina.home}/conf/server.xml or tomcat_installation/conf/server.xml. All you need is append below line of code with in <Engine> Tag.
<Host appbase="webapps/ROOT/m" autodeploy="true" name="m.domain.com" unpackwars="true" xmlnamespaceaware="false" xmlvalidation="false">
<Context docbase="/usr/local/software/tomcat7/webapps/ROOT/m" path="" reloadable="true"></Context>
<Context antijarlocking="false" antiresourcelocking="false" docbase="/usr/local/software/tomcat7/webapps/manager" path="/manager" privileged="true" reloadable="true"></Context>
</Host>
Things you need to change:

  • appbase : If you have folder where webapps folder is created then appbase will be just m . If folder is with in webapps then appbase will be webapps/m and so on...
  • name : change it with your domain name.
  • docbase in first context : Set the location of your folder with absolute path.
  • Second context : You can remove if you want or set it the the manager folder for your application.

Step 2: Edit DNS record for your website. Search for DNS editor on your website's admin panel. Follow below steps.

  • Go to List zones.
  • Edit your zones.
  • Add record.
  • Provide name m.domain.com
  • Set Type to A
  • Set Content to your Server IP Address.
  • Set TTL as per your want or 86400.

Note 1: DNS changes may take sometime if you are working on shared server or ask to your hosting provider.
Note 2: If you are working on windows then search on www.google.com for edit hosts file for subdomain .

Step 3: Restart your Apache Tomcat 7.

Getting started with JSON and Java Web application


What is JSON?
JSON stands for JavaScript Object Notation. Its text-based open standard designed for human-readable data interchange. To know more about JSON read the wikipedia . Here is how JSON object holds the data.

{
    "firstName": "Vicky",
    "lastName": "Thakor",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

Why use JSON in java web-application?
Its time to develop web-application that perform operation faster. Say if you want to process data without refreshing current page/content JSON is perfect solution for you. I'm going to show you quick demo with validating the email.

Download the JSON library for Java from sourceforge https://sourceforge.net/projects/javaqueryapi/files/


validateEmail.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Validate Email Address</title>
    </head>
    <body>
        <input name="email" id="email"/>
        <span id="result"></span>
        <input type="button" value="check" id="check"/>
        <script src="../staticCDN/js/jquery-1.8.2.min.js"></script>
        <script>
            $("#check").click(function(){
                var emailID = $("#email").val();
               $.get('emailJSON.jsp',{email:emailID},function(data){
                    var obj = eval ("(" + data + ")");
                    var status = obj.status;
                    if(status=="FAIL"){
                        alert(obj.notify_error);
                    }else{
                        //SUCCESS
                        $("#result").html("Email is Okay!");
                    }
               })
            });
        </script>
    </body>
</html>
emailJSON.jsp
<%@page import="org.json.JSONObject"%>
<%@page import="javaQuery.validation.validate"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
String email = request.getParameter("email");
validate vEmail = new validate();
JSONObject status = new JSONObject();
if(vEmail.Email(email)){
    status.put("status", "SUCCESS");
    status.put("notify_error", "Email is Okay!");
    out.print(status);
}else{
    status.put("status", "FAIL");
    status.put("notify_error", "Provide valid email!");
    out.print(status);
}
%>

Hope you get proper idea of JSON by checking all above codes. If you have any problem let me know.
Output of Demo:
JSON

JSON

Validate the data for enterprise web applications.

 If you are web developer then you must validate some data. I did validation part easy for you guys. Check out the validate class in latest javaQuery API. Let me tell you what i included in new validation class.






  • Get file extension of any file
  • Validate the email
  • Remove html tags.
Check the below example that show the demo of the API:

import javaQuery.validation.validate;

public class RunCode {
    public static void main(String[] args) {
        validate _validateData = new validate();
        String strfile_Extension = "test.mp3";
        String strhtml_Data = "This test is bold";

        System.out.println("File extension: " + _validateData.getFileExtension(strfile_Extension));
        System.out.println("Email is: " + _validateData.Email("vkijust4u@javaquery.com"));
        System.out.println("HTML tag normalized: " + _validateData.removeHTML(strhtml_Data));
    }
}
Output : 
File extension: .mp3
Email is: true
HTML tag normalized: <b>This test is bold</b>
So now you don't need to write bunch of codes to validate the email address/ remove html tags and get the file extension of any file.

Developers : How to attach video in your website using java?

After long time I'm back to javaQuery article. Today m gonna show you how google+, Facebook, Twitter embed videos in there post, Tweet, etc... I was working on this code. This code will cover all video website like Youtube, vimeo, etc... that contains video information in proper formation. Check out the below code to demonstrate the URL. This library is present in latest javaQuery API. Some website may not be support by this API.



/*
* javaQueryAPI 7.0 or less
*/
import javaQuery.j2ee.EmbedVideo;
public class Video {
    public static void main(String[] args) {
        String WebVideo = "";
        EmbedVideo em = new EmbedVideo();
        boolean flag = em.EmbedVideo("http://www.youtube.com/watch?v=0N9JxHEoYd4");
        //flag will return true if website/link contains video details in proper format.
        if (flag) {
            System.out.println(EmbedVideo.provider_name);
            System.out.println(EmbedVideo.provider_url);
            System.out.println(EmbedVideo.author_name);
            System.out.println(EmbedVideo.author_url);
            System.out.println(EmbedVideo.title);
            System.out.println(EmbedVideo.description);
            System.out.println(EmbedVideo.html);
            System.out.println(EmbedVideo.width);
            System.out.println(EmbedVideo.height);
            System.out.println(EmbedVideo.thumbnail_url);
            System.out.println(EmbedVideo.video_url);
            System.out.println(EmbedVideo.xml_type);

            WebVideo = "Author:"+EmbedVideo.author_name;
            //Modify the Data as per your requirement like place the video in iframe
        }
    }
}
/*
* javaQueryAPI 8.0 or above
* This code requires additional JSON library. You must include JSON lib to work this API. Its available in javaQueryAPI 8.0/lib folder on sourceforge.net
*/
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.embedvideo;

public class Demo {
    public static void main(String[] args) {
        embedvideo em = javaQueryBundle.create_embedvideo();
        em.linkTo("http://www.youtube.com/watch?v=SmM0653YvXU");
        System.out.println(em.title);
        System.out.println(em.video_url);
        System.out.println(em.description);
        System.out.println(em.width);
        System.out.println(em.height);
        System.out.println(em.thumbnail_url);
        System.out.println(em.author_name);
        System.out.println(em.author_url);
        System.out.println(em.html);
        System.out.println(em.provider_name);
        System.out.println(em.provider_url);        
    }
}
/*
* output
* Pitbull - Rain Over Me ft. Marc Anthony
* http://www.youtube.com/watch?v=SmM0653YvXU
* Not Available
* 480
* 270
* http://i4.ytimg.com/vi/SmM0653YvXU/hqdefault.jpg
* PitbullVEVO
* http://www.youtube.com/user/PitbullVEVO
* <iframe allowfullscreen="" frameborder="0" height="270" src="http://www.youtube.com/embed/SmM0653YvXU?feature=oembed" width="480"></iframe>
* YouTube
* http://www.youtube.com/
*/

Once you done with the code. You can change the properties of video attachment for your page. Change the video CSS, width, height.

Check out the http://www.javaquery.com/p/javaquery-api.html for download.

How to boost your website in Java?

Innovators making internet faster then our thoughts. Its also essential we have to serve our user best of it. User wants everything on finger tip like a blink of light. Some of you may searching for the content like

  • How to speed up site?
  • How to load site faster?
  • How to make Java, JSP, Servlet site fast?

To make your website secure and safe read this article How to create java website secure and safe?

I'll give you some tips to do it and you can see the effect its loading way much faster. Some content you ignored but it really matters when user have slow connection speed. Let me show how you made your site and its old idea to do it. Your site currently having this scenario as below.

This is how your site works if you didn't optimized it. Now we'll see how you can optimize if you didn't. Check your site grade using Yslow http://developer.yahoo.com/yslow/ We'll do optimization and after that check your grade you'll see it increased.

Compress StyleSheet, javaScripts
You must compress content to make response faster. So it'll take less time to load. Removing whitespace, unwanted semi colons from the StyleeSheet, javaScript. Use the below online tool to compress it

  • StyleeSheet (CSS) - Tool compress css and give you compressed CSS. Compress CSS in .css file as well as data between <style></style>
  • Tool : http://www.csscompressor.com/
  • Note: This tool compress CSS but some time it made changes according standard CSS rules. If you made any tricks in CSS it'll be omitted. After compression test your CSS and make changes again  for tricky CSS
Note : Place StyleSheet at the TOP and javaScript before the </body>.

Compress images, Don't scale it.
Compress images using some software, or online so it load faster on client side. Below some sites that helps you to convert and compress images. Secondly don't scale images say image 128x128 and you try to show as a 30x30. Better to make that image 30x30 rather then showing 128x128 image using width = 30.


Combine static images
Combine all static png images. Say if you have menubar icons so combining all images in one will reduce http requests. http://csssprites.com/

Remove Buffer
This is also required to flush the buffer. Put the below code between </head> <body> <% response.flushBuffer();%>

Few HTTP request
Combine all scripts in one file so it makes less parallel HTTP request. Say browser loads data after DNS look up(Domain Validation). So if you use multiple domain (image, script, etc... from other site) then it make DNS look up for every site. Try to minimize the HTTP request.Make HTTP request between 2-4 if possible. 

Set expire header for the content important task.
Browser it self store data in cache. But if you store data with out expiry. It'll load images, javascripts, stylesheets, etc... any time. Store data with proper expiry so it'll refresh data at that time only. All site have some static content like logo, menu image, script, stylesheet. Store this data at the client side so browse each time use data from cache. Browser doesn't make request for that data on server so server has to response less data. I'll show how you can do it.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletResponse;

public class cacheControl implements javax.servlet.Filter {
    FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }
    public void doFilter(ServletRequest req,
            ServletResponse res,
            FilterChain chain)
            throws IOException, ServletException {
        String sCache = filterConfig.getInitParameter("cache");

        if (sCache != null) {
            ((HttpServletResponse) res).setHeader("Cache-Control", sCache);
        }
        chain.doFilter(req, res);
    }
    public void destroy() {
        this.filterConfig = null;
    }
}

Create servlet using above code. Make an entry in web.xml if you are not using some IDE. Now set filer for what you want to set expiry header. Like *.css, *.js, *.png, etc....Copy paste the below code in web.xml . *.css, *.js, means every css from your domain, Below code have max-age=250000 mean it'll store data round about two days. You can also append *.png, *.jpg, etc... create proper filter.


<filter>
        <filter-name>Cache</filter-name>
        <filter-class>alien.config.cacheControl</filter-class>
        <init-param>
            <param-name>cache</param-name>
            <param-value>public, max-age=250000</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Cache</filter-name>
        <url-pattern>*.css</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>Cache</filter-name>
        <url-pattern>*.js</url-pattern>
    </filter-mapping>

Now check your grade using Yslow it would improve. The above filer response after some 2-3 request if you already opened site in your browser because browser already stored data. If your request comes from first time from that browser it'll store everything.

Compress content and serve to user.
Now we will pass data as a Gzip to client/user. All you need is find server.xml now find the Connector tag  and Append below code to it.

compression="on"
compressionMinSize="2048"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"
It'll look like
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8084" protocol="HTTP/1.1" redirectPort="8443" compression="on" compressionMinSize="2048" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

How to create java website secure and safe?


Web site developer must keep in mind before publishing site that site has enough validation to keep site secure and safe. I'll give you some tips and tricks to keep your java website safe and secure. The tips helps to prevent hacker from hacking your java website.



How hacker try to hack your site?

  • Check server loop holes. (Server vulnerable)
  • Cross the validation of site by disabling scripts. (Site vulnerable)
  • Wrong inputs

Above are the simple way the hacker try to gain access in your site. The advance hacker can hack site by cracking server.

Note: Chinese Hacker can hack Google, This tips helps but not assure that its provide full protection. 

  • Choose best server

    • - If you are planning to host your java site. Please choose best server, ensure server's security. I prefer to use www.eatj.com
    • - Planning to set up your own server. Use best anti virus, Strong firewall, Close all loop holes.

  • Cross - Validation

    • - Validation must required for the site.
    • - Client - Server both side validation to protect site.
    • - If you created javaScript to validate email, hacker disable the javaScript and give wrong input. When request come to server check email on server side also.

  • File Upload (If allowed to users)

    • - User not allowed to upload  ( .jsp, .java, .class, .jar ).
    • - Suppose if user allow to upload .jsp file then hacker can read other .jsp page using file reader. It'll print all your .jsp page code.

  • Check each and every input with proper validation at server side.

  • Handle all errors with proper output.(Display error pages)

    •    505 - Shows database query error on webpage and shows all code of page.
    •    404 - Content not found

If you have other idea you can comment it. This will help other to secure site built in java platform.

How to upload file using JSP / Servlet?


Technology world moving fast as a speed of light. Its getting change day by day. Web application is build under the MVC ( Model-View-Controller) model. Colleges still using servlet in study. In below article we'll discuss how you can manage your web application to upload files.

Required .jar files
import bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

All above packages you have to import in you servlet. Below code is for file upload in servlet. File upload directory is "/upload/"

List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/upload/");
//Change upload with your directory
HttpSession session = request.getSession(true);
try {
 if (ServletFileUpload.isMultipartContent(request)) {
 ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
       try {
        fileItemsList = servletFileUpload.parseRequest(request);
       } catch (FileUploadException ex) {
        Logger.getLogger(FileUploadExample.class.getName()).log(Level.SEVERE, null, ex);
        //Change above line replace FileUploadExample with your file name
           }
           String optionalFileName = "";
           FileItem fileItem = null;

           Iterator it = fileItemsList.iterator();
           while (it.hasNext()) {
           FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
               if (fileItemTemp.getFieldName().equals("filename")) {
                  optionalFileName = fileItemTemp.getString();
               }
             /*
             * If you want to pass some other data from JSP page. You can access then in this way.
             * For each field you have do create if like below.
             * if (fileItemTemp.getFieldName().equals("Name of other field like:Firstname")) {
             * String Firstname = fileItemTemp.getString();
             * }
             */
            } else {
                  fileItem = fileItemTemp;
            }
         }
         if (fileItem != null) {
           long size_long = fileItem.getSize();
           filesize = size_long / 1024;
           filesize = filesize / 1000;
           //If you want to limit the file size. Here 30MB file size is allowed you can change it
           if (filesize > 30.0) {
           //Pass error message in session.
           setNotification _sN = new setNotification();
           _sN.setError("File size can't be more than 30MB");
           session.setAttribute("error", _sN);
           } else {
           _fileName = fileItem.getName();
           if (fileItem.getSize() > 0) {
              if (optionalFileName.trim().equals("")) {
                _fileName = FilenameUtils.getName(_fileName);
              } else {
                _fileName = optionalFileName;
              }
               _fileLink = "../upload/" + _fileName;
               try {
                File file = new File(new File(_uploadDir + "/"), fileItem.getName());
                fileItem.write(file);
               } catch (Exception e) {
                e.printStackTrace();
               }
               setNotification _sN = new setNotification();
               _sN.setError("File Uploaded to : " + _fileLink + "");
               session.setAttribute("error", _sN);
                }
               }
              }
             String referer = request.getHeader("Referer");
            response.sendRedirect(referer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

Now notification class to shows the message to users. Use the below code.
public class setNotification {
    private String Error="";
    public String getError() {
        return Error;
    }
    public void setError(String Error) {
        this.Error = Error;
    }
}

The JSP file. Change the servlet name in action (form). Change package import bean.setNotification.
<%@page import="bean.setNotification"%>
<%
            setNotification _sN = new setNotification();
            if (session.getAttribute("error") != null) {
                _sN = (setNotification) session.getAttribute("error");
            }

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>File Upload Example</title>
        <link type="text/css" href="css/bundle.css" rel="StyleSheet"/>
    </head>
    <body>
        <center>
            <div class="signal_box" style="width: 400px;height: 150px">
                <div class="head">File Upload - javaQuery.com</div>
                <form action="FileUploadExample" method="post"  enctype="multipart/form-data">
                <input type="file" name="myFile"/><br/>
                <input type="submit" value="Upload it"/>
                </form>
                <br/>
                <%=_sN.getError()%>
                <%_sN.setError("");%>
            </div>
        </center>
    </body>
</html>
So this is file upload example in servlet.....

How to get visitors IP address in Java?


This is tough task i searched around the Google , Tones of codes but after so many test i got the solution for this. This is very simple let me explain how you can get IP address of visitor. There is questions of programmers like "how to get client's IP Address in Java?"








  • I know you tried "request.getRemoteAddr()" but its not working and give you 127.0.0.1 as an output.
Sample code to get IP address

request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }

This code works perfectly i tested it on my server. Now you have IP address but after that question is how to get Country, City, Latitude, Longitude using Java? This will be done by javaQuery API. For that u can try below code.

Important notice for existing user (javaQueryAPI 7.0 or less) : Please check the new changes in javaQueryAPI 8.0 before installing API in your project.

/*
* javaQueryAPI 7.0 or less
*/
import javaQuery.j2ee.GeoLocation
request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }
GeoLocation gl = new GeoLocation();
gl.GetGeoLocationByIP(ipAddress);
String country = gl.Country;
/*
* javaQueryAPI 8.0 or above
*/
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;

request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }
        GeoLocation $gl = javaQueryBundle.createGeoLocation();
        $gl.MAPTargetByIP("117.204.232.104", "This is Demo. You can set even NULL");
        System.out.println($gl.Latitude);
        System.out.println($gl.Longitude);
        System.out.println($gl.Country);
        System.out.println($gl.City);
        System.out.println($gl.State);
        System.out.println($gl.GoogleMap_URL);
        System.out.println($gl.GoogleMap_URL_Bubble);
   
/*
* output
* 23.0333
* 72.616699
* India
* Ahmedabad
* Gujarat
* http://maps.google.com/maps?q=23.0333,+72.616699+(117.204.232.104)&iwloc=A&hl=en
* http://maps.google.com/maps?q=23.0333,+72.616699+(This is Demo. You can set even NULL)&iwloc=A&hl=en
*/

Some of users facing that its not working. It won't work on local machine as it won't resolve the data for 127.0.0.1 . Upload your file on server and access page through any browser.

Check out the http://www.javaquery.com/p/javaquery-api.html for download.