Reading Console Input

26 11 2008

The term console refers to a command line interface.All java program automatically import java.lang package.This package defines a class called System,which encapsulates every aspects of runtime environment.System class contains three pre defined stream variables. These fields are declared as ‘public static’ in the System

  • System.in
    refers standard InputStream
  • System.out
    refers standard OutputStream
  • System.err
    refers standard Error Stream

There is no obvious System.in.readLine() in the InputStream API. The closest thing available is the readLine method in the BufferedReader class. The System class in the java.lang package automatically creates an InputStream object that is connected to the keyboard. It is called System.in and is part of the java.lang package.We will use the System.in object to create an instance of the InputStreamReader class and then use that object to create an instance of the BufferedReader class.

Steps for console based user input:

  • Use the System.in object to create an InputStreamReader object.

  • Use the InputStreamReader object to create a BufferedReader object.

  • Display a prompt to the user for the desired data.

  • Use the BufferedReader object to read a line of text from the user.

Example

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

public class TestConsoleInput {

	public static void main(String[] args) throws IOException {
		int count =0;
		BufferedReader console = new BufferedReader( new InputStreamReader(System.in));

		System.out.println("What is your name?");

		//Reading Character input
		String name = console.readLine();

		//Reading Integer input
		System.out.println("How many eyes do you have?[ Please enter numeric values ] ");
		String no_eyes = console.readLine();
		try{
		count = Integer.parseInt(no_eyes); // convert string to integer
		}catch (Exception e) {
			System.out.println("[ "+no_eyes+ " ] is not numeric");
		}

		System.out.println("Name : "+name);
		if(count != 0){
			System.out.println("Number of eyes : "+count);
		}
	}
}

Output:
	What is your name?
	Joe
	How many eyes do you have?[ Please enter numeric values ]
	2
	Name : Joe
	Number of eyes : 2




6 12 2008

Rico Live Grid Application with Java Plug in

Here we are discussing the Rico Live and Super grid implementation with java plug in. Rico provides a very simple interface for registering Ajax request handlers as well as HTML elements or JavaScript objects as Ajax response objects .This Implementation only supports MySQL and Oracle database. Java Implementation only supports live grid scrolling, sorting, search row, hide/show features. Will be updating filters soon.

Here are the steps for Rico live grid with Java Web Application.

Downloads:

    • Download Jar files:

        1. dom4j-1.5.2.jar
           Download Link :  Dom4j
        2.mysql-connector-java-3.1.10-bin.jar
           Download Link : MySQLConnector
        3.ojdbc14.jar
           Download Link : Oracle Connector

     •	Download Rico live grid

        1.Rico Live grid
           Download Link : Rico Live Grid

           Unzip the file and copy all files and folders from  src  folder and  paste to WebContent/js/rico

     •	Download rico supergrid items:

        1.Rico Super Grid
           Download Link : Rico Super Grid

          Unzip the file and copy ,
          1.	ricoSuperGrid.js and paste to WebContent/js/rico
          2.	table.css and 1x1.gif and paste  to WebContent/ GridShow-Dateien
          3.	main.css and ie5-7.css and paste to WebContent/css
        Download Rico Live grid along with super grid and paste it in the appropriate folders.Please Refer previous one., ie, Download Rico live grid

Please refer the directory structure,

Directory Structure :
• Simple Structure

webcontent2
• Detailed Structure

webcontent-rico-files-open

1. Servlet Implementation :

You have to call this from the Rico Live Grid as “/ricoXMLquery”

package com.ricogrid.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ricogrid.Utils.DBConnection;
import com.ricogrid.Utils.MySQLQueryGenerator;
import com.ricogrid.Utils.OracleQueryGenerator;

public class RicoXMLQuery extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		DBConnection dbConnection = null;
		Connection connection = null;

		System.out.println("Processing rico sql request");

		try {
			int limit = 20;
			String responseString = "";

			String id = (request.getParameter("id") != null) ? request
					.getParameter("id") : "";

			limit = (request.getParameter("limit") != null) ? Integer
					.parseInt(request.getParameter("limit")) : limit;

			int offset = (request.getParameter("offset") != null) ? Integer
					.parseInt(request.getParameter("offset")) : 0;

			/*
			 * String size = (request.getParameter("page_size") != null) ?
			 * request.getParameter("page_size") : "";
			 *
			 * boolean total = (request.getParameter("get_total") != null) ?
			 * Boolean.getBoolean(request.getParameter("get_total").toString()):
			 * false;
			 *
			 * String distinct = (request.getParameter("distinct") != null) ?
			 * request.getParameter("distinct"): "";
			 */

			String sqlQuery = (String) request.getSession().getAttribute(id);

			dbConnection = new DBConnection(getServletContext().getRealPath("/WEB-INF/db.properties"));
			connection =  dbConnection.getConnection();
			String dialect  = dbConnection.getDialect();
			Map paramMap = request.getParameterMap();

			if( "MySQL".equals( dialect )){
				//if MySQL
				responseString = MySQLQueryGenerator.generateRicoResponseXML( connection, sqlQuery, paramMap,
                                                       offset, limit, dialect );
			}else{
				//if Oracle
				responseString = OracleQueryGenerator.generateRicoResponseXML( connection, sqlQuery, paramMap,
                                                       offset, limit, dialect );
			}
			response.setHeader("Content-Type", "text/xml");
			ServletOutputStream sos = response.getOutputStream();
			sos.write(responseString.getBytes());
			System.out.println("Processing rico sql request - Complete");

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			dbConnection.closeConnection(connection);
		}
	}

}

