Sunday, June 20, 2010

Set Environment variables - PATH, CLASSPATH, JAVA_HOME, ANT_HOME in Ubuntu

Setting Environment variables in Ubuntu can be tricky. It comes with OpenOffice which requires OpenJDK, so the path for java is set to that of OpenJDK. The command

$ java -version

works but uses the OpenJDK. Once you have installed Sun JDK the location of the JDK should be "/usr/lib/jvm/java-6-sun-1.6.0.20" depending upon the version you have installed. Once you have installed it you may want to update the PATH, CLASSPATH variables and create environment variables like JAVA_HOME, ANT_HOME, etc.

The location to set up the environment variables in Ubuntu is /home/Your_User_Name/.bashrc. You will need to make entries like:

JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.20
ANT_HOME=/home/harkiran/javaTools/apache-ant-1.8.1
PATH=$PATH:$ORACLE_HOME/bin:$JAVA_HOME/bin:$ANT_HOME/bin
CLASSPATH=.:/usr/lib/jvm/java-6-sun-1.6.0.20/lib
export JAVA_HOME
export ANT_HOME
export CLASSPATH
export PATH

The separator to use in Linux between PATH is ":" (colon). Windows uses ";" (semi colon).

Once you have set this up you will also need to create symbolic links in the "/etc/alternatives" directory. You will need administrative privileges to do so.

$ ln -s /usr/lib/jvm/java-6-sun-1.6.0.20/bin/java /etc/alternatives/java
$ ln -s /usr/lib/jvm/java-6-sun-1.6.0.20/bin/javac /etc/alternatives/javac

Once done you can check using the commands java -version, javac -version, ant to check all is working and has been set up properly.

Monday, May 3, 2010

How to fix ATI driver problem in Ubuntu 10.04

Recently I downloaded Ubuntu 10.04 and upgraded Ubuntu 9.10 to 10.04. I had tried the Live CD first to make sure that video and sound will work. After upgrading to Ubuntu 10.04, for some apparent reasons it did not liked the ATI driver and it wanted to run in low graphics mode. I had to restart X on each boot. To fix the problem I went to google to search for any available solutions and I found one. So, here is what worked for me:

  1. Open Terminal, and run the following command: sudo apt-get purge fglrx-modaliases fglrx-amdcccle fglrx-kernel-source xorg-driver-fglrx xorg-driver-fglrx-dev
  2. Now run the following command: sudo rm -r /etc/ati
  3. Now run: rm /etc/X11/xorg.conf*
  4. Now run: rm -rf /usr/share/ati
  5. Now open Synaptic and install fglrx package. If the installation fails then run sudo apt-get install -f in a Terminal window.
  6. Now run the command: sudo aticonfig --initial
  7. Now reboot your computer and the graphics should be working now.
Here is the original link to the solution: http://ubuntuforums.org/showpost.php?p=9062521&postcount=158


Monday, April 19, 2010

Converting String instance variables of any given object to uppercase

In this post I will describe how to convert all the String members of an object into uppercase. The same can be done to convert to lowercase. Creating a method in a class (JavaBean) can also solve this purpose, but when the JavaBeans are already available then modifying each class is a tedious process. This was exactly the problem that I was facing. Then I though of using something similar to the 'copyProperties' method of the 'BeanUtils' class in Commons BeanUtils.


The Java Reflection API came to assistance. Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

The 'java.lang.reflect' package provides various classes and methods which can be used to deeply examine an object, find out its member variables and  methods, invoke its setter and getter methods and much more. The below code will show how you can use the Java Reflection API to access the setter and getter methods of an object of any type and convert all the member variables of type 'String' to uppercase.

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionUtil
{
    public static void printValues(Object obj)
    {
 Class c = obj.getClass();
 
 Field fields[] = c.getDeclaredFields();
 Method method;
 String gMethodName, sMethodName, value;

 try
 {
      for(Field f : fields)
     {
                if(f.getType().toString().contains("java.lang.String"))
  {
      gMethodName = "get" + Character.toUpperCase(f.getName().charAt(0)) + f.getName().substring(1);
      method = c.getDeclaredMethod(gMethodName);
      value = (String) method.invoke(obj);
      System.out.println(f.getName() + ":" + f.getType() + ":" + value);
  }
   
     }
        }
 catch(Exception ex)
 {ex.printStackTrace();}
    }

    public static void convertToUpperCase(Object obj)  
    {
 Class c = obj.getClass();
 
 Field fields[] = c.getDeclaredFields();
 Method method;
 String gMethodName, sMethodName, value;

 try
 {
      for(Field f : fields)
     {
                if(f.getType().toString().contains("java.lang.String"))
  {
      gMethodName = "get" + Character.toUpperCase(f.getName().charAt(0)) + f.getName().substring(1);
      method = c.getDeclaredMethod(gMethodName);
      value = (String) method.invoke(obj);
      value = value.toUpperCase();
      sMethodName = "set" + Character.toUpperCase(f.getName().charAt(0)) + f.getName().substring(1);
      method = c.getDeclaredMethod(sMethodName, f.getType());
      method.invoke(obj, new Object [] {value});
  }
     }
        }
 catch(IllegalAccessException ex)
 {ex.printStackTrace();}
 catch(java.lang.reflect.InvocationTargetException ex)
 {ex.printStackTrace();}
 catch(java.lang.NoSuchMethodException ex)
 {ex.printStackTrace();}
    }

    public static void main(String... args)
    {
  Category category = new Category("abc", "cat name", null, "user", "code");
 System.out.println("\nCalling convertToUpperCase");
 ReflectionUtil.convertToUpperCase(category);
 System.out.println("\nCalling printValues");
 ReflectionUtil.printValues(category);
    }
}

