Think Differently

Vidya

# java.sql.SQLException: ORA-00911: invalid character

Posted by vidya on January 11, 2010

If you are getting this exception while running a JDBC query from a Java program check if your query is having semicolon (“;”) at the end of it or anywhere in the query. You should not have semicolon in a JDBC query.

Posted in JDBC | Tagged: | Leave a Comment »

Checking focus in Javascript

Posted by vidya on November 9, 2009

<script>
// Sets the form focus to the first element found in forms[0] that
// is a textfield or text area
function setFocus() {
// Bail if no form on page
if (document.forms[0] == null) return;

// Iterate though elements
for (var i = 0; i < document.forms[0].elements.length; i++) {
  e = document.forms[0].elements[i];
  if ((e.type == "text") || (e.type == "textarea")) {
    e.focus();
    break;
  }
}
}

</script>  

<body onload="setFocus()">

Posted in JavaScript | Leave a Comment »

Error while converting Excel data to XML Using POI

Posted by vidya on July 16, 2009

Error:

Exception in thread “main” java.lang.IllegalStateException: Cannot get a text value from a numeric cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:620)
at org.apache.poi.hssf.usermodel.HSSFCell.getRichStringCellValue(HSSFCell.java:699)
at org.apache.poi.hssf.usermodel.HSSFCell.getStringCellValue(HSSFCell.java:682)
at com.apress.excel.ExcelToXML_test.generateXML(ExcelToXML_test.java:86)
at com.apress.excel.ExcelToXML_test.main(ExcelToXML_test.java:323)

Solution:

Its a type mismatch Numerical problem in POI, Because in the excel sheet u somewhere used numerical values, but you will be try to fetch as a String value.  for example

revenueElement1.appendChild(document.createTextNode(row1.getCell((short) 1).getStringCellValue()));

change to

revenueElement1.appendChild(document.createTextNode(((Double)row1.getCell((short) 1).getNumericCellValue()).toString()));

Posted in Java | Tagged: , , | Leave a Comment »

Difference between Struts and Spring

Posted by vidya on May 26, 2009

SNO

Struts

Spring

1 Struts is an MVC framework for developing web applications Spring is an End to End framework for developing enterprise applications
2 It’s easy to develop, Structured view/presentation layer of the MVC applications.
  • it’s a Lightweight Invention of Control and Aspect Oriented Container Framework
  • It’s adoptable and easy to run light weight applications.
  • It provides a framework to integrate OR mapping,JDBC etc
  • Struts can be used as the presentation tier in Spring
  • spring uses few tags less than struts, when need u can create using JSTL
3 Struts just does the mapping to jsp pages Spring integrates business logic and other frameworks
4 It has Action Forms It has no action forms(code reduces)
5 actions in the struts are the controllers Spring controllers are the interfaces
6 with respect to presentation level struts is better than spring
7 A strut is MVC pattern provides limited features.For distributed applications it will have to use EJB. Spring framework provides dependency injection. Which is alternative to EJB.Spring framework provides many features

like velocity,Hibernate,Ibatis,PDF,Excel

Views, JDO, Interceptors, web services. This can be built in Spring framework very easily. It is a J2EE application framework.

Posted in Java, Spring | Leave a Comment »

Rails Migration

Posted by vidya on May 26, 2009

add_column

Creates a new column on the specified table.

    add_column :table_name, :column_name, :column_type, { options }
  • :null => true or false – if false, the underlying column has a NOT NULL constraint added by the database engine
  • :limit => size – set a limit on the size of the field
  • :default => value – set a default value for the column

add_index

Creates an index for the specified table, the name of which defaults to table_column_index

    add_index :table_name, :column_name, :unique => true, :name => "chosen_index_name"

change_column

Change the data type of the specified column

    change_column :table_name, :column_name, :new_type, { options as add_column }

create_table