2: Database Connection class:

This Class is used for database Connectivity, getConnection Method gives you the Connection Object

package com.ricogrid.Utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnection {
	Connection connection;
	Properties propertyObj;
	String sql_driver;
	String sql_url_database;
	String sql_user;
	String sql_password;
	public String dialect;
	public DBConnection(String location) {
		try {
			propertyObj = new Properties();
			propertyObj.load(new FileInputStream(location));
			dialect = propertyObj.get("dialect").toString();
			this.setDialect( dialect );
			// MySQL Connection parameters
			if ("MySQL".equals(dialect.trim())) {
				sql_driver = propertyObj.get("sql.driver").toString();
				sql_url_database = propertyObj.get("sql.url.datasource").toString();
				sql_user = propertyObj.get("sql.user").toString();
				sql_password = propertyObj.get("sql.password").toString();
			}
			// Oracle Connection Parameters
			if ("Oracle".equals(dialect.trim())) {
				sql_driver = propertyObj.get("oracle.driver").toString();
				sql_url_database = propertyObj.get("oracle.url.datasource").toString();
				sql_user = propertyObj.get("oracle.user").toString();
				sql_password = propertyObj.get("oracle.password").toString();
			}

			Class.forName(sql_driver);
			connection = DriverManager.getConnection(sql_url_database,sql_user, sql_password);

			this.setConnection(connection);

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * returns connection Object
	 *
	 * @return Connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * set the connection object
	 *
	 * @param connection
	 *            the connection to set
	 */
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	/**
	 * Method is used to close the connection Object
	 *
	 * @param con
	 *            -- indicates connection Object
	 */
	public void closeConnection(Connection con) {

		try {
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @return the dialect
	 */
	public String getDialect() {
		return dialect;
	}

	/**
	 * @param dialect the dialect to set
	 */
	public void setDialect(String dialect) {
		this.dialect = dialect;
	}
}

3: DB Operation class

All the Database Operation like runQuery etc were implemented in this class

package com.ricogrid.Utils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;

public class DBOperations {
	/**
	 * Method is used to run the generated SQL queries
	 *
	 * @param sqlQuery
	 *            -- indicates the given SQL query
	 * @param connection
	 *            -- indicates DB Connection Object
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @param rowCount
	 *            -- indicates the total row count
	 * @param paramSize
	 *            -- indicates total number of field names
	 * @return RICO based XML string
	 */
	public static String runQuery(String sqlQuery, Connection connection,
			int limit, int offset, int rowCount, int paramSize ) {

		String ricoGridValue = "";
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {

			ps = connection.prepareStatement(sqlQuery);
			//ps.setMaxRows( limit );
			rs = ps.executeQuery();

			if (rs != null) {
				ricoGridValue = ResponseBuilder.createAjaxResponseForRicoGrid(
						rs, offset, rowCount, paramSize );
			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (ps != null)
					ps.close();
				if (rs != null)
					rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return ricoGridValue;
	}

	/**
	 * Method is used to get the total row count
	 *
	 * @param connection
	 *            -- indicates the DB Connection Object
	 * @param sqlString
	 *            -- indicatse the given SQl queries
	 * @return total row count
	 */
	public static int getTotalRowCount(Connection connection, String sqlString ) {

		int rowCount = -1;
		String elementString = "";
		PreparedStatement ps = null;
		ResultSet rs = null;

		sqlString = sqlString.toUpperCase().trim();

		if (sqlString.contains("SELECT "))
			elementString = sqlString.substring(7, sqlString.indexOf(" FROM"))
					.trim();

		sqlString = sqlString.replaceFirst(elementString, " count(*) ");

		try {

			ps = connection.prepareStatement(sqlString);
			rs = ps.executeQuery();

			if (rs != null) {

				if (rs.next())
					rowCount = rs.getInt(1);
			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (ps != null)
					ps.close();
				if (rs != null)
					rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return rowCount;
	}

}

4: MySQLQueryGenerator

This class is used to generate MySQL based SQL query

package com.ricogrid.Utils;

import java.util.List;
import java.util.Map;
import java.util.Set;

import java.sql.Connection;
public class MySQLQueryGenerator {

	/**
	 * Method to generate the ResponseXML from the given parameters
	 * @param connection -- indicates the Connection Object
	 * @param sqlQuery -- indicates the given SQLQuery
	 * @param paramMap -- contains the request.params object
	 * @param limit -- to limit query results in some specified range
	 * @param offset -- indicates the starting value of limit results
	 * @return a string of generated ResponseXML
	 */
	public static String generateRicoResponseXML(Connection connection, String sqlQuery,
			Map paramMap, int offset, int limit, String dialect) {

		int position = -1;
		int paramElemSize = -1;
		int rowCount = -1;
		String value = "";
		String responseString = "";

		if (connection != null && paramMap != null && !"".equals( sqlQuery )) {

			try {

				// parse the given SQL query and to get the field name list from SQLParser.java class
				SQLParser parser = new SQLParser();
				parser.parseSqlQuery(sqlQuery);
				List selectItemList = parser.selectItemList;

				// get the size of field name list
				if (selectItemList != null && selectItemList.size() > 0)
					paramElemSize = selectItemList.size();

				if (paramMap != null) {

					// iterate parameter Map
					Set set = paramMap.keySet();
					for (String key : set) {

						String prefix = key.substring(0, 1);

						// from here we got the sorting order(ASC/DESC) and the clicked column ID
						if ("s".equals(prefix)) {

							String[] valueArray = (String[]) paramMap.get(key);
							value = valueArray[0].toString();
							position = Integer.parseInt(key.substring(1));

						}
					}
				}

				if (!"".equals(value) && position != -1) {
					// if sorting
					sqlQuery = createSortingSQLQuery(sqlQuery, limit, offset,
							value, position, selectItemList);
				} else {
					// if scrolling
					sqlQuery = createNormalSQLQuery(sqlQuery, limit, offset);
				}

				if (connection != null && !"".equals(sqlQuery)) {

					// get the total row count
					rowCount = DBOperations.getTotalRowCount( connection, sqlQuery );

					if ( rowCount != -1 && paramElemSize != -1 ){
					// run SQL Query and to generate XML String
						responseString = DBOperations.runQuery(sqlQuery,
								connection, limit, offset, rowCount,
								paramElemSize);
					}else{
						responseString = "Your connection with the server was idle for too long and timed out. Please refresh this page and try again";
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return responseString;
	}

	/**
	 * Method is used to create the sorting SQL query
	 *
	 * @param sqlQuery
	 *            -- indicates the given sql query
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @param sortOrder
	 *            -- indicates sort order (ASC/DESC)
	 * @param key
	 *            -- indicates the column position to identify the field name
	 * @param elementArray
	 *            -- indicates the list of field names
	 * @return sort query with the given parameters
	 */
	private static String createSortingSQLQuery(String sqlQuery, int limit,
			int offset, String sortOrder, int key, List elementArray) {

		sqlQuery = sqlQuery.toUpperCase().trim();
		String orderByValue = (String) elementArray.get(key);

		if (sqlQuery.contains("ORDER BY "))
			sqlQuery = sqlQuery.substring(0, sqlQuery.indexOf(" ORDER BY"))
					.trim();

		sqlQuery = sqlQuery + " ORDER BY " + orderByValue + " " + sortOrder
				+ " LIMIT " + limit + " OFFSET " + offset;

		return sqlQuery;

	}

	/**
	 * Method to generate normal SQL query with out sorting parameters. ie, SQL
	 * query for scrolling
	 *
	 * @param sqlQuery
	 *            -- indicates given SQL query
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @return normal SQL query for scrolling
	 */
	private static String createNormalSQLQuery(String sqlQuery, int limit,
			int offset) {

		String query = "";
		if (!"".equals(sqlQuery))
			sqlQuery = sqlQuery.toUpperCase().trim();
			query = sqlQuery + " LIMIT " + limit + " OFFSET " + offset;

		return query;
	}
}

5: OracleQueryGenerator

This class is used to generate MySQL based SQL query

package com.ricogrid.Utils;

import java.util.List;
import java.util.Map;
import java.util.Set;

import java.sql.Connection;
public class OracleQueryGenerator {

	/**
	 * Method to generate the ResponseXML from the given parameters
	 *
	 * @param connection
	 *            -- indicates the Connection Object
	 * @param sqlQuery
	 *            -- indicates the given SQLQuery
	 * @param paramMap
	 *            -- contains the request.params object
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @return a string of generated ResponseXML
	 */
	public static String generateRicoResponseXML(Connection connection,
			String sqlQuery, Map paramMap, int offset, int limit, String dialect) {

		int paramElemSize = -1;
		String value = "";
		int position = -1;
		int rowCount = -1;
		String responseString = "";

		if (connection != null && paramMap != null && !"".equals(sqlQuery)) {

			try {

				// parse the given SQL query and to get the field name list from
				// SQLParser.java class
				SQLParser parser = new SQLParser();
				parser.parseSqlQuery(sqlQuery);
				List selectItemList = parser.selectItemList;

				// get the size of field name list
				if (selectItemList != null && selectItemList.size() > 0)
					paramElemSize = selectItemList.size();

				if (paramMap != null) {

					// iterate parameter Map
					Set set = paramMap.keySet();
					for (String key : set) {

						String prefix = key.substring(0, 1);

						// from here we got the sorting order(ASC/DESC) and the
						// clicked column ID
						if ("s".equals(prefix)) {

							String[] valueArray = (String[]) paramMap.get(key);
							value = valueArray[0].toString();
							position = Integer.parseInt(key.substring(1));

						}
					}
				}

				// get the total row count
				if (connection != null && !"".equals(sqlQuery))
					rowCount = DBOperations.getTotalRowCount(connection,sqlQuery );

				if (!"".equals(value) && position != -1) {
					// if sorting
					String orderByValue = ( selectItemList.get(position)) != null ? (String) selectItemList.get(position):"";
					sqlQuery = createSQLSortingQuery(sqlQuery, orderByValue,value, offset, limit );
				}else{
					sqlQuery = createNormalSQLQuery( sqlQuery, offset, limit);
				}

				// run SQL Query and to generate XML String
				if (rowCount != -1 && paramElemSize != -1 && connection != null && !"".equals(sqlQuery)) {

					responseString = DBOperations.runQuery(sqlQuery,
								connection, limit, offset, rowCount,
								paramElemSize);
				} else
					responseString = "Your connection with the server was idle for too long and timed out. Please refresh this page and try again";

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return responseString;
	}

	/**
	 * Method is used to return the sorting SQL query
	 *
	 * @param sqlQuery
	 *            -- indicates the given SQL query
	 * @param orderByValue
	 *            -- indicates the field name for sorting
	 * @param value
	 *            -- sorting order(ASC/DESC)
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @return the formatted SQl query as String
	 */
	private static String createSQLSortingQuery(String sqlQuery,
			String orderByValue, String value, int offset, int limit ) throws Exception{

		sqlQuery = sqlQuery.toUpperCase().trim();

		String orderBy = " ORDER BY " + orderByValue + " " + value;

		if (sqlQuery.contains("ORDER BY "))
			sqlQuery = sqlQuery.substring(0, sqlQuery.indexOf(" ORDER BY"))
					.trim();

		sqlQuery += orderBy;

		sqlQuery = generateLimitQuery(sqlQuery, offset, limit);

		return sqlQuery;

	}

	/**
	 * Method to generate normal SQL query with out sorting parameters. ie, SQL
	 * query for scrolling
	 *
	 * @param sqlQuery
	 *            -- indicates given SQL query
	 * @param limit
	 *            -- to limit query results in some specified range
	 * @param offset
	 *            -- indicates the starting value of limit results
	 * @return normal SQL query for scrolling
	 * @throws Exception
	 */
	private static String createNormalSQLQuery(String sqlQuery, int offset, int limit ) throws Exception {

		sqlQuery = sqlQuery.toUpperCase().trim();
		sqlQuery = generateLimitQuery(sqlQuery, offset, limit);

		return sqlQuery;
	}

	/**
	 *  Method is used to create the sorting SQL query
	 * @param sqlQuery -- indicates the given SQL query
	 * @param offset -- indicates the starting value of limit results
	 * @param limit -- to limit query results in some specified range
	 * @return the generated SQL limit Query as String
	 */
	private static String generateLimitQuery(String sqlQuery, int offset, int limit) throws Exception{

		sqlQuery = sqlQuery.toUpperCase().trim();
		boolean isForUpdate = false;
		StringBuffer limitQuery = new StringBuffer(sqlQuery.length() + 150);

		if (sqlQuery.toLowerCase().endsWith(" FOR UPDATE")) {

			sqlQuery = sqlQuery.substring(0, sqlQuery.length() - 11);
			isForUpdate = true;
		}

		limitQuery.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( ");
		limitQuery.append(sqlQuery);
		limitQuery.append(" ) ROW_ WHERE ROWNUM <= " + (offset + limit)	+ ") WHERE ROWNUM_ > " + offset);

		if (isForUpdate) {
			limitQuery.append(" FOR UPDATE");
		}

		return limitQuery.toString();
	}

}

5: ResponseBuilder

This class is used to generate the xml using dom4j

package com.ricogrid.Utils;

import java.io.IOException;
import java.io.StringWriter;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class ResponseBuilder {

	// XML format
	public static OutputFormat XML_OUTPUT_FORMAT = OutputFormat.createPrettyPrint();

	/**
	 * Method to create the RICO based XML from the resultset Object
	 * @param resultSet -- indicates the ResultSet Object
	 * @param offset -- indicates the starting value of limit results
	 * @param rowCount -- indicates the total row count
	 * @param paramSize -- indicates total number of field names
	 * @return  RICO based XML string
	 * @throws SQLException
	 */
	public static String createAjaxResponseForRicoGrid(ResultSet resultSet, int offset, int rowCount, int paramSize) throws SQLException {

		Document document = DocumentHelper.createDocument();
		Element ajaxResponse = document.addElement("ajax-response");
		Element response = ajaxResponse.addElement("response");
		response.addAttribute("type", "object");
		response.addAttribute("id", "data_grid_updater");

		Element rows = response.addElement("rows");
		rows.addAttribute("update_ui", "true");
		rows.addAttribute("offset", (offset+1)+"");

		while( resultSet.next() ){

			Element tr_user = rows.addElement("tr");

			for( int i = 1; i<= paramSize; i++){
				tr_user.addElement("td").addText( resultSet.getString(i));
			}

		}
		response.addElement("rowcount").addText( rowCount+"");
		StringWriter stringWriter = new StringWriter();
		XMLWriter writer = new XMLWriter(stringWriter, XML_OUTPUT_FORMAT);
		try {
			writer.write(document);
			writer.close();
			stringWriter.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		return stringWriter.toString();
	}

}

6: SQLParser

This class is used to parse the given sql query to various components

package com.ricogrid.Utils;

import java.util.ArrayList;
import java.util.List;

public class SQLParser {

	public  List selectItemList;
	public  String tableName ;
	public String whereClause;
	public String fromClause;

	public SQLParser() {

		tableName = "";
		whereClause = "";
		fromClause = "";
		selectItemList = new ArrayList();
	}
	/**
	 * Parse a SQL select statement into its major components
  	 * Does not handle:
  	 * 	1) select * from tablename ( use field names instead of * )
  	 * @param sqlQuery
	 * @throws Exception
	 */

	public void parseSqlQuery(String sqlQuery) throws Exception{

		String elementString = "";

		if (!"".equals(sqlQuery)) {
			sqlQuery = sqlQuery.toUpperCase().trim();

			if (sqlQuery.contains("SELECT ")) {
				elementString = sqlQuery
						.substring(7, sqlQuery.indexOf(" FROM")).trim();

				if (!"*".equals(elementString)) {

					String[] elementArray = elementString.split(",");
					for (String element : elementArray){

						if( element.contains( "AS" ))
							element = element.substring(0, element.indexOf("AS")).trim();

						selectItemList.add(element);
					}

				}else{

				}
			}

			if (sqlQuery.contains("FROM ")) {

				if (sqlQuery.contains(" WHERE"))
					tableName = sqlQuery.substring(
							sqlQuery.indexOf(" FROM") + 5,
							sqlQuery.indexOf(" WHERE")).trim();
				else
					tableName = sqlQuery.substring(
							sqlQuery.indexOf(" FROM") + 5).trim();

				fromClause = sqlQuery.substring(sqlQuery.indexOf(" FROM") + 5, sqlQuery.length());
			}

			if( sqlQuery.contains("WHERE")){
				whereClause = sqlQuery.substring( sqlQuery.indexOf( "WHERE ") +5 );
			}

		}
	}

}

7: db.properties file

## General parameters
## MySQL/Oracle
dialect 			=Oracle  

## MySQL Connection parameters

#sql.driver 			=com.mysql.jdbc.Driver
#sql.url.datasource      =jdbc:mysql://192.168.0.34:3306/ricogrid
#sql.user			=root
#sql.password		=root

## Oracle Connection parameters

oracle.driver		=oracle.jdbc.driver.OracleDriver
oracle.url.datasource	=jdbc:oracle:thin:@192.168.0.34:1521:XE
oracle.user			=system
oracle.password		=root

8: index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
</head>
<body leftMargin="0" topMargin="0" marginheight="0" marginwidth="0">
   <table cellspacing="0" cellpadding="0" border="0" width="1374">
       <tr>
  	   <td align="center" colspan="3"><iframe name="iframe_MyIFrame" id="iframe_MyIFrame" height="520" width="1375"
                 frameborder="0" src="livegrid.jsp" scrolling="no"></iframe></td>
      </tr>
 </table>
</body>
</html>

9: livegrid.jsp[ for super grid ]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--[if lte IE 7]>
  <link rel="stylesheet" type="text/css" href="css/ie5-7.css">
<![endif]-->
<link href="GridShow-Dateien/table.css" type="text/css" rel="stylesheet">
<style>
	#grid_head{
		font-size: 19px;
	}
</style>
</head>
<body leftmargin="0" topmargin="0"
	style="background-color: rgb(236, 240, 246);" marginheight="0"
	marginwidth="0">

<script src="js/rico/prototype.js" type="text/javascript"></script>
<script src="js/rico/rico.js" type="text/javascript"></script>
<%
String sqlQuery = "select ID,USER_NAME,CITY from user_details order by user_name";
request.getSession().setAttribute("tblGrid" , sqlQuery);
%>
<script type='text/javascript'>
	Rico.loadModule('LiveGrid', 'LiveGridAjax', 'customgrid.css');
</script>

<script src="js/rico/ricoSuperGrid.js" type="text/javascript"></script>

<script>
	var opts = {
		frozenColumns :0,
		defaultWidth :90,
		useUnformattedColWidth :false,
		allowColResize :true, // allow user to resize columns
		windowResize :true, // Resize grid on window.resize event? Set to false when embedded in an accordian.
		useUnformattedColWidth :true,
		scrollBarWidth :19, // this is the value used in positioning calculations, it does not actually change the width of the scrollbar
		hdrIconsFirst :false,
		sortCol :0,
		sortDir :'ASC',
		headingSort :'hover',
		highlightElem :'cursorRow',
		highlightClass :'dataRollOver',
		persistRowClick :true,
		persistantRowClass :'persistantRow',
		minScrollWidth :100, // min scroll area width when width of frozen columns exceeds window width
		canFilterDefault :false,
		canPrint :false,
		columnSpecs : [ {
			type :'number',
			canSort :true
		} ]
	};

	var buffer = null;
	var tblGrid = null;

	Event.observe(window, 'load', function() {

		buffer = new Rico.Buffer.AjaxSQL('/ricoXMLquery?limit=30');
		tblGrid = new Rico.SuperGrid('tblGrid', buffer, opts);
		//tblGrid = new Rico.LiveGrid ('tblGrid', buffer, grid_options);
			tblGrid.options.rowClickHandler = clickMe
					.bindAsEventListener(tblGrid);
			tblGrid.initClickEvents();
		});

function clickMe(e) {
		var cell = Event.element(e);
		cell = RicoUtil.getParentByTagName(cell, 'div', 'ricoLG_cell');
		var newIdx = this.winCellIndex(cell);
		var rowVals = new Array();
		for ( var c = 0; c < this.columns.length; c++) {
			var value = this.columns[c].cell(newIdx.row).textContent;
			rowVals.push(value);
		}

		var rowID = tblGrid.buffer.windowStart + newIdx.row + 1;

		alert("Row Values  :  " + rowVals);
		alert("Selected Row ID : "+ rowID );
	}

	function selectRow(rowId) {
		if (tblGrid != null)
			tblGrid.scrollToSelectRow(rowId - 1);
	}
</script>

<style>
.dataRollOver {
	background-color: #AABBCC;
}

.persistantRow {
	background-color: orange;
	color: #fff;
}

#rowId{
	border-color: black;
	border-style: solid;
	width: 80px;
}

#serach_img{
	margin-left: 10px;
}

</style>
<div style="background: steelblue; padding: 10px;">
<table width="100%">
	<tr>
		<td width="50%">
		<div align="left"><span id ="grid_head">Rico Live Grid Demo</span>
		<p class="ricoBookmark"><span id="tblGrid_bookmark" class="grid_bookmark">&nbsp;</span></p>
		</div>
		</td>
		<td width="50%">
			<div align="right">
				<input type="text" id="rowId" />
				<img src="images/search_16x16.gif"  id="serach_img" onclick="selectRow($('rowId').value)" alt="Search Row by ID" title="Search Row by ID" />
			</div>
		</td>
	</tr>
</table>

</div>

<div class="dataGridHeader">
<div class="dataGridContent">
<table class="tableGrid scrolltablestyle" id="tblGrid" name="tblGrid"
	border="0" cellpadding="0" cellspacing="0" width="100%">

	<thead>
		<tr>
			<th>User ID</th>
			<th>User Name</th>
			<th>City</th>

		</tr>
	</thead>
	<tbody>
	</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

10: livegrid.jsp [ for Simple live grid]

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Rico LiveGrid Plus-Example Demo</title>

<script src="js/rico/prototype.js" type="text/javascript"></script>
<script src="js/rico/rico.js" type="text/javascript"></script>
<%
String sqlQuery = "select ID,USER_NAME,CITY from user_details order by user_name";
request.getSession().setAttribute("ex3" , sqlQuery);
%>
<script type='text/javascript'>
Rico.loadModule('Effect','LiveGridAjax','LiveGridMenu','greenHdg.css');

var ex3,buffer;

Rico.onLoad( function() {
  // filterUI='t' --> text box
  // filterUI='s' --> select list
  var grid_options = {
    frozenColumns:  1,
    canFilterDefault: false,
    canPrint: true,
    columnSpecs: [{type:'number', canSort:true }]
  };
  buffer=new Rico.Buffer.AjaxSQL('/ricoXMLquery?limit=30');
  ex3=new Rico.LiveGrid ('ex3', buffer, grid_options);

});

</script>

</head>

<body>

<p class="ricoBookmark">
<span id="ex3_bookmark">&nbsp;</span></p>
<table id="ex3" class="ricoLiveGrid" cellspacing="0" cellpadding="0">
  <tr>
	  <th>User ID</th>
	  <th>User Name</th>
	  <th>City</th>
  </tr>
</table>

</body>
</html>

11: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	RicoLiveGridAutoFetch</display-name>
	<servlet>
		<description>
		</description>
		<display-name>RicoXMLQuery</display-name>
		<servlet-name>RicoXMLQuery</servlet-name>
		<servlet-class>com.ricogrid.servlets.RicoXMLQuery</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>RicoXMLQuery</servlet-name>
		<url-pattern>/ricoXMLquery</url-pattern>
	</servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>




Basic String Functions

26 11 2008

The Basic String Functions are shown below,

  • concat(String)
  • replace(char, char)
  • length()
  • toLowerCase()
  • toUpperCase()
  • trim()

concat(String)

This Function is used to concatenate one string onto another.

	String str1 = new String("Hi ");
	String str2 = new String("GoodMorning");
	String str3 = str1.concat(str2);
	System.out.println(str3);

Output:

Hi GoodMorning

replace(char, char)

This Function is used to replace all occurrences of one character with a different character.

		String str = new String("Hi GoodMorning ");
		String newStr = str.replace("Morning", "Afternoon");
		System.out.println(newStr);

Output:

Hi GoodAfternoon

length()

This Function returns the length of the string.

		String str = new String("Hi GoodMorning ");
		int strLen = str.length();
		System.out.println(strLen)

Output:

15

toLowerCase()

This Function converts the entire string to lowercase.

		String str = new String("Hi GoodMorning ");
		String lowerStr = str.toLowerCase();
		System.out.println(lowerStr);

Output:

hi goodmorning

toUpperCase()

This Function converts the entire string to uppercase.

		String str = new String("Hi GoodMorning ");
		String upperStr = str.toUpperCase();
		System.out.println(upperStr);

Output:

HI GOODMORNING

trim()

This Function removes both leading and trailing whitespace from the string.

		String str = new String("        Hi GoodMorning        ");
		String trimStr = str.trim();
		System.out.println(trimStr);

Output:

Hi GoodMorning




Strings

26 11 2008

Java’s String class allow programmers to search strings,extract parts of them, compare them, etc. There are seven String constructors in java,

  • String str1 = new String();
  • String str2 = new String(“Sample String”);
  • char charArray[] = {‘S’, ‘t’, ‘r’, ‘i’, ‘n’ ,’g'};
  • String str3 = new String(charArray);
  • String str4 = new String(charArray, 2, 3);
  • StringBuffer buf = new StringBuffer(“buffer”);
  • String str5 = new String(buf);

In the first example, str1 is created as an empty string.The second string, str2, will hold the text “A New String”. The next two examples, str3 and str4, are constructed from a character array. In the case of str3, the entire array is placed in the string. For str4, three characters starting in array position two are copied into
the string. Because Java arrays are zero-based, this results in str4 containing “ray”. In the final example, the string str5 is constructed from a StringBuffer.





String Buffer Operations

26 11 2008

StringBuffer is a peer class of String that provides much of the functionality of the strings. String represents fixed-length, immutable character sequences.In contrast StringBuffer represents growable and writable character sequences. String buffers are preferred when heavy modification of character strings is involved (appending,inserting, deleting, modifying etc).Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations.The StringBuffer
provides 3 constructors which create, initialize and set the initial capacity of StringBuffer objects.

StringBuffer Constructors

public class TestStringBuffer {

  public static void main(String[] args) {

	StringBuffer stringBuffer = new StringBuffer("Test StringBuffer");
	StringBuffer stringBufferWithFixedSize = new StringBuffer(500);
	StringBuffer stringBufferWithDefaultSize = new StringBuffer(); //Default Constructor
	System.out.println("StringBuffer : " + stringBuffer);
	System.out.println("StringBuffer with Fixed Size capacity : " + stringBufferWithFixedSize.capacity());
	System.out.println("StringBuffer with Default Size capacity : " + stringBufferWithDefaultSize.capacity());
  }
}
	StringBuffer : Test StringBuffer
	StringBuffer with Fixed Size capacity : 500
	StringBuffer with Default Size capacity : 16

String Buffer Functions

  • capacity() -:

    Returns the current capacity
    of the String buffer.

  • length() :-

    Returns the length (character count)
    of this string buffer.

  • charAt(int index) :-

    The specified character of the sequence currently
    represented by the string buffer, as indicated by the index argument, is returned.

  • setCharAt(int index, char ch) :-

    The character at the
    specified index of this string buffer is set to ch

  • toString() :-

    Converts to a string representing the data
    in this string buffer

  • insert(int offset, char c) :-

    Inserts the string representation
    of the char argument into this string buffer.

  • delete(int start, int end) :-

    Removes the characters in a substring
    of this StringBuffer

  • replace(int start, int end, String str) :-

    Replaces the
    characters in a substring of this StringBuffer with characters in the specified String.

  • reverse() :-

    The character sequence contained in this string buffer
    is replaced by the reverse of the sequence.

  • append(String str) :-

    Appends the string to this string buffer.

public class TestStringBuffer {

  public static void main(String[] args) {

	StringBuffer stringBuffer = new StringBuffer("Test String Buffer");
	StringBuffer stringBufferWithFixedSize = new StringBuffer(100);
	StringBuffer stringBufferWithDefaultSize = new StringBuffer();

	//StringBuffer function capacity()
	System.out.println("StringBuffer : " + stringBuffer);
	System.out.println("StringBuffer capacity : " + stringBuffer.capacity());
	System.out.println("StringBuffer with Fixed Size capacity : " + stringBufferWithFixedSize.capacity());
	System.out.println("StringBuffer with Default Size capacity : " + stringBufferWithDefaultSize.capacity());

	//StringBuffer function length()
	System.out.println("stringBuffer length : " + stringBuffer.length());

	//StringBuffer function charAt()
	System.out.println("stringBuffer charAt 2 : " + stringBuffer.charAt(2));

	//StringBuffer function setCharAt()
	stringBuffer.setCharAt(1, 'E');
	System.out.println("stringBuffer after setCharAt 1 to E is : "+ stringBuffer);

	//StringBuffer function toString()
	System.out.println("StringBstringBufferuffer toString() is : " + stringBuffer.toString());

	//StringBuffer function append()
	stringBufferWithDefaultSize.append("Test Buffer");
	System.out.println("stringBufferWithDefaultSize when appended with a String : "+ stringBufferWithDefaultSize.toString());

	//StringBuffer function insert()
	stringBufferWithDefaultSize.insert(1, 'C');
	System.out.println("stringBufferWithDefaultSize when C is inserted at 1 : "	+ stringBufferWithDefaultSize.toString());

	//StringBuffer function delete()
	stringBufferWithDefaultSize.delete(1, 'C');
	System.out.println("stringBufferWithDefaultSize when C is deleted at 1 : "+ stringBufferWithDefaultSize.toString());

	//StringBuffer function reverse()
	stringBufferWithDefaultSize.reverse();
	System.out.println("Reversed stringBufferWithDefaultSize : " + stringBufferWithDefaultSize);

	//StringBuffer function setLength()
	stringBufferWithFixedSize.setLength(5);

	stringBufferWithFixedSize.append("Sample Buffer");
	System.out.println("stringBufferWithFixedSize : " + stringBufferWithFixedSize);

	}
  }

Output:

	StringBuffer : Test String Buffer
	StringBuffer capacity : 34
	StringBuffer with Fixed Size capacity : 100
	StringBuffer with Default Size capacity : 16
	stringBuffer length : 18
	stringBuffer charAt 2 : s
	stringBuffer after setCharAt 1 to E is : TEst String Buffer
	StringBstringBufferuffer toString() is : TEst String Buffer
	stringBufferWithDefaultSize when appended with a String : Test Buffer
	stringBufferWithDefaultSize when C is inserted at 1 : TCest Buffer
	stringBufferWithDefaultSize when C is deleted at 1 : T
	Reversed stringBufferWithDefaultSize : T
	stringBufferWithFixedSize : Sample Buffer




Copy Characters using BufferedStream

26 11 2008

Buffered input streams read data from a memory area known as a buffer;the native input API is called only when the buffer is empty. Similarly,buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
Example

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class CopyFiles {

  public static void main(String[] args){
	  String sourceFileName = "D:\\Test Folder\\Test File.txt";
	  String destinationFileName = "D:\\Test Folder\\Test File 1.txt";
	  copyFile(sourceFileName, destinationFileName);
  }	

 private static void copyFile(String sourceFileName,String destinationFileName) { 

      BufferedReader br = null;
      BufferedWriter bw = null; 

      try {
      	br = new BufferedReader(new FileReader( sourceFileName ));
      	bw = new BufferedWriter(new FileWriter( destinationFileName ));
        int c;
        while ((c = br.read()) != -1)  {
           bw.write(c);
        }
        br.close();
        bw.close();
      }catch (Exception e) {
	  e.printStackTrace();
      }
}




Copy Files[ line by line ]

26 11 2008

Invoking readLine returns a line of text with the line CopyLines outputs each line using println, which appends the line terminator for the current operating system.This might not be the same line terminator that was used in the input file.
Example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class CopyFiles {

  public static void main(String[] args){
	  String sourceFileName = "D:\\Test Folder\\Test File.txt";
	  String destinationFileName = "D:\\Test Folder\\Test File 1.txt";
	  copyFile(sourceFileName, destinationFileName);
  }	

 private static void copyFile(String sourceFileName,String destinationFileName) { 

      BufferedReader br = null;
      PrintWriter pw = null; 

      try {
          br = new BufferedReader(new FileReader( sourceFileName ));
    	  pw =  new PrintWriter(new FileWriter( destinationFileName ));

          String line;
          while ((line = br.readLine()) != null) {
              pw.println(line);
          }

          br.close();
          pw.close();
      }catch (Exception e) {
	  e.printStackTrace();
      }
}




Copy Files[ characters ]

26 11 2008

CopyCharacters is very similar to CopyBytes. The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int
variable holds a byte value in its last 8 bits.
Example

import java.io.FileReader;
import java.io.FileWriter;

public class CopyFiles {

  public static void main(String[] args){
	  String sourceFileName = "D:\\Test Folder\\Test File.txt";
	  String destinationFileName = "D:\\Test Folder\\Test File 1.txt";
	  copyFile(sourceFileName, destinationFileName);
  }	

 private static void copyFile(String sourceFileName,String destinationFileName) { 

      FileReader reader = null;
      FileWriter writer = null;
      try{
          reader = new FileReader( sourceFileName );
          writer = new FileWriter( destinationFileName );

          int c;
          while ((c = reader.read()) != -1)  {
              writer.write(c);
          }
          reader.close();
          writer.close();
      }catch (Exception e) {
	  e.printStackTrace();
      }
}




Create Temporary Files

26 11 2008

Create a temporary file whose name is guaranteed to be unique.
You specify a prefix, suffix and directory to use. Always name your temporary files with a prefix
temp and a suffix .tmp,so that they can easily be scavenged and deleted after a crash by
generic junk cleaning utilities. The file will not be automatically deleted on exit, unless you use
deleteOnExit.
Example:

import java.io.File;

public class CreateTempFile {

  public static void main(String[] args){
	try {
		File temp = File .createTempFile( "temp", ".tmp", new File( "D:\\" ) );
		temp.deleteOnExit();
	} catch (Exception e) {
		e.printStackTrace();
	}
  }
}




Copy Files [byte by byte ]

26 11 2008

CopyBytes spends most of its time in a simple loop that reads the input stream and writes the output stream one byte at a time.The following example illustrates, how to copy a file in to another File.
Example

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyFiles {

  public static void main(String[] args){
	  String sourceFileName = "D:\\Test Folder\\Test File.txt";
	  String destinationFileName = "D:\\Test Folder\\Test File 1.txt";
	  copyFile(sourceFileName, destinationFileName);
  }	

 private static void copyFile(String sourceFileName,String destinationFileName) { 

	 int i;
	 FileInputStream fin;
	 FileOutputStream fout;

	 try {
		 fin = new FileInputStream(new File( sourceFileName ));
		 fout = new FileOutputStream(new File( destinationFileName ));
		 do {
			 i = fin.read();
			 if(i != -1)
				 fout.write(i);
		 } while(i != -1);

		 fin.close();
		 fout.close();

	 } catch(Exception e) {
		 e.printStackTrace();
	 }
   }
}




Writing Files

26 11 2008

The following example illustrates, how to write contents in to a File.
Example

import java.io.FileOutputStream;
import java.io.PrintStream;

public class TestConsoleInput {

  public static void main(String[] args){
	  String destinationFileName = "D:\\Test Folder\\Test File 1.txt";
	  writeFile(destinationFileName);
  }	

 private static void writeFile(String destinationFileName) { 

     FileOutputStream out;
     PrintStream pw = null;
     try
     {
       out = new FileOutputStream( destinationFileName );
       pw = new PrintStream( out );
       pw.println ("Hi Friends GoodMorning!!");
       pw.close();
     }
     catch (Exception e)
     {
       e.printStackTrace();
     }
}
}







Follow

Get every new post delivered to your Inbox.