Home » Utilities & Tools

Category Archives: Utilities & Tools


Java Console Input Example

This is a simple example of taking console input and invoking a method based on the user inputs. There are many ways to do this and couple of them are listed below.

1) Using  simple    java.io.BufferedReader;
2) Using     java.io.Console;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

* Sample Console Input example
* @author manjul
public class ConsoleInput {

public static void main(String[] args) throws IOException, InterruptedException {
  int in = takeInput();

  switch (in) {
   case 1:

   case 2:


private static int takeInput() throws IOException{
   StringBuilder sb = new StringBuilder();
   sb.append("Please Select an option: \n");
   sb.append("1: Show Songs\n");
   sb.append("2: Add Songs\n");
   sb.append("3: Exit \n");
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String input = br.readLine();
   System.out.println("You Selected: " + input);

   int in = -1;
    in = Integer.parseInt(input);
   }catch(Exception ex){
   System.out.println("Enter correct value [1,2,3]");
   return in;

private static void fun1(){
   System.out.println("Heloo 1");

private static void fun2(){
   System.out.println("Hello 2");

private static void exit(){



Simple Combination Generation Algorithm.

Some times we come across situation of generating all possible combinations of given set of values or objects. One classical example of combination without repetition is Lottery System where lotteries are listed for all possible number combination but the one lucky combination wins that.

Another example of combination is number lock where we set a number combination as a key.Whichever be the need below is a simple algorithm of creating combination.

Combination means all possible arrangements of given set of values or objects.


Suppose we have been given set of some words or numbers or say letters like {a,b,c,d}. Then think how do we practically crate a combination.. Answere is you would probably pick an item say a


then you may place another item in the available space ex:


then you would put c and d.


and then


This is how you have achieved one combination where we put first element ‘a’ at first position and arranged other three elements at vacant positions one by one. Like wise in next iteration we can place a at second positions and again place all element one by one in vacant positions.

We have mode this practical approach in algorithm where we pick first item and put in all possible positions and then pick second element and put in all possible positions.

We are using approach or recursion where we first position first element ‘a’ in all available possible position one by one in a loop and then we call subsequently same approach for other elements one by one. Simple here you go !

Here is a simple code written for this algorithm.

import java.util.Arrays;
public class PasswordGen {
static String[] options = {"a","b","c","d"};
static String[] places = new String[options.length];
static int count;

public static void main(String [] args){
  //Starting with initial position of a i.e. 0

private static void sequence(int level, String[] holder){
    //combination complete
    System.out.println(""+(++count) + " Combination " + Arrays.toString(holder));
    return ;

  String val = options[level];
  String[] inrHolder = null;
  for(int c=0; c<holder.length; c++){
    inrHolder = holder.clone();
      sequence(level+1, inrHolder.clone());
  return ;

Output of the above program tested for sample a,b,c,d :

1 Combination [a, b, c, d]
2 Combination [a, b, d, c]
3 Combination [a, c, b, d]
4 Combination [a, d, b, c]
5 Combination [a, c, d, b]
6 Combination [a, d, c, b]
7 Combination [b, a, c, d]
8 Combination [b, a, d, c]
9 Combination [c, a, b, d]
10 Combination [d, a, b, c]
11 Combination [c, a, d, b]
12 Combination [d, a, c, b]
13 Combination [b, c, a, d]
14 Combination [b, d, a, c]
15 Combination [c, b, a, d]
16 Combination [d, b, a, c]
17 Combination [c, d, a, b]
18 Combination [d, c, a, b]
19 Combination [b, c, d, a]
20 Combination [b, d, c, a]
21 Combination [c, b, d, a]
22 Combination [d, b, c, a]
23 Combination [c, d, b, a]
24 Combination [d, c, b, a]

Drill Down Pivot Table in Adobe Flex

This has been a very demanding feature among most of the business users to display drill down Pivot Table. In our previous blog we have gone through about how to create a Pivot Table. Drill down Pivot table enable you to click on any cell and it would display the full result set for that summary data.

Previous blog: How to create simple pivot table.
Experience Previous Example
Download the Code

Creating Drill Down Pivot Table:                                                                                                                                                                                                                                                       We can devide the work in four following logical sections. Each one has its own specific purpose.   

1: Adding event listener on Cell Click.

2: Fetching Selected Cell information on Cell Click.

3: Make another service call for this selected information.

4: Display the received drilled data in a grid\popup window or anyother option of your choice.


1: Adding event listener on cell click:

We know that in flex OLAPDataGrid is the UI component to display the Pivot table and OLAPCube is the model object which holds information of Pivot Dimentions.

<mx:OLAPDataGridFONT-SIZE: 10pt; COLOR: #990000; FONT-FAMILY: ‘Courier New'”>myOLAPDG”  defaultCellString=”” visible=”true” itemClick=”olapClick(event)” selectionMode=”multipleCells” allowMultipleSelection=”false” dataProvider=”{dataSet}”      />  

OLAPData grid is very much similar to the dataGrid component. Default grid allows you to select a row at a time, so you will have to specify that your selection usnit is Cell by setting property selectionMode=”multipleCell”.

We can add an event listener by setting it’s itemClick property by specifying a event listener function. You can also do this by using AddEventListener api at on page load. Other properties you see in code snippet are the normal we can specify with any normal pivot table always like dataprovider etc.                                   

2: Fecthing cell data on cell click.
We have written a function by name olapClick and calling the same on pivot click, now lets look into this fucntion. Main job of this fucntion is to findout the clicked cell and its correcponding Row and Column field name and it’s value.

function olapClick(event:ListEvent){
pvtSlectedColNo = event.columnIndex -1 ; // row count starts from 0 , but colum starts from 1
pvtSelectedRowNo = event.rowIndex;
pivotRowField = “EMPLOYEE”;
pivotRowFieldDim = “EMPLOYEEDim”;
pivotColField = “DATE”;
pivotColFieldDim = “DATEDim”;

var op:OLAPAxisPosition = myOLAPDG.selectedItem as OLAPAxisPosition;
var pivotData:OLAPResult= myOLAPDG.dataProvider as OLAPResult;
var cell:OLAPCell = pivotData.getCell(pvtSelectedRowNo,pvtSlectedColNo) as OLAPCell;
var axis:IOLAPResultAxis = pivotData.getAxis(1) as IOLAPResultAxis;
var dim:IOLAPDimension = myMXMLCube.findDimension(pivotColFieldDim) as IOLAPDimension;
var att:IOLAPAttribute = dim.findAttribute(pivotColField) as IOLAPAttribute;
var rowList:IList = att.children;
var temp:IOLAPMember = rowList[pvtSlectedColNo];
pivotColSelected = temp.displayName
var colList:Array = myOLAPDG.columns;
dim = myMXMLCube.findDimension(pivotRowFieldDim) as IOLAPDimension;
att = dim.findAttribute(pivotRowField) as IOLAPAttribute;
var rowList:IList = att.children;
var temp:IOLAPMember = rowList[pvtSelectedRowNo];
pivotRowSelected = temp.displayName


In this function we have tried to fetch the value of selectedRow , selectedColumn, and selected Cell data. Later this value would be used for expandable report or view. We can use this piece of information to make another AJAX call by httpService request and once we receive the resultset of the second call we can populate this drilled down information in any other grid or popup window.

yet to write on last two sections…

Experience Drill Down Pivot Table
Download the Code

Generate and Send an Excel file from J2EE WebApplication

Generating Excel file in J2EE Server.


This article is written to describe a simple way of generating an Excel file in Java. We will be using an open source Java Excel API  ( jxl http://jexcelapi.sourceforge.net/ ) to dynamically generate an excel file and reading and modifying an existing excel file.


Using this technology we can directly generate an Excel file on the fly on a user request.

In a typical web application a user can request for an excel sheet based report from a web based application.


With the proper integration of this API and the server side backend data layer, we can transform the fetched data into an excel sheet. Later this excel sheet can be sent to client side using proper http response header information.


To begin with the application we need to download the jxl.jar file and put it under the project folder.  To download go to the URL: http://sourceforge.net, and under File section you have a link to download the required jar files.



Code side view:

We may need following classes depending on our need:


import jxl.Workbook;

import jxl.format.Colour;

import jxl.format.UnderlineStyle;

import jxl.write.Label;

import jxl.write.Number;

import jxl.write.WritableCellFormat;

import jxl.write.WritableFont;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import jxl.write.WriteException;

import jxl.write.biff.RowsExceededException;



2) Create workflow object:

WritableWorkbook  wrtWorkbook = Workbook.createWorkbook(new


WritableSheet sheet1 ;


This function will create a writable workBook object. We can specify the location of the Excel file otherwise it will create in the current running folder. Later using defined API’s we can add worksheets on this workbook.

Note in case on reading excel sheet, we need to create WorkBook class

Object not WritableWorkBook.



3) Create worksheet :

sheet1 = this.wrtWorkbook.createSheet(“Sheet1”,0);

params: sheetname and location.

Here we have created a worksheet for the workbook, minimum one worksheet is required for a workbook to write some data in it. Like an Excel file one workbook can also contain more that one Sheet.


4) Adding cells :


Once the sheet object is created, we will use following API to write data in the specified cells. Here we are giving very simple demonstration but if require it also supports various kind of formatting.

To add number

Number number = new Number(colIndex, rowIndex, num);



To add string

Label label = new Label(colIndex, rowIndex, str);



5) Formatted Data

We can also specify specific format by using defined format classes:

WritableFont times10font = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BROWN);


WritableCellFormat times10format = new WritableCellFormat

Label label = new Label(colIndex, rowIndex, str, times10format );



6) Closing Worksheet

wrtWorkbook.write(); this function will write sheet into workBook




Sending an Excel file along with the HTTP Response.


In a typical J2EE web application an http Request is processed in doGet\doPost method and a response is generated and send back to the client. We need to set response header to provide specific information about the content it carrying, so that browser can automatically detect the compatible application to open that.

resp.setHeader(“Cache-Control”, “max-age=30”);



application/vnd.ms-excel defines that it is an excel spreadsheet application.

We can defile to send content in inline format or as an attachment.

resp.setHeader(“Content-disposition”,“inline; filename=MyExcel.xls);


here using java.io API’s we will write Excel file content in the response object.


ServletOutputStream sos = response.getOutputStream();

FileInputStream fio = new FileInputStream(“./” + “MyExcel.xls”);


while((c = fio.read()) != -1) {




And that’s all. Its all set and Please go and receive the Excel file in the client’s browser.