Creates a table on the database. Creates a table called :table_name and makes the table object available to a block that can then add columns to it, following the same format as add_column.

    create_table :table_name, { options } do |t|
      t.column :column_name, :column_type, :options
    end
  • :force => true – forces drop of an existing table of the same name before creation the new one
  • :temporary => true – creates a temporary table, one that goes away when the application disconnects from the database
  • :id => false – defines a table with no primary key, for example when you need to define a join table
  • :primary_key => :new_primary_key_name – overrides the default name of id for the primary column, use this to specify the name of the column in the database that Rails will use to store the primary key
  • :options => "" – lets you specify options to your underlying database, e.g. "auto_increment = 10000". Will lose default "ENGINE=InnoDB statement".

execute

Takes a single string identifying a valid SQL command to execute directly

    execute "alter table line_items add constraint fk_line_item_products foreign key (product_id) references products(id)"

IrreversibleMigration

Use in the down method of a migration file to raise an exception when the up methods of the same migration file can not be reversed, e.g. changing a column type from :integer to :string

    raise ActiveRecord::IrreversibleMigration

rename_table

Renames the specified table.

    rename_table :new_table_name, :old_table_name

rename_column

Renames the old_column_name to new_column_name

    rename_column :old_column_name, :new_column_name

rename_table

Renames the specified table.

    rename_table :new_table_name, :old_table_name

remove_index

Remove an index for the specified table.

    remove_index :table_name, :column_name

Example migration file

class CreateCustomers < ActiveRecord::Migration

def self.up
# Create “Customers” table
create_table :customers, :primary_key => :customer_id, :options => “auto_increment = 10000″ do |t|
# Add columns to “Customers” table
t.column :customer_id, :integer
t.column :name, :string, :limit => 30, :null => false
t.column :age, :integer
t.column :premium, :boolean, :default => 0
t.column :photo, :binary, :limit => 2.megabytes
t.column :thumbnail, :binary, :limit => 256.kilobytes
t.column :dob, :date, :null => false
t.column :created_at, :timestamp
t.column :notes, :text, :default => “No notes recorded”
end
# Add “surname” column to “Customers” table
add_column :customers, :surname, :string, :limit => 50
# Add “price” column to “Orders” table
add_column :orders, :price, :decimal, :precision => 8, :scale => 2
# Create a record on the “Customers” table
Customer.create :name => “David”, :surname => “Smith”, :age => “32″, :premium => “1″, :notes => “One of our top customers!”
end

def self.down
# Delete the “Customers” table
drop_table :customers
end
end

Posted in Rails | 2 Comments »

Rake tasks

Posted by vidya on May 26, 2009

Generate migration ruby script/generate migration your_chosen_migration_name
run all unapplied migrations rake db:migrate
migrate database to specific version rake db:migrate VERSION=18
use your migrations to recreate the tables in the testing or production databases rake db:migrate RAILS_ENV=production
Create a db/schema.rb file that can be portably used against any database supported by ActiveRecord rake db:schema:dump
Load a schema.rb file into the database rake db:schema:load
Loads a schema.rb file into the database and then loads the initial database fixtures. rake db:bootstrap

Posted in Rails, Rake | Tagged: , | Leave a Comment »

Multiple database search using Lucene

Posted by vidya on May 21, 2009

The muliple database search using lucene is just i am writing the logic how its working. we will see the step by step how its working.

Step 1: create the application and include the required jar files has given below.

  • lucene-core-2.0.0.jar
  • mysql connector
  • servlet-api

Step2 : create the below files

  • DbConnection.java – this containg mysql connectivity
  • IndexManager.java- here we will IndexWriter and adding the contents
  • SearchManager.java-this is for to search the search input from the indexing files
  • SearchQuery.java-it will map the multiple databases and queries.
  • SearchResultBean.java – it contains bean values
  • SearchController.java

Step 3: DBConnection.java

In this file we have create the db connection pool as usual. I connected to mysql.

Step 4: SearchQuery.java

Here i used two hashmaps , one is SearchConnectionHashMap andSearchQueryHashMap respectively.

Step 5: SearchResultBean.java

