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.

URL shortening using tinyURL- An API for Java / JSP / Servlet - Unofficial API

Tiny URL Logo


Are you sick of posting URLs in emails only to have it break when sent causing the recipient to have to cut and paste it back together? API will create a tiny URL that will not break in email postings and never expires.

This is an unOfficial tinyURL Java API for link shortening.

Turn this URL:
http://www.amazon.com/Kindle-Wireless-Reading-Display-Globa lly/dp/B003FSUDM4/ref=amb_link_353259562_2?pf_rd_m=ATVPDKIK X0DER&pf_rd_s=center-10&pf_rd_r=11EYKTN682A79T370AM3&pf_rd_ t=201&pf_rd_p=1270985982&pf_rd_i=B002Y27P3M

into this TinyURL:
http://tinyurl.com/KindleWireless

Which one would you rather cut and paste into your browser? That's the power of TinyURL!

Terms of use
TinyURL was created as a free service to make posting long URLs easier, and may only be used for actual URLs. Using it for spamming or illegal purposes is forbidden and any such use will result in the TinyURL being disabled and you may be reported to all ISPs involved and to the proper governmental agencies. This service is provided without warranty of any kind.

For more information visit www.tinyurl.com
import javaQuery.j2ee.tinyURL;

public class tinyURLTest {
    public static void main(String[] args) {
        tinyURL tU = new tinyURL();
        String getLink = tU.getTinyURL("www.javaquery.com");
        System.out.println("Short Link:"+getLink);
    }
}
//output:
//Short Link:http://tinyurl.com/6kuhl6j


GeoLocation - javaQuery API

I've been working on my personal project. It needs to track down the visitors of website. I searched couple of query on Google but couldn't work for me so I created my own API to track down the users. I'm sharing this API with you guys. Please make note that I'm using open source website to track users but it allows you only 3000 request per day.

Now lets jump to code conclusion. Users already using javaQueryAPI 7.0 or less. I've made major changes in javaQueryAPI 8.0 so when you import new API keep in mind that you must change your existing code that uses javaQueryAPI.
/*
* 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. I'm working on API that allows you to track the user location based on mobile information. I'll publish ASAP. till then happy coding.

Read the related Article :

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

Review of Godday for Java/JSP/Servlet Hosting

GoDaddy Logo


This is personal experience for hosting JAVA on Godaddy. You find so many site for hosting JAVA and Godaddy is very famous site. Even Google uses Godaddy for domain registration and All.But one thing I must inform you.

"Don't Go with Godaddy for JAVA shared hosting"

I hosted site of JSP/Servlet on GoDaddy with below configuration.

  • Plan : Hosting - Shared - Deluxe - Linux 
  • Language : JAVA
  • Space : 15 GB
  • Bandwidth : Unlimited
  • Email : 5 
  • Domain Transfer Cost : Rs. 369.80 ( $7.56 )
  • Web space : Rs. 4857.67 ( $99.28 )

But be careful to go with Godday Shared hosting because it has major issue of File permission. When you try to create Directory / Upload file it shows you the below error.
HTTP Status 500 -
type Exception report

message
description The server encountered an internal error () that prevented it from fulfilling this request.

exception
javax.servlet.ServletException: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:284)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:157)
java.security.AccessController.doPrivileged(Native Method)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
sun.reflect.GeneratedMethodAccessor363.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:592)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:239)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:266)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:213)

root cause
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:361)
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
alien.processRequest.updateRequest.processRequest(updateRequest.java:74)
alien.processRequest.updateRequest.doPost(updateRequest.java:220)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
sun.reflect.GeneratedMethodAccessor359.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:592)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:239)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:266)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:157)
java.security.AccessController.doPrivileged(Native Method)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
sun.reflect.GeneratedMethodAccessor363.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:592)
org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:239)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:266)
org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:213)
note The full stack trace of the root cause is available in the Apache Tomcat/5.0.27 logs.

Apache Tomcat/5.0.27

Tried following solution:
  • 100 + times Google search 
  • 150 + Website Visit
  • 40-50 email to Godaddy Technical team
  • 1 time I Called to technical team (6 minutes)
  • Callback from Godaddy (30 minutes of discussion)

Result : NO Solution (Refund Money)
So if you are getting this error contact the GoDaddy technical team you want refund your money. This problem can't be solve by GoDaddy technical support so As soon as possible try to get your money back without wasting single day on solving issue. I emailed so many time to GoDaddy and they couldn't and the last came with refund of your money of remaining time period of hosting.

Refund Email


My suggestion:
  • Stop wasting time for solution try to get refund.
  • Don't Go with Godaddy.com shared JAVA hosting.

How to send mail from Godaddy? - Java Mail

Hello folks if you are using Goddady as you hosting site for JSP, Servlet, etc...We need to send mail from our domain to users. I'm giving you the steps how you can send mail using Java from your domain on Godaddy.

Step 1 : Login to your Goddady account
Step 2 : Login to web mail . To login click on Check my web mail.


Step 3 : Now You need your SMTP (Simple Mail Transfer Protocol) URL. Goto Help menu Click on Email Client


That will pop up your domain Incoming and Outgoing server URL


Now you need SMTP server URL : smtpout.asia.secureserver.net (*This is for my domain it may different for your domain)

Now the Code. I'm giving you the sample code. Change it as your domain.

private static final String SMTP_HOST_NAME = "smtpout.asia.secureserver.net"; //smtp URL
private static final int SMTP_HOST_PORT = 465; //port number
private static String SMTP_AUTH_USER = "Username"; //email_id of sender
private static String SMTP_AUTH_PWD = "Password"; //password of sender email_id

try {
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(true);
    Transport transport = mailSession.getTransport();
    MimeMessage message = new MimeMessage(mailSession);

    message.setSubject(Subject);
    message.setContent("Message that you want to send", "text/html");
    Address[] from = InternetAddress.parse("abc@your_domain.com");//Your domain email
    message.addFrom(from);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("abc@javaquery.com")); //Send email To (Type email ID that you want to send)

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
} catch (Exception e) {
 e.printStackTrace();
}
This is how you can send email from your Godaddy account. You need the API of Javamail Download from here http://www.oracle.com/technetwork/java/index-138643.html. Include it to lib folder.

How to pass object from Servlet to JSP?



To pass an objects from Servlet to JSP you can use session. You can pass simple object, List, etc... in session but you have to cast to its original type at JSP.

//Servlet Code
setNotification _sN = new setNotification();
_sN.setError("Your message");
request.setAttribute("error", _sN);
RequestDispatcher rd = request.getRequestDispatcher("./settings.jsp");
rd.forward(request, response);

//JSP Code
<%
setNotification _sN = new setNotification();
if (request.getAttribute("error") != null) {
 _sN = (setNotification) request.getAttribute("error");
}
%>
<%= _sN.getError()%>

How to read webpage / URL using java code?

Some of you think how facebook shows the webpage. It actually retrieve the content of the page. how to read webpage in java code/Program?

Some time we need to retrieve the data of web page when there is data in XML format. You can also read the page using java here I'm putting sample code that will help you to read the page line by line.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

public class readURL  {
    public static void main(String[] args) {
        String generate_URL = "http://www.javaquery.com";
        String inputLine;
        try {
            URL data = new URL(generate_URL);
            /**
             * Proxy code start 
             * If you are working behind firewall uncomment below lines. 
             * Set your proxy server
             */

            /* Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.0.202", 8080)); */
            /* HttpURLConnection con = (HttpURLConnection) data.openConnection(proxy); */
            
            /* Proxy code end */
            
            /* Open connection */
            /* comment below line in case of Proxy */
            HttpURLConnection con = (HttpURLConnection) data.openConnection(); 
            /* Read webpage coontent */
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            /* Read line by line */
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            /* close BufferedReader */
            in.close();
            /* close HttpURLConnection */
            con.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run the above code that will give you source code of that page. Now modify the above code as per requirement. It'll read the data in all the type. XML,HTML,etc...