For a detailed tutorial on Java Reflection API click here.

Friday, January 15, 2010

Creating a zip file

Creating a zip file in Java web application may appear to be a difficult task, but thanks to Java which comes bundled with many packages and classes which provide many useful utilities, tools and methods. One such package is the "java.util.zip" package which provides various classes and methods to manage zip files.

Following is an extract of code from a Servlet which can be customized and used to create zip files.


import java.util.zip.*;

// These are the files to include in the ZIP file
java.util.Set fileNames = new java.util.TreeSet () ; 

fileNames.add(csvFileName);
// add multiple files as above

/*
 * Creating a ZIP File
 */
     
  // Create a buffer for reading the files
  byte[] buf = new byte[1024];
  String outFilename="";
  fileName="";
  try 
  {
     // Create the ZIP file
     outFilename = getServletContext().getRealPath("/insurance") + "/" + "insurance.zip";
     ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outFilename));
     
     // Compress the files
     for(String str : fileNames)
     {
         FileInputStream in = new FileInputStream(str);
    
         // Add ZIP entry to output stream.
         fileName = str;
         fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
         zipOut.putNextEntry(new ZipEntry(fileName));
     
         // Transfer bytes from the file to the ZIP file
         int len;
         while ((len = in.read(buf)) > 0) 
            zipOut.write(buf, 0, len);
  
         // Complete the entry
         zipOut.closeEntry();
         in.close();
     }
     
     // Complete the ZIP file
     zipOut.close();
  }
  catch(java.util.zip.ZipException ex)
  {
      System.out.println("InsuranceReportArtistWiseServ:ZipException:creating zip\n"+ex);
  }
  catch(IOException ex) 
  {
      System.out.println("InsuranceReportArtistWiseServ:IOException:creating zip\n"+ex);
  }

  /*
   * Clean up - zip file ready to download, now delete all csv files
   */
    boolean success=false;
    for(String str : fileNames)
    {
    success = (new java.io.File(str)).delete();
    }
Now the "insurace.zip" file is ready to be sent as a download to the user.

Sending a file as a download using Java

Many times it may be a requirement to send a file from a server to a user as a download which can be saved on the users machine. To send a file as a download to a user all you need is a Servlet and the file which will be sent to the user. Below is a sample code for the Servlet which will send a file as a download.

private static javax.servlet.ServletConfig config;

/* (non-Javadoc)
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) throws ServletException 
{
    // TODO Auto-generated method stub
    super.init(config);
    FileDownloadServ.config = config;
}

private void sendFile(String fileName, HttpServletRequest request, HttpServletResponse response)
{
  java.io.File f = null;
  String file;
  
  file = FileDownloadServ.config.getServletContext().getRealPath("/" + fileName);
  f = new java.io.File(file);

  int length = 0;
  javax.servlet.ServletOutputStream op=null; 
  try
  {
      op = response.getOutputStream();
  }
  catch(java.io.IOException ex)
  {
      System.out.println("IOException while opening the output stream\n"+ex);
  } 

  javax.servlet.ServletContext context  = getServletConfig().getServletContext();
  String mimetype = "application/octet-stream";
  response.setContentType(mimetype);
  response.setContentLength( (int)f.length() );

  response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"" );
  //
  //  Stream to the requester.
  //
  byte[] bbuf = new byte[1024];
  try
  {
     java.io.DataInputStream in = new java.io.DataInputStream(new java.io.FileInputStream(f));

     while ((in != null) && ((length = in.read(bbuf)) != -1))
     {
      op.write(bbuf,0,length);
     }

     in.close();
     op.flush();
     op.close();
  }
  catch(java.io.IOException ex)
  {
     System.out.println("IOException while reading file!\n"+ex);
  }
}     

The above method when called from a Servlet's doPost() or doGet() with fileName as parameter will sent the file to the user.