Friday, October 26, 2012
--------------------UPDATE-------------------
I have updated my post so that now it can detect IE 11. This modification was necessary as the user-agent of Internet Explorer 11.0 was changed. So check the new code which has an additional if-else block in class BrowserRecognitionModel .
---------------------------------------------------
Today I am going to post program which will be able to detect client's browser details i.e. browser name and version using servlets and JSPs. First of all, user-agent header is extracted and then string processing is done to obtain browser name and version.
Benefits : You will be able to detect which browser is being used by client. Moreover the whole application is being written following the MVC pattern.
BrowserRecogntionServlet.java : contains the code for extracting user-agent and hands it over to the model class and then forwards the result to the JSP and thus acting as controller.
BrowserRecognitionModel.java : contains the code that processes the string and gets the browser version and name.
 browserDetails.jsp : contains the code for showing result.

 Screenshots of output as seen in Chrome and Firefox :
Output in Chrome

Output in Firefox








--------------------------------------------------------------------------------------------------------------------------
SOURCE CODE
--------------------------------------------------------------------------------------------------------------------------
/* Code for servlet(BrowserRecogntionServlet.java) */
package detector.servlets;

import detector.model.BrowserRecognitionModel;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/detect.html")
public class BrowserRecognitionServlet extends HttpServlet{
    @Override
    public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
        String userAgent=req.getHeader("user-agent");
        /*passing data to model class */
        BrowserRecognitionModel browserDetails=new BrowserRecognitionModel(userAgent);
        /* setting attribute to request for the JSP */
        req.setAttribute("model",browserDetails);
        /* forwarding to JSP for output */
        RequestDispatcher view=req.getRequestDispatcher("/browserDetails.jsp");
        view.forward(req,res);
        }
}

/* Code for model class(BrowserRecognitionModel.java) */
package detector.model;

public class BrowserRecognitionModel {
    private String userAgent,browserName,browserVer;
    public BrowserRecognitionModel(String userAgent){
        this.userAgent=userAgent;
        process();
    }
    private void process(){
        browserName="unknown";
        browserVer="unknown";
        if(userAgent.contains("Chrome")){ //checking if Chrome
            String substring=userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0];
            browserName=substring.split("/")[0];
            browserVer=substring.split("/")[1];
        }
        else if(userAgent.contains("Firefox")){  //Checking if Firefox
            String substring=userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0];
            browserName=substring.split("/")[0];
            browserVer=substring.split("/")[1];
        }
        else if(userAgent.contains("MSIE")){ //Checking if Internet Explorer
            String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
            browserName=substring.split(" ")[0];
            browserVer=substring.split(" ")[1];
        }
        else if(userAgent.contains("rv")){ //checking if Internet Explorer 11
     String substring=userAgent.substring(userAgent.indexOf("rv"),userAgent.indexOf(")"));
     browserName="IE";
     browserVer=substring.split(":")[1];
 }
    }
    public String getName(){
        return browserName; //returning browser name
    }
    public String getVersion(){
        return browserVer;  //returning browser version
    }
}

/* Code for JSP(browserDetails.jsp) */
<html>
<head><title>Browser Details</title></head>
<%@ page import="detector.model.BrowserRecognitionModel" %>
<body>
  <h1>Browser Details</h1>
  <%
    BrowserRecognitionModel model=(BrowserRecognitionModel)request.getAttribute("model");
    String browserName=model.getName();
    String version=model.getVersion();
  %>
  <b>Browser Name : </b><%= browserName %></br>
  <b>Browser Version : </b><%= version %>
</body>
</html>

--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD LINKS
--------------------------------------------------------------------------------------------------------------------------
 DOWNLOAD the application(rar) from Mediafire
 DOWNLOAD the application(rar) from 4shared
Monday, October 15, 2012
Today I am going to post a program that will be able to change i.e control the brightness of any image in Java. First the image is read from a file using Java's ImageIO class (in javax.imageio package) as a BufferedImage. A function is written that takes in the image and brightness value as parameter. Inside it an object of RescaleOp class (in java.awt.image package) is created using the brightness value. Then the object's filter(src,dest) method is called and source image is passed (destination is kept null) and the final image developed is returned. This final image is drawn on a JPanel and shown in frame. Also this image is saved in a new file named dest.jpg in jpeg format using ImageIO class. Screenshots of the original and the brightened image is shown below

Original image
Brightened by 50%








--------------------------------------------------------------------------------------------------------------------------
 SOURCE CODE
--------------------------------------------------------------------------------------------------------------------------
import java.io.File;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import javax.imageio.ImageIO;

@SuppressWarnings("serial")
public class Brighten extends JPanel{
   @Override
   public void paintComponent(Graphics g){
      Graphics2D g2d=(Graphics2D)g;
      try{

          //reading image data from file
          BufferedImage src=ImageIO.read(new File("src.jpg"));
          /* passing source image and brightening by 50%-value of 1.0f means original brightness */
          BufferedImage dest=changeBrightness(src,1.5f);

          //drawing new image on panel
          g2d.drawImage(dest,0,0,this);

          //writing new image to a file in jpeg format
          ImageIO.write(dest,"jpeg",new File("dest.jpg"));
      }catch(Exception e){
            e.printStackTrace();
      }
   }