Use of Proxy
You need to take care for proxy connection and it depends upon whether you are writing program for applet or desktop application. If you are writing code for applet then in production applet, you don't need proxy connection as server will have all access and will work without proxy. If you are working on desktop application that run within the Local Area Network then you must set proxy in case of firewall.

How to create master page in Java/JSP ?


Hello Java developer you face many problems regarding the developing site and you have to maintain design for all the page as a same. ASP .Net supports master page but what about JSP. I'll show you how you can create master page for your site.

The API that helps to create the master page is "SiteMesh" developed by Open Symphony. You want to check out the site click here . We'll discuss sitemesh 2 series. Yet not tested sitemesh 3.

Download JSTL : http://goo.gl/6uzwCJ

Sitemesh is a java web application development framework developed by Open Symphony.

Some time website uses the same menu and other content to all pages. Example  like Menubar in head of the page it'll be used on every page ti navigate the site. Template(Master Page) comes here to apply certain design to every page of domain.

How it works?

Step 1: Create blank JSP page. Include taglib at the top. You can copy paste below code. This will be the master page.
<%@taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fn" %>

Step 2: Sample code of master page.
<%@taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fn" %>
<%@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><decorator:title/></title>
   </head>
   <body>
      <decorator:body/>
   </body>
</html>