Created bean for title and content.

Step 6: IndexManger.java

used two loops for databases and database queries an inside used the

IndexWriter.Document doct=createDocument(contentResultset.getString(2),
contentResultset.getString(3));
indexWriter.addDocument(doct);

Then close the below statements without fail.

indexWriter.optimize();
indexWriter.close();

for createDocument is private static Document createDocument(String title, String content) {
Document doc = new Document();
doc.add(new Field(“title”, title, Field.Store.YES,
Field.Index.TOKENIZED, TermVector.YES));
doc.add(new Field(“content”, content, Store.YES,
Index.TOKENIZED, TermVector.YES));
return doc;
}

Now index has been created in the specified directory, now we have search the content from the index folder.

Step 7: SearchManager.java

To Search the content from the index, the following terms are important.indexSearcher = new IndexSearcher(indexManager.getIndexDir());

QueryParser queryParser = new QueryParser(“content”,analyzer);

Hits hits = indexSearcher.search(query);

Then we can set the title and content in the bean from the result set.

Step 8: SearchController.java

here we can get the parameter for searchword from the search.jsp and pass the parameter to SearchManager.java, finally forward it to result page.

Hence, that’s how i done for muliple search database search engine using lucene, if you any queires please let me know.

Posted in Java, JDBC | Tagged: , , , | Leave a Comment »

Update iframe src using javascript onload

Posted by vidya on April 22, 2009

when we are redirect the url from one page to another page, we may confuse how to update the iframe src with the browser parameter values if you using iframe, the solution is,

http://localhost/test_url/search.html?text=test

and iframe will be

<iframe id=”myFrame” frameborder=”0″ scrolling=”auto” src =”http://localhost:8080/regain/search.jsp?query=” width=”100%” height=”500″>
<p>Your browser does not support iframes.</p>
</iframe></td>

then write the script has given below,

<script>
window.onload=function() {
var querystr=window.location.search.substring(1, window.location.search.length).split(“=”)[1];
var iframesrc=document.getElementsByTagName(‘iframe’)[0].src;
iframesrc=iframesrc.split(“=”)[0]+”=”+querystr;
document.getElementsByTagName(‘iframe’)[0].src=iframesrc;
};
</script>

Posted in JavaScript | Tagged: , , | Leave a Comment »

how to call Stored Procedures in Java and spring

Posted by vidya on April 2, 2009

Step 1: Create new stored procedure in mysql.

DELIMITER $$

DROP PROCEDURE IF EXISTS `test_db`.`test`$$

CREATE PROCEDURE `test`()
BEGIN
truncate table person;
truncate table error_log;
END$$

DELIMITER ;

Step 2:Call Stored procedure into java code.

public static void main(String[] args) {
Connection con = null;
String url = “jdbc:mysql://localhost:3306/test_db”;
String driver = “com.mysql.jdbc.Driver”;
String user = “root”;
String pass = “”;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, user, pass);
try{

CallableStatement calstat=con.prepareCall(“{call test()}”); //SP call
ResultSet rs = calstat.executeQuery();

con.close();
calstat.close();
System.out.println(“Success Coonected with the datanase”);
}
catch (SQLException s){
System.out.println(“SQL code does not execute.”);
}
}
catch (Exception e){
e.printStackTrace();
}

}

Step 3 : In spring just we have to use given below instead of callable statement.

this.jdbcTemplate.update(“call test()”);

Posted in Java, JDBC | Tagged: , , , | Leave a Comment »

Plain JDBC vs. Spring JDBC

Posted by vidya on April 2, 2009

JDBC

Spring JDBC

DriverManager/

DataSource

DataSource

Statement/

PreparedStatement/

CallableStatement

JdbcTemplate/

SimpleJdbcaTemplate,

SimpleJdbcCall,

SimpleJdbcInsert,

MappingSqlQuery/

StoredProcedure

ResultSet/RowSet

POJOs / List of POJOs or

Maps / SqlRowSet

Posted in Java, Spring | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.