Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday 16 August 2014

CAFEBABE - Print the magic number from Java class file

Isn't it interesting to know that Java class files have a 4 byte header which could be read as CAFEBABE in Hexadecimal. This is being mentioned in Wikipedia: Java class file.

Have you ever tried printing this secret code out? If not, let's do that.

Below is the code which reads it's own class file and prints the code to output stream.

 package com.javavirtues.cafebabe;  
 public class PrintHeader {  
      public static void main(String[] args) {  
           File classFile = new File(  
           if (classFile.exists()) {  
                System.out.println("Class file exists. Reading header.");  
                byte[] readHeader = new byte[4];  
                FileInputStream fileInputStream = null;  
                try {  
                     fileInputStream = new FileInputStream(classFile);  
                     for (byte readByte : readHeader) {  
                          System.out.printf("%02X", readByte);  
                } catch (IOException exception) {  
                } finally {  
                     if (fileInputStream != null) {  
                          try {  
                          } catch (IOException e) {  

You can download the eclipse project here.

Sunday 20 January 2013

Java Web Application using Eclipse

Java's web technology provides us the facility to create dynamic web applications easily with the components it provide. Servlets play an important role in Java web application development by providing the developer with its options to hold the client request, pass it to the handled method and send the response to the client. This document will help you in understanding the architecture better.

Before starting web development, the developer should understand the request flow. All requests from the client (web browser) to server happens through HTTP methods defined by the protocol. GET and POST are the methods which are commonly used to pass the request. Each request contains an action and may have parameters sent to the server to perform specific operation. For example, in a login operation, the action would be loginaction and the parameters passed can be user-name and password.

Once the server processes the request, it responds back to the client with a status code saying if the operation was successful, a content type which helps browsers to show the response as html, pdf, zip etc. and optional message body.

Another important matter to be noticed is that the Java Server Pages (JSP) should be thought only in the scope of web server. The contents of the JSPs will get transformed to html elements before being served to the browser as response.

Moreover, web.xml, residing in the WEB-INF folder is the major configuration file. You will come across this file as we go forward.

Here we start developing a hello world web application using Eclipse. Assuming that you have configured a web server on your Eclipse IDE. If you have not, you can follow this link to configure JBoss web server.

This Eclipse project can be downloaded here. You can extract the file and use File > Import to download the project into your Eclipse workspace.

  1. On Eclipse, go to File > New > Project.
  2. Under Web, choose Dynamic Web Project and choose Next.
  3. Name your project and click Next.
  4. Click Next, choose your context root and content directory, and then click Finish. Context root is what you will use to access the application from a browser client. Content directory is where you will create your web pages and other resources such as images and javascript files.

    We have successfully created a web project. Next is to write a Servlet to handle requests.
  5. Right-click on the project, choose New > Servlet.
  6. Name the package, then the Servlet and click Next.
  7. Type any description, edit the default URL mapping and click Next.
  8. Choose the methods to handle the types of requests and click Finish.

    If you look into web.xml contents, you will find that the Servlet which we created is mapped to the URL we had provided in the above step. Whatever requests arrives to the application in the url-pattern we have specified will be set to be handled by the mapped Servlet instance. Our Servlet extends from HttpServlet. Go through the javadoc of HttpServlet and GenericServlet to find the basic methods and their descriptions. I have chosen to get hold of service, init and destroy methods just to print the life-cycle of this Servlet. Hence, the method call will be directed to the super class for actual processing.

  9. In the doGet method, write the code to handle the request.
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      System.out.println("In the doGet(HttpServletRequest request, HttpServletResponse response) method of HelloWorldServlet");
      PrintWriter printWriter = response.getWriter();
      printWriter.print("<html><head></head><body>Hello World</body></html>");
  10. Create a JSP file as referred in web.xml's welcome-file-list. The first available among them will be be displayed by default on visiting the context root. Right-click on the project, choose New > JSP File or from New > Other > Web > JSP File.
  11. Select WebContent folder or the contents folder mentioned in step 4, type the file name and click Next.
  12. By default, the JSP file will be opened in your editor. Modify the title as you wish.
  13. Add the following code snippet in the body part of JSP and save the file.
      Object message = request.getAttribute("message");
      if (message == null) {
     <form action="sayHello" method="post">
      <input type="submit" value="Submit" />
      } else {
  14. Edit the doPost method of Servlet as
     protected void doPost(HttpServletRequest request,
       HttpServletResponse response) throws ServletException, IOException {
        .println("In the doPost(HttpServletRequest request, HttpServletResponse response) method of HelloWorldServlet");
      request.setAttribute("message", "Hello World through post");
      RequestDispatcher requestDispatcher = getServletContext()
      requestDispatcher.forward(request, response);
  15. Let us try running the application. Right-click on the application and choose Run As > Run On Server and click Finish.
  16. On your browser, go to http://<server-host-name>:<port>/<contextpath>. In my case http://localhost:8080/MyHelloWorldWeb.
  17. You will see a Submit button because web.xml is blindly set to show the welcome file. The content of the file tries to get the request attribute named message, which will be null since the request has not gone to the doPost method.
  18. Click on the Submit button and see the server log on the console. The doPost method would be called and message will be passed to index.jsp, which behaves in a different way.
  19. Try the URL contextpath/sayHello and check the log to see the request being handled by doGet method.
  20. From the Servers view of Eclipse, expand the server, right click on the web application and say Remove.
  21. Look at the console to see the message given to print at destroy method being called which completes the life-cycle of the Servlet.

Configuring JBoss server on Eclipse

JBoss application server is a server which offers Java Enterprise Edition services to web applications authored in Java language.

Here are the steps to configure JBoss server on Eclipse:

  1. Download JBoss server from here. I have chosen the 4.2.3 version of JBoss server to download.
  2. Extract the downloaded compressed file to a suitable location. I have extracted the file to /opt.
  3. On Eclipse, go to Servers view. If you do not see Servers view, go to Window > Show View > OtherOn the Show View window, choose Server > Servers and click OK.
  4. Click on new server wizard or right-click and choose New > Server.
  5. Choose JBoss > JBoss v4.2 and click Next.
  6. To set the Application Server Directory, click Browse or type the path to the extracted server folder in step 2 and click Next.
  7. Choose address, port, JNDI port and server configuration and click Next. I have left it as default values here.
  8. If you have any web application to be set to run on the server, add them and click Finish. You will find the server being listed in the Servers view.
  9. Double click on the server listed in the Servers view or right-click and choose Open.
  10. The server can be configured in the window opened up. Expand the Timeouts section and modify the Start and Stop values. These are the values in which the server has to start-up or shutdown as monitored by Eclipse. You may need to increase these timings, otherwise you will end up with an error saying server could not be started as displayed below. Once done, save the configuration from File > Save.

  11. Right-click on the server from Servers view and choose Start.
  12. Monitor the Console view to see if the server has started successfully.
  13. Test the server from browser by going to the host name and port configured.

Saturday 19 January 2013

Java standalone application on Eclipse

Java standalone application would be the easiest one to start when learning the language. We will print "Hello World" text on the console as the first step.

Java standalone applications should have at least a class with main method, in the right signature. This is the first method that will take the handle of the application when called by Java Virtual Machine. Here we go.

  1. On your Eclipse IDE, click on File > New > Project.
  2. Choose Java > Java Project and click Next.
  3. Key in the project name and click Finish.
  4. From the Package Explorer, right click and create new Class.
  5. Name your new Class. If you need to place the new Class in a package, fill-in the package name. Since this is your Main class, you can check "public static void main(String[] args)" under "Which method stubs would you like to create?". I would not select this option now.
  6. You will find your Main class being opened in the editor. You can type the entire signature of the main method or just type main, then use Ctrl + Space to show the proposed templates and choose main method to generate the main method.
  7. Type the statement to print "Hello World" statement on the output stream. That is, System.out.println("Hello World");. The template way to type the statement is sysout and using Ctrl + Space.
  8. Format the code snippet using Source > Format or Ctrl + Shift + F and save the file.
  9. Right-click on the project or the class and use Run As > Java Application to run the file.
  10. See the console. If console could not be found, select to show it from Window menu.

Sunday 30 December 2012

Setting up Java Development Environment (JDK) on Linux

Java Development Kit (JDK) is essential for developing Java applications on your computer. JDK consists of many tools which can make your development easy and comfortable, especially when you do not have an Integrated Development Environment (IDE) such as Eclipse or NetBeans.

Here, I will mention about setting up JDK on CentOS 64 bit Operating System. However, the steps of installation are common on most of the Linux flavors.


  1. Visit Oracle website to download the installation file.
  2. Click on the "Download" button at the JDK section to download the latest release of JDK. If you are looking for a previous version of JDK, you can visit the "Previous Releases" section on the same page. If you could not locate the section, you can search for "Previous" keyword on the page using the Ctrl + F key combination supported by most browsers.
  3. Accept the license agreement and choose the download. Determine your Operating System architecture bit length by executing getconf LONG_BIT or uname -m command on console. CentOS uses RPM based package management. Hence, you can download either .rpm or the zipped package. The steps of path configuration varies with the kind of package you choose.
  4. Follow the below steps according to the package you have downloaded:

RPM Installation:

  1. Switch to root user using su command.
  2. Copy the downloaded file to a location or navigate to the directory.
  3. Use rpm -ivh jdk<version>-<XXbit>.rpm to start the installation.

While installing JDK 7, you may find the errors being displayed as in the above image. These can be ignored. You can verify the installation using the java -version command and you are done.

Compressed Package Installation (tar.gz):

  1. Execute su command to switch to root user.
  2. Use tar <download-path>/<jdk<version>-<XXbit>.tar.gz -C /usr/java to extract the contents to the installation location. If /usr/java does not exist, you may create the directory using mkdir /usr/java.
  3. Once extracted the contents, you are done with the basic installation. You can follow the section to set the PATH environmental variable.

Binary File Installation:

Packages are available with .bin extension. They can be installed by executing them from the shell.
  1. Switch to root user with su.
  2. Copy the installation file to a location.
  3. Add execution permission to the file using chmod u+x jdk<version>-<XXbit>.bin command.
  4. Execute the file using shell. 
  5. Follow the prompts for installation.
  6. Move the installation folder to /usr/java. Create the folder if it does not exist.
  7. Follow the steps in the section to set the PATH variable.


Setting PATH variable:

While installing the package other than from rpm, you will need to set the PATH environmental variable to run the java development tools from console. Extra care should be taken while performing the steps below.

  1. Copy the path where you have java installed; remember to omit the '/' at the end. Usually on /usr/java/jdk<version>. This becomes the path for JAVA_HOME environmental variable.
  2. Edit /etc/profile file using an editor such as vi to set the PATH variable for all users, on their log in. Locate the section where the PATH variable is exported.
  3. Add line defining JAVA_HOME, append $JAVA_HOME/bin to PATH variable and include JAVA_HOME to the export command.
  4. Save the file and exit the editor.
  5. Source the file to reflect the changes in the current console window.
  6. Verify if java command works.