Step 3: Configure the sitemesh to pass request of the page through the template/master page. Create decorators.xml file in WEB-INF folder as follow.
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/template">
    <decorator name="main" page="template1.jsp">
       <pattern>/Folder_name/*</pattern>
       <pattern>/Folder_name2/test.jsp</pattern>
    </decorator>
</decorators> 
  • - defaultdir : Path of template/master page
  • - page : Template/master page that will be applied to pages
  • - /Folder_name/* : The URL pattern (Directory) on which the template/master page will be applied.if we use /* so all request pages pass through the template and it'll be applied to all page.   
  • - /Folder_name2/test.jsp : Template/master page will render only test.jsp file of Folder_name2 directory. Other file will be displayed as normal page.

Step 4: Configure the web.xml file. Append the below code in web.xml file.
<filter>
    <filter-name>sitemesh</filter-name>
    <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>sitemesh</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

  • - /* : Template applied to all page extension.
  • - /.html : Template applied to only on html page.


How to get value from database without refreshing JSP page?

There are situations when you need data without refreshing current page. We can achieve this using jQuery or AJAX. Following example demonstrate it using jQuery.

test.html
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script>
            $(document).ready(function(){
                 $("#users").change(function(){
                     var value = $(this).val();
                     $.get("data.jsp",{q:value},function(data){
                      $("#javaquery").html(data);
                     });
                 });
             });
        </script>
    </head>
    <body>
        <select id = "users">
           <option value="">Select Account ID</option>
           <option value="0">0</option>
           <option value="1">1</option>
        </select>
        <br />
        <div id="javaquery"><b>Name will be displayed here</b></div>
    </body>
</html>

data.jsp
<%
   String name = "";
   String q = request.getParameter("q");
   try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/javaquery", "username", "password");
        Statement smt = con.createStatement(); //Create Statement to interact
        ResultSet r = smt.executeQuery("select * from users where(AccountID='" + q + "');");
        while (r.next()) {
          name = r.getString("name");
        }
        con.close
   } catch (Exception e) {
        e.printStackTrace();
   }
%>
Name:<%out.print(name);%>
Output:
jquery, ajax

jquery, ajax

Free JSP/Java hosting [updated: 16/03/2013]

               So many Java developer have question about free JSP,Servlet,Java hosting. After visiting so many site i found one perfect solution that works fine for my application. I'll give you step by step procedure to publish your site for demo. You'll find so many free hosting site but they will give you free hosting for month after you pay but for demo we need not pay from now.


Open site : http://free.hostingjava.it. Its Italian website so you won't understand language but don't worry. To understand all options of this website i divided tutorial in 4 different sections.

Section 1: How to register on http://free.hostingjava.it ?

Step 1: Register your self for free account. Fill required information to register. You must agree both conditions to processed further. I recommend you not to upload sensitive and personal database on website. This is for testing purpose only. Check out the below image for reference.


Section 2: How to manage database on http://free.hostingjava.it.

Step 1: Open Mysql from left side link and login with username and password of your account.


Step 2: Open your database from left side panel. Admin panel of MySql shown in below image.


Step 3: Create table with column you want.


Step 4: Create column with datatype you want for your table.


Step 5: Inserting data for sample application.


Section 3: How to create web application on http://free.hostingjava.it with database access?

Step 1: Get database connection link. Its available on website when you logged in user Tips and Hints section. It differ from user by user.

/*
* Its differ user by user.
* Get it from website itself.
*/
javax.sql.DataSource ds=
(javax.sql.DataSource)new javax.naming.InitialContext(). lookup("java:comp/env/jdbc/javaQuery"); 
ds.getConnection();

Step 2: Sample code to access database.

<%
import java.sql.*;
 try {
      Class.forName("com.mysql.jdbc.Driver");
      javax.sql.DataSource ds=(javax.sql.DataSource) new javax.naming.InitialContext().lookup("java:comp/env/jdbc/javaQuery");
      Connection con = ds.getConnection();
      PreparedStatement stmt = con.prepareStatement("select * from javaQueryDEMO limit 0,1");
      ResultSet rs = stmt.executeQuery();
      if (rs.next()) {
 out.print(rs.getString(1));
      }
      con.close();
     } catch (Exception e) {
       e.printStackTrace();
 }
%

Section 4: How to upload file on website http://free.hostingjava.it.

Step 1: You must have FTP software to upload files.
Step 2: FTP URL : ftp://javaQuery@free.hostingjava.it/ change this URL with your username or you can get it from admin panel of the website.
Step 3: Username and password is same as register on website.
Step 4: Upload appropriate file on web directory.

How to send mail using JAVA?

SMTP, Java Mail
Mail is one of the important part of any application. Mail service helps you to notify important update to your users. There are lots of mail service provider over internet now a days. Choose one that fulfill your all requirements. They all follow almost similar way for mail delivery.

//imports required in below code.
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
private static final String SMTP_HOST_NAME = "smtp.gmail.com"; //smtp URL
private static final int SMTP_HOST_PORT = 465; //port number
private static final String SMTP_AUTH_USER = "email_ID"; //email_id of sender
private static final String SMTP_AUTH_PWD = "password"; //password of sender email_id

try{
    Properties props = new Properties(); 
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(true);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("Java Mail");
    message.setContent("Type_your_msg_here","text/html");
    message.addRecipient(Message.RecipientType.TO,new InternetAddress("abc@javaquery.com"));

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
    transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.close();
} catch (Exception e) {
    e.printStackTrace();
}
Important Note: Change your SMTP Host, SMTP port, Email ID from you want to send mail, Email Password and Message, To, Subject, Content type details in above code.