   public BufferedImage changeBrightness(BufferedImage src,float val){
       RescaleOp brighterOp = new RescaleOp(val, 0, null);
       return brighterOp.filter(src,null);
//filtering
   }
   
   public static void main (String[] args) {
       JFrame jf=new JFrame("BRIGHTEN");
       Brighten obj=new Brighten();
       jf.getContentPane().add(obj);
       jf.setVisible(true);
       jf.setSize(325,270);
       jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
    }
}

--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD LINKS
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire 
DOWNLOAD the source from 4shared
--------------------------------------------------------------------------------------------------------------------------
RELATED POSTS
--------------------------------------------------------------------------------------------------------------------------
Monday, October 8, 2012
Today I am going to post a program that will be able to show all the headers associated with a servlet request;  Here in the code request object is used to get an enumerations of headers associated with the request of the client. Then with a loop one by one all the headers are extracted and their corresponding values are available using the getHeader(String headername) method. All these headers and their values are sent to the client as a dynamically generated html. Also note that the values will differ according to the browser which has been used to send the request.
Screenshot of output as seen on Chrome in Windows7
Here is the code for you -->

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/header.html")
public class HeaderViewer extends HttpServlet{

   public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
          Enumeration headers=req.getHeaderNames(); 
/*getting enumerations of all headers */
          PrintWriter out=res.getWriter(); 
//getting writer
          out.write("<html><head><title>HeaderViewer</title></head>");
          out.write("<body><h1><center>Headers associated with your request</center></h1>");
         
          while(headers.hasMoreElements()){
                 String header=(String)headers.nextElement(); 
/*extracting header */
                 out.write("</br><b>"+header+" : </b>"+req.getHeader(header));
/* sending header name and its value to client */
          }
          out.write("</body></html>");
          out.close();
   } 
}
Sunday, October 7, 2012
Today I am going to post a hello world servlet program that uses latest Servlet3.0 technology. For all new users of this technology, I would like to mention that deploying your web-app has been made easy. With this technology you can use annotations to set the URL of your web-app now, which was only possible through deployment descriptor in their previous versions. So here I will post the simplest code to show how to use this method.

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;


/*http://localhost:8080/def/a/b/simple.html is the complete url when your server is running at port 8080 and your app directory is def */

@WebServlet("/a/b/simple.html") //this is relative URL
public class SimpleServlet extends HttpServlet {

   
    @Override
    public void doGet(HttpServletRequest req,HttpServletResponse res){

       try{
        PrintWriter out = res.getWriter();
/* getting writer yo send dynamic data to client */
        out.println(
            "<html><head><title>Servlet Demo</title></head><body> <h1><center>Hello World</center></h1></body></html>"); 
//sending html data
        out.close();
//closing writer
        }catch(Exception e){ e.printStackTrace();  }
    }

}

Note that we are not mapping servlet in DD but using annotation for that. The URL we are giving is a relative one and false. Client cannot access the file directly as it is inside WEB-INF directory. Also it is written in such a way that client will think its a static html page whereas it is a dynamically generated html by servlet behind the curtain. So we are achieving url hiding and deployment in a very easier way. So try it out guys.
Thursday, October 4, 2012
 Reasons for introducing the concept of packages in Java-->
1 : for better organizing of resources
2 : to avoid class name conflicts i.e. if there were no packages then it wouldn't have been possible to declare duplicate class names;
Convention of declaring packages--> package names are generally given according to reverse domain name. e.g.if your domain is javaingrab.blogspot.com then package is com.blogspot.javaingrab followed by your project and so on. This will prevent package name conflicts.
How to use packages--> First of all you will have to create a directory structure according to packages. e.g. for package com.blogspot.javaingrab directory structure is com/blogspot/javaingrab and so on. There is a keyword in java called package to declare a package. Now package statement should be the first line of your code. take a look at following code

package com.blogspot.javaingrab.xamples;
public class MyClass{
   public MyClass(){
      Sysytem.out.println("Package Demo");
   }
   public static void main(String[] args){
       new MyClass();
   }
}

How to compile with packages--> Generally sources are kept in a separate folder named src and classes in classes directory.Considering above example the directory would be like this /project/classes and /project/src/ and within src it will be src/com/blogspot/javaingrab/xamples and inside it will be MyClass.java file. Now if you are compiling from project directory command will be
C:\project javac -d classes -cp src src\com\blogspot\javaingrab\xamples\MyClass.java
-d switch : it is optional and is used if you want to place class files in a separate directory. This helps in automatic creation of directories according to your packages.
-cp switch : it means classpath. This is necessary only when your source requires other classes which may or may not reside in the same packages. Using this you can compile a particular class even if the dependent class resides in a different drive.
How to run with packages--> While running you will have to give the -cp switch followed by the dependent class file directory and then the fully qualified class name with package which you want to run. for the above class the command should be
C:\project java -cp classes com.blogspot.javaingrab.xamples.MyClass

WARNING : Do not mention about any package named directory as java compiler or JVM searches for the particular package inside the classpath. Yf you do this then it will be disastrous,so be careful.

Total Pageviews

Followers


Labels

Popular Posts

free counters