How to Convert Blob column to String in Java

How to Convert java.sql.Blob column datatype  to String in Java

 

Given below is the sample for all of you. Just sample exception handling is there and for production deployment code require modifications like cleaning up database connections and a proper exception handling.


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Blob;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class DBUtil{

    public void getEmployeeData(int employeeId){
        Connection databaseConn = getDBConnection();
        PreparedStatement pStmt = databaseConn.prepareCall("Select Employee_Summary from Employee where EmpID=?");
        pStmt.setInt(1, employeeId);
        ResultSet rs = pStmt.executeQuery();
        Blob blob = rs.getBlob("Employee_Summary");
       
        byte[] bdata = blob.getBytes(1, (int) blob.length());
        String empSummary = new String(bdata);
    }
   
 

    public Connection getDBConnection() {

        Properties properties = new Properties();
        Connection con = null;
        try {
            InputStream iStream = new BufferedInputStream(new FileInputStream("/home/application/db.properties"));
            properties.load(iStream);
            iStream.close();
            String driver = properties.getProperty("db.jdbcDriver");
            String dataSource = properties.getProperty("db.dataSource");
            String dbUserName = properties.getProperty("db.user");
            String dbPassword = properties.getProperty("db.password");
            try {
                Class.forName(driver);
                con = DriverManager.getConnection(dataSource, dbUserName,
                        dbPassword);
            } catch (ClassNotFoundException e) {
                LogManager.debug(DBUtil.class.getName(), " getConnection, ClassNotFoundException :" + e.getMessage());
            } catch (SQLException e) {
                LogManager.debug(DBUtil.class.getName(), " getConnection, SQLException :" + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            LogManager.debug(DBUtil.class.getName(), " getConnection, FileNotFoundException :" + e.getMessage());
        } catch (IOException e) {
            LogManager.debug(DBUtil.class.getName(), " getConnection, IOException :" + e.getMessage());
        }
        return con;
    }
 

}

 

 

Convert String Array to Arraylist

I was working on collections in one of my project and while working on copying arrays to collections found below two approaches to do it. These two approaches have their advantages as well as limitations.



Solution 1:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class StringArrayToCollectionSample
{
   public static void main(String[] args)
   {
      String[] strArray = new String[] {"Hello", "World", "Application"};
      List<String> strList = Arrays.asList(strArray);


   }
}

This approach will work fine if you only need read access to the array as if it is a List and you don't want to add or remove elements from the list. As it doesn't need to copy the content of the array. This method returns a List that is a "view" onto the array or you can say a wrapper that makes the array look like a list.Most important is that the list is of fixed size, i.e if you try to add elements to the list, you'll get an java.lang.UnsupportedOperationException.

Solution 2:
public class StringArrayToCollectionSample
{
   public static void main(String[] args)
   {
      String[] strArray = new String[] {"Hello", "World", "Application"};
      List<String> strList = new ArrayList(Arrays.asList(strArray));

   }
}

This approach will copies the content of the array to a new ArrayList. Advantage of this approach is that you can easily add or remove element from the List.

 

 

Basic Java Syntax and Rules

Basic Java Syntax

If we talk about the Java syntax, Than a basic will cover a Object name referring to an instance with a dot operator that separates the Object from message. "Message" in above sentence refers to fields or methods accessible to object. Always define the method name keeping in mind what it does. All statements are terminated by a semi-colon sign(;).

What is a Method

You can define it is a measurement unit code. It is a smallest unit of code. You can add comments before defining the method. It have following properties
  • Has a name.
  • Defines the parameters that are passed and their data type.
  • Define the visibility - Controlled by access modifiers like public, private, protected.
  • Defines the Behavior and what it is going to return, if someone access it.


Comments in Java can be Single line as well as Multi-line also. Single line comment starts with a two forward slashes(//) and ends at line end. Multi-line comment starts with a forward sign and an asterisk(/*) and ends with an asterisk and a forward slash(*/).

Java Statement
They are building blocks of code. Statement must be terminated by a semi-colon(;). A statement can be
  • An empty statement(Ex only ;).
  • Instance creation.
  • Variable assignment.
  • Operators that work on data.
  • Messages being send to object.
  • If block or while, for loop.

What is Block
Block is a group of statements defined between two curly braces({}). Block start with { and ends with }. Every statement inside a block is terminated by semi-colon.

Java Package
A Package is Java language component that contains classes. It is a directory structure, dots in package name defines the order of directory.

Java Class
To create a Java class either use an IDE(like Eclipse, Netbeans etc) or use any test editor. Only one public class is allowed per file. To save the Class remember File name is same as the public class name with .java as extension. To compile the file run the compiler javac.exe with source code file in a command prompt window.

If the file compiles without any errors then you will see another file name in same directory with .class as extension.


More Java Stories
Convert String Array to Arraylist



What is a Function Point

Function Points are a unit of measure like hour is to measuring time or inch is to measuring distance. A unit plays an important role in understanding and communicating metrics like average cost. In software application, we generally consider a screen or a report as a function point, But these are not. Instead Function Point is an elementary business process. From a project manager point of view measurement is necessary to manage a project. It also helps project managers to make project decisions.

What is Function Points Analysis or FPA?
Except the software industry all other industries are managed by unit cost. If you like to define Function Point Analysis, than You can say It is a
  • Structured technique of classifying components of a system.
  • Method to break systems into smaller components, so they can be better understood and analyzed.
  • Measures software by quantifying its functionality provided to the user based primarily on the logical design.
  • Logical functionality from a sophisticated user view rather than a physical view.
  • Standard method for measuring software development from the customers point of view.

Advantages of Function Point Analysis
  • Improves requirements documentation.
  • Improves the estimating process.
  • Improves the communication of workload.
  • Improves the understanding of business functions.
  • Improves traceability of requirements through implementation.
  • Improves the allocation of resources.

GRAILS - Installation and Configuration

Recently I got a chance to work on a project based on GRAILS. At first I was tense and even I have an argument with my Project lead, that why he is giving me a new challenge? Instead of listening to me he just told me learn the framework and build solution required by client as per requirement.

So at last I started goggling with the GRAILS, like searching for tutorials, how to configure it and on top How I am going to create application using Eclipse. At last when I had enough of the taste, I just thought of making a bunch of tutorials and keep it one place. Given below is the first part of tutorial covering the installation and configuring GRAILS at your own machine.

1. Configure Java

Before moving to installation of GRAILS ensure that you have a  Java installed, If not download it from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. After then configure the JAVA_HOME environment variable at your jdk installation directory. For Example if you installed jdk in C:\Java6\jdk1.6.0_10 then your JAVA_HOME variable will point to C:\Java6\jdk1.6.0_10. After then modify the environment variable PATH, In windows append %JAVA_HOME%\bin with a semi-colon(;) to it. Once it is done check by typing java -version at command prompt, If it is configured correctly It will be displaying the version you have installed.

2. Configure GRAILS

After installation and configuring JAVA, download the latest version of GRAILS from http://grails.org/Download. Unzipped the GRAILS zipped download in a new directory. Make sure none of the directory have blank space in them. After then create a new environment variable GRAILS_HOME and point it to your GRAILS directory. Example If you have unzipped GRAILS at C:\grails, then GRAILS_HOME will have the value C:\grails. Also modify the PATH variable and append %GRAILS_HOME%\bin to it(Windows).
Once it is done type grails at command prompt to verify that Grails is installed and ready to use. If successfully installed and configured it will display welcome message from GRAILS and will display the version installed.