Saturday, March 31, 2012

Writing custom cursor adapter to use data from a SQLITE database with AutoCompleteTextView

In this post i am going to discuss how to implement a custom cursor adapter that take the data from a sqlite database and populate the  AutoCompleteTextView on the fly.

First let us write our database code which return a cursor. ( Here i only display the related method to return cursor. You have to write a new class extending  "android.database.sqlite.SQLiteOpenHelper" and write the database initialization and open logic in the class. )



1:  public synchronized Cursor getAutoCompleteCursor(String prefix){  
2:         Cursor c = null;  
3:         if(prefix.compareTo("")==0){  
4:              c = myDataBase.query("dict", new String[]{ID_COLUMN_NAME},   
5:                     ID_COLUMN_NAME+" like '' || ? || '%'",   
6:                     new String[]{"*"},   
7:                     null,   
8:                     null,   
9:                     null);  
10:         }else{  
11:              c = myDataBase.query("tableName",   
12:                        new String[]{COLUMN_NAME},   
13:                     ID_COLUMN_NAME+" like '' || ? || '%'",   
14:                     new String[]{prefix},   
15:                     null,   
16:                     null,   
17:                     null);  
18:         }  
19:         if(c == null & c.getCount() <= 0){  
20:              new Exception("Cursor " + (c==null?"null":" fill with wrong data"));  
21:         }  
22:         return c;  
23:    }  





Here "tableName" is the name of the table and "COLUMN_NAME" is the name of the column in table you want to bind with auto complete view.

My database is a very large one so when query for empty string it returns a large number of rows. This will lead to throw an exception in GPU level (creating a view larger than 40000 rows). So i used a conditional check to verify the empty string and at the initial point i query for a string that is not in database to retrieve a empty cursor and on the second letter enter and onward it will query for the prefix and get suggestion list. Another method i used to overcome this memory issue is to use a threshold in  AutoCompleteTextView so it will start to display suggestions only after the number of characters exceed threshold.

Then we write a class extending CursorAdapter class and implementing the filterable interface to include the view generation logic with the listening to key events in background and query the database to obtain suggestion words.


1:  
2:  import android.content.Context;  
3:  import android.database.Cursor;  
4:  import android.view.LayoutInflater;  
5:  import android.view.View;  
6:  import android.view.ViewGroup;  
7:  import android.widget.AutoCompleteTextView;  
8:  import android.widget.CursorAdapter;  
9:  import android.widget.Filterable;  
10:  import android.widget.TextView;  
11:  public class CustomCursorAdaptor extends CursorAdapter implements Filterable {  
12:       private DatabaseHelper dbHelper;  
13:       private LayoutInflater inflater ;  
14:       public CustomCursorAdaptor(Context context, Cursor c) {  
15:            super(context, c);  
16:            this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
17:            this.dbHelper = DatabaseHelper.getDatabaseHelper(context);  
18:       }  
19:       @Override  
20:       public void bindView(View view, Context context, Cursor cursor) {            
21:            String keyword = cursor.getString(cursor.getColumnIndex(DatabaseHelper.ID_COLUMN_NAME));  
22:      TextView tv = (TextView) view.findViewById(R.id.sugestionTextView);  
23:      tv.setText(keyword);  
24:       }  
25:       @Override  
26:       public View newView(Context context, Cursor cursor, ViewGroup parent) {  
27:            return inflater.inflate(R.layout.list_item, null);            
28:       }  
29:     @Override
31: public CharSequence convertToString(Cursor cursor) {
32:  
33:  return cursor.getString(cursor.getColumnIndex(DatabaseHelper.DICT_ID_COLUMN_NAME));
34: }
35:       @Override  
36:       public Cursor runQueryOnBackgroundThread(CharSequence constraint) {  
37:            //return super.runQueryOnBackgroundThread(constraint);  
38:            if(getFilterQueryProvider() != null){  
39:                 return getFilterQueryProvider().runQuery(constraint);  
40:            }  
41:            String filter = "";  
42:            if(constraint != null){  
43:                 filter = constraint.toString();  
44:            }  
45:            return dbHelper.getIdCursor(filter);  
46:       }  
47:  }  

Here at the construct i initialize the LayoutInflater and obtain the reference to my DatabaseHelper class which was written by extending the SQLiteOpenHelper and included the getAutoCompleteCursor method.

We have to override two abstract methods in the class which are newView and bindView.

In newView  write our code to use the inflater and populate a view return it to current cursor position. Here i used this method to populate my custom written "list_item" layout and return a view of that layout.

1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:id="@+id/sugestionTextView"  
4:    android:layout_width="fill_parent"  
5:    android:layout_height="fill_parent"  
6:    android:padding="10dp"  
7:    android:textSize="16sp"  
8:    android:textColor="#000">  
9:  </TextView>  

"list_item.xml" file

In bindView we used to populate an existing view that is being reused with data in our cursor. Here i get a string from the cursor, create a text view by finding a sugestionTextView which is located in my "list_item" xml file and set the text view with the string i obtained from the cursor.

In the method runQueryOnBackgroundThreadhas been used to run a background thread each time a new character been entered to AutoCompleteTextView and obtain a cursor with the prefix text that is in the AutoCompleteTextView at that point.

Finally in the Activity class write the following code inside onCreate method to initialize the new CursorAdapter implementation class and set the adapter to AutoCompleteTextView.


1:  autoText = (AutoCompleteTextView) findViewById(R.id.autoCompleteEnglishWordText);  
2:  autoText.setThreshold(2);  
3:  CustomCursorAdaptor cursurAdaptor = new CustomCursorAdaptor(this, null);  
4:  autoText.setAdapter(cursurAdaptor);


Tuesday, March 20, 2012

Python list comprehensions for string sub listing

I am still learning python language which apparently needed for implement some tools regarding my research. And i came through this amazing feature in python lists.
Although i know python can do amazing stuff that no other popular languages can do, this thing suprised me a lot.

So what is this list comprehensions ?
A list comprehension is a way to describe a list. If you have taken mathematics basic class you might be familiar with set theories and for each of set we use we have a definition for that set.

For an example lets say a list that has all the even numbers. We can write this definition in mathematical way like below.

E = { x | x%2=0}
This means set s has all the x values that suppress the condition of "remaining of x by 2 is 0".

When it comes to set of strings, we can define those sets in the same way.

Alphabet = { x | x in 'a' to 'z'} 
V = { a , e , i , o , u }

So in python language it has been facilitated to use the similar notation we used in mathematical definitions.

Say we want to obtain a separate list of items from a main list that has a special string within it.

prefix = "http"
dirListing = os.listdir(sys.argv[1])
httpList = [x for x in dirListing if prefix in x]

Above python sample code demonstrate how to sub list the set of strings that contains "http" within the strings from set of strings.
Here we say that "httpList" list should contain all the x values where x is in "dirListing" list and x contains "dnsString" within it.





Sunday, March 18, 2012

Configure manually Apache HTTPD and PHP in your machine.

There are "WAMP" and "XAMP" softwares that install all three apache httpd web server, php interpreter and mysql server, and automate the configuration process with just few clicks. But just  think of a situation where you have previously installed mysql instance running !


Either you have to uninstall the current instance of mysql server and install one of above "three in one" packs or change the port number of the newly installing my sql server. But what is the point of running two mysql instances at the same machine ???? (adding another service to windows means resources will be eaten more). Even though you uninstall current mysql server and install WAMP or XAMP there might be high chance that you will end up those installations not working due to some conflict with previously installed and now removed mysql instance and the one in WAMP or XAMP.


So it is always better to keep the current mysql instance and configure the other two with the existing one. And after all it is fun! and you can  be proud of your self about what you have done because almost all the php developers depends on wamp and when it comes to the server configuration and deployment environment you cant depend on a WAMP ! its just a development tool (and what if you do you client wants MS SQL server instead of mysql offer in WAMP ? ). So be an adult and do things by your self.


Ok enough talking lets start the work.


First download the latest releases of Apache HTTPd web server, PHP interpreter from the links. (Please download the executable files since that will be helpful with some auto configurations )


Then create a directory called "web" in the location c drive "c:\web". (name of the directory can be anything you like but without spaces, we dont install to "program files" because of the space in file path, try to avoid spaces in file path.)


Installing apache httpd server


Launch the setup (double click on setup.exe) and choose custom. Then choose the directory as "c:\web\apache" and enter the information of your server in to the following window.
( I prefer,
Network Domain - localhost
server name - localhost
Email Address - anything@you.want  If you intend to use the server in local development)


apache-install 
  Click next and choose content to install as showed in below.


apache-install-2 


And finish the setup.


Installing PHP setup.


Launch the setup and when prompt to select a location select the "c:\web\php" as the location.


In next window select the server which u wish to configure the PHP interpreter with shown as below. ( here we choose apacheXXX where XXX is the version of the apache httpd server that you have downloaded and installed previously)


php-install-2 


In next prompt choose the apache configuration directory in our case "c:\web\Apache\conf". 


On next window choose the libraries you wanted to install with PHP.


(Caution!!! some of the modules will not be compatible with the current PHP interpreter version that we are installing this might give us errors when we run the interpreter. If you are a newby most of the time you will miss understand this errors as miss configurations. So its better to leave not installing modules for now since we can add modules by editing "php.ini" manually later.)


Configuring apache server


First you have to add the a map to localhost and your server name if it is not "localhost" that you have entered in the beginning of apache server installation process. To do this open the host file in the "c:\windows\system32\drivers\etc\hosts" location using text editor (Most of the time if you are not in the administrator account you wont be able to save the edited host file. In that case copy the host file to Desktop edit it, save it there and copy back to the location of the original host file by overwriting it).



127.0.0.1 localhost
127.0.0.1 yourDomain


Then we are going to edit apache configuration files. ( keep in mind to use forward slash '/' instead of back slash '\' in file paths ).

(First of all copy and backup the "c:\web\apache\conf\httpd.conf" file in case of things gone wrong)

Open "c:\web\apache\conf\httpd.conf" and search for the lines.

1. DocumentRoot
DocumentRoot "c:/web/Apache/htdocs"

change this to any directory you prefer to use to  store your html and php files. (lets say "c:\web\www").

DocumentRoot "c:/web/www"
2. Then change 

<Directory "c:/web/Apache/htdocs">
to
<Directory "c:/web/www">

3. Add entry for php in the apache configuration file.
#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "C:/web/PHP"
LoadModule php5_module "C:/web/PHP/php5apache2_2.dll"
AddType application/x-httpd-php .php
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

4. Include index.php to apache directory index files.
DirectoryIndex index.html index.htm index.php




Configuring PHP

(First of all copy and backup the "c:\web\php\php.ini " file in case of things gone wrong) 

Edit php.ini file located in "c:\web\php\php.ini".

1. Change the display errors on.
display_errors = Off
to
display_errors = On

2. Copy all the "php5apache2_2.dll" in php root directory and ext directory to "c:\windows\system32" directory with edited php.ini file.


Adding or removing modules to php.ini

Edit php.ini file and add entries for required modules.

Eg:

[PHP_MCRYPT]
extension=php_mcrypt.dll
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll
[PHP_OPENSSL]
extension=php_openssl.dll
[PHP_PDO]
extension=php_pdo.dll
[PHP_SOAP]
extension=php_soap.dll
[PHP_SQLITE]
extension=php_sqlite.dll
[PHP_XMLRPC]
extension=php_xmlrpc.dll
[PHP_ZIP]

Adding MySQL support to PHP


Here i assumed that you have already installed mysql server and configured it. Do not store your mysql host, user and password fields in php.ini file even though php mysql configuration allows to store them.

[MySQLi]

; Maximum number of links.  -1 means no limit.
mysqli.max_links = -1

; Default port number for mysqli_connect().  If unset, mysqli_connect() will use
; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services or the
; compile-time value defined MYSQL_PORT (in that order).  Win32 will only look
; at MYSQL_PORT.
mysqli.default_port = 3306

; Default socket name for local MySQL connects.  If empty, uses the built-in
; MySQL defaults.
mysqli.default_socket =

; Default host for mysql_connect() (doesn't apply in safe mode).
mysqli.default_host =

; Default user for mysql_connect() (doesn't apply in safe mode).
mysqli.default_user =

; Default password for mysqli_connect() (doesn't apply in safe mode).
; Note that this is generally a *bad* idea to store passwords in this file.
; *Any* user with PHP access can run 'echo get_cfg_var("mysqli.default_pw")
; and reveal this password!  And of course, any users with read access to this
; file will be able to reveal the password as well.
mysqli.default_pw =

; Allow or prevent reconnect
mysqli.reconnect = Off

Testing
 



Write the following php code. Store it as index.php in your webroot location. ( here we use "c:\web\www" ).

<?php phpinfo(); ?>



Then open a browser and type localhost in address bar. You will get a similar page as below.



Saturday, March 17, 2012

Ant target to start axis2 server

Here i will describe how to write ant target to start apache axis2 server directly from your "build.xml" file without calling any shell script file. For this purpose we use "org.apache.axis2.transport.SimpleAxis2Server" class and pass it few arguments to tell it about our configuration files and service folder path.

First let us add locations to class path.
(here the ${axis-homerefers to the root of your apache axis2 directory.)



<path id="axis-classpath">
 <pathelement location="${axis-home}"/>
 <pathelement location="${axis-home}/conf"/>
 <pathelement location="${env.JAVA_HOME}/lib/tools.jar"/>
 <fileset dir="${axis-home}/lib">
  <include name="*.jar"/>
 </fileset>
</path>

with adding those paths to the class path let us write ant target to start axis2 server like below.


<target name="start-axis">
 <java classname="org.apache.axis2.transport.SimpleAxis2Server" fork="true">
  <classpath refid="axis-classpath" /> 
  <jvmarg value="-Djava.endorsed.dirs=${axis-home}/lib/endorsed;${env.JAVA_HOME}/jre/lib/endorsed;${env.JAVA_HOME}/lib/endorsed" />
  <arg line="-repo ${axis-home}/repository"/>
  <arg line="-conf ${axis-home}/conf/axis2.xml"/>
 </java>
</target>


Here we pass a jvm argument stating all the endorsed folder paths and two runtime arguments which are the location for service repository and path to axis configuration file.

Friday, March 16, 2012

Ant target for Apache Tomcat

This tutorial will explain how to write an ant target to start and stop tomcat. For this task we use a special class located in "tomcat/bin/bootstrap.jar" namely "org.apache.catalina.startup.Bootstrap". Also this  jar will be depend on another jar which is located at the same location "tomcat/bin/tomcat-juli.jar".

First add these locations to a class path like below.
(here the ${tomcat} refers to the root of your tomcat directory.)


<path id="tomcat-classpath">
 <fileset dir="${tomcat}/lib">
  <include name="*.jar" />
 </fileset>
 <fileset dir="${tomcat}/bin">
  <include name="tomcat-juli.jar" />
  <include name="bootstrap.jar" />
 </fileset>
</path>


Then we write start-tomcat target to start the apache tomcat.


<target name="start-tomcat">
 <java classname="org.apache.catalina.startup.Bootstrap" fork="true">
  <classpath refid="tomcat-classpath" />
  <jvmarg value="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager" />
  <jvmarg value="-Djava.util.logging.config.file=${tomcat}/conf/logging.properties" />
  <jvmarg value="-Dcatalina.home=${tomcat}" />
  <jvmarg value="-Dcatalina.base=${tomcat}" />
  <jvmarg value="-Djava.io.tmpdir=${tomcat}/temp" />
  <arg line="start"/>
 </java>
</target>


And then we write the stop-tomcat target to stop the running tomcat instance.


<target name="stop-tomcat">
 <java classname="org.apache.catalina.startup.Bootstrap" fork="true">
  <classpath refid="tomcat-classpath" />
  <jvmarg value="-Dcatalina.home=${tomcat}" />
  <arg line="stop" />
 </java>
</target>


Ok! we are done!!!

Wednesday, March 14, 2012

Configuring mysql server for ruby


Even though sqlite 3 officially ported with rails, in mass scale application production environments, the typical candidate will be MySQL due to several reasons like its open source, established an a reliability.

 
  1. If you have already installed MySQl server skip to step 2 directly other wise download it from here and run the UI installer and it will guide u through the steps. ( You need to made couple of requirements inorder to run this msi package sucessfully one is .NET 4 framework and second Microsoft C++ runtime 2010 32 bit package.)
  2. After that go to this location and download the zip file which contain MySQL c driver.
  3. UNZIP the file.
  4. Copy the dll file in "mysql-connector-c-noinstall-6.0.2-win32-vs2005\lib" location to " <your-ruby&rails-installation-directory>\ruby <version>\bin " directory.

Sunday, March 11, 2012

Install Ruby on Rails to Windows 7




Recently i have found that i like to learn new programming language and choose ruby to full fill my desire. But all the tutorials i have found how to install rails and configure gems are outdated and it took me 3 days to create a project correctly without giving any errors about missing gems or dev kit.

So that inspired me to write a guide on how to install rails correctly. ( i further wish to write more on ruby later)

So let us start the work then.

  • First go to this website and download the latest release of  "rails installer for windows" ( at the moment i m writing this blog the newest release was 2.1.0). This installer comes with current ruby language interpreter, rails framework and dev kit, all 3 in one.

  • After downloading it double click on the exe file and follow the steps to install the setup. ( i prefer a location in top level of C drive (eg: C:\ruby) because of spaces in the path will be problematic sometimes). 

  • After finishing the installer go to start menu and find "All Programs > RailsInstaller > Git Bash " and click it. This will open a command prompt like terminal (if you have previously work with git you may find out this is the same  terminal that git has provide). Or you can use windows command prompt as well.



  • Then type "ruby -v" to check the ruby version and "gem -v" to check the gem version.


  • And then type "rails -v" where the prompt say that it is unknown command and this is because even though we installed rails it has not been configured yet as a gem. 

  • Type " gem install rails --include-dependencies " to install rails gem and you are done. ( of course this may take few time )
Installing Rails
  • Re check by typing "rails -v".



  • Create a new folder in any where you like to create ruby projects. Open a command window and "cd" to that folder. Then type "rails new testApp". ( here testApp is my test applications name you can give any name and this will be your project name". After issuing this command rails will create a ruby project for you with all the dependencies, configurations and scripts.


  • Type "rails server" to start ruby server on your localhost. Then go to your web browser and type "http://localhost:3000" . You will get a page like below. (ruby server use port 3000)

You’re riding Ruby on Rails!













Saturday, March 10, 2012

Reverse engineering - Generating hbm.xml from annotated POJO

I have look for these particular scenario every where but couldnot found anything usefull other than the hibernate tools documentation. Reason the people not doing this is because hibernate - tools are mainly using for reverse engineering where this is not coming across. Only scenario i can think of where you need to generate a hibernate mapping xml from a POJO which is already annotated ( annotations are the successor of hibernate mapping xmls) is when you are in middle of the migration process from hibernate mapping xmls to annotations.

People already developing a product are not likely to suddenly adapting the changes. So they do it, step by step when it is needed so in such a case first you write annotation base POJOs but really not using them instead u generate the hbm.xml from the annotations, is the best way to work around. And also writing POJO separately and mapping separately increase the possibility of  erroneous of the code. Instead generating one automatically when the other given is much applicable which in case reduce   the time of the development and make the process more efficient.

enough talking now i will explain the process
only to generate the hbm mapping i only needed hibernate-tool-xx.jar and fremarker.jar but to run a complete hibernate base code using the generated hbm i need the following dependencies so before you start better to include all of them in to your lib directory

below jars are coming with hibernate distribution
antlr-2.7.6.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar                                                              
hibernate3.jar
slf4j-api-1.6.1.jar
jta-1.1.jar
javassist-3.12.0.GA.jar

and you have to download these separately
commons-collections-3.2.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jtidy-r8-21122004.jar
mysql-connector-java-5.0.4-bin.jar (if you use mysql as back end database)
slf4j-simple-1.6.1.jar
freemarker.jar
hibernate-tools-3.2.4.GA.jar

that is all you need. And lets begin coding you have to write an ant build script with following target and taskdef which need to create hbm.xml mapping for your pojo

 <taskdef name="hibernatetool"   
                classname="org.hibernate.tool.ant.HibernateToolTask"   
                classpathref="lib" />  
      <taskdef name="annotationconfiguration"   
                classname="org.hibernate.tool.ant.AnnotationConfigurationTask"   
                classpathref="lib" />  
      <target name="init" depends="copy-resources">  
           <hibernatetool destdir="${builddir}">  
                <classpath>  
                     <path location="${srcdir}" />  
                     <path location="${libdir}" />  
                     <path location="${builddir}" />  
                </classpath>  
                <annotationconfiguration configurationfile="${srcdir}/hibernate.cfg.xml" />  
                <hbm2hbmxml />  
           </hibernatetool>  
      </target>  

Put this ant file in to your project and write a POJO with annotations as they used to write in. (Everything is normal than the crazy work - trying to generate hbm.xml from annotations.)

And here is the important part. You have to include your pojo's full class path into your hibernate.cfg.xml (hibernate configuration file) as a mapping.

Below is my example hibernate.cfg.xml ,

 <?xml version='1.0' encoding='utf-8'?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD//EN"  
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
 <session-factory>  
  <property name="hibernate.connection.driver_class">  
 com.mysql.jdbc.Driver</property>  
  <property name="hibernate.connection.url">  
 jdbc:mysql://localhost:3306/testhib</property>  
  <property name="hibernate.connection.username">root</property>  
  <property name="hibernate.connection.password">1234</property>  
  <property name="hibernate.connection.pool_size">1</property>  
  <property name="show_sql">true</property>  
  <!-- <property name="hibernate.bytecode.provider">javassist</property> -->  
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  <property name="hibernate.hbm2ddl.auto">update</property>  
  <!-- Mapping files -->  
  <mapping class="com.example.User"/>  
  <mapping class="com.example.Task"/>  
  </session-factory>  
 </hibernate-configuration>  

here my POJOs which are  "com.example.User"  and "com.example.Task"  list under the mapping where normally hbm.xml goes. What happen here is the when the ant target "init" is called it tell hibernate tool task to read the hibernate configuration file and find the mapping class files then it goes to class path folders defined under hibernatetool task, travel the folder structure defined in package name and find the .class file, read the annotations in the .class file and generate the mappings in your directory where you defined under "destdir".

Editing XML using apache ant target - dtd validation

To acomplish this specific task and automate the xml injections there is a tool called XmlTask which can be download here.

For more information about how to write a ant target or use xmltask you can refer this guide.

This article is not about how to use xmltask actually it is a situation i have to face whilie using this. My machine connects to a proxy server when it connect to internet or other network and when inserting or updating ant task "xmltask" use the dtd declared in <!DOCTYPE >. Actually it tries to download it if it is not in a local machine. So with the proxy i got java.net.ConnectException .


 [xmltask] It looks like you've got a network error. The probable cause  
  [xmltask] is that you're trying to resolve a DTD on the internet although  
  [xmltask] you don't know it! Check your XML for DTDs external to your network  
  [xmltask] and read the Ant documentation for <xmlcatalog>. XMLTask will support  
  [xmltask] usage of <xmlcatalog>. See the following:  
  [xmltask] http://ant.apache.org/manual/CoreTypes/xmlcatalog.html  
  [xmltask] http://www.oopsconsultancy.com/software/xmltask  
  [xmltask] If this isn't the problem, then please report this error to the support  
  [xmltask] mailing list. Thanks!  
  [xmltask] Connection refused  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.documentFromStream(XmlTask.java:372)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.documentFromFile(XmlTask.java:400)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.access$000(XmlTask.java:27)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask$InputFile.getDocument(XmlTask.java:216)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.execute(XmlTask.java:651)  
  [xmltask]   at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)  
  [xmltask]   at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)  
  [xmltask]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
  [xmltask]   at java.lang.reflect.Method.invoke(Method.java:597)  
  [xmltask]   at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)  
  [xmltask]   at org.apache.tools.ant.Task.perform(Task.java:348)  
  [xmltask]   at org.apache.tools.ant.Target.execute(Target.java:357)  
  [xmltask]   at org.apache.tools.ant.Target.performTasks(Target.java:385)  
  [xmltask]   at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)  
  [xmltask]   at org.apache.tools.ant.Project.executeTarget(Project.java:1306)  
  [xmltask]   at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)  
  [xmltask]   at org.apache.tools.ant.Project.executeTargets(Project.java:1189)  
  [xmltask]   at org.apache.tools.ant.Main.runBuild(Main.java:758)  
  [xmltask]   at org.apache.tools.ant.Main.startAnt(Main.java:217)  
  [xmltask]   at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)  
  [xmltask]   at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)  
  [xmltask] Caused by: java.net.ConnectException: Connection refused  
  [xmltask]   at java.net.PlainSocketImpl.socketConnect(Native Method)  
  [xmltask]   at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)  
  [xmltask]   at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)  
  [xmltask]   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)  
  [xmltask]   at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)  
  [xmltask]   at java.net.Socket.connect(Socket.java:529)  
  [xmltask]   at java.net.Socket.connect(Socket.java:478)  
  [xmltask]   at sun.net.NetworkClient.doConnect(NetworkClient.java:163)  
  [xmltask]   at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)  
  [xmltask]   at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)  
  [xmltask]   at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)  
  [xmltask]   at sun.net.www.http.HttpClient.New(HttpClient.java:306)  
  [xmltask]   at sun.net.www.http.HttpClient.New(HttpClient.java:323)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.startEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.startDTDEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDTDScannerImpl.setInputSource(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.documentFromStream(XmlTask.java:356)  
  [xmltask]   ... 20 more  
  [xmltask] --- Nested Exception ---  
  [xmltask] java.net.ConnectException: Connection refused  
  [xmltask]   at java.net.PlainSocketImpl.socketConnect(Native Method)  
  [xmltask]   at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)  
  [xmltask]   at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)  
  [xmltask]   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)  
  [xmltask]   at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)  
  [xmltask]   at java.net.Socket.connect(Socket.java:529)  
  [xmltask]   at java.net.Socket.connect(Socket.java:478)  
  [xmltask]   at sun.net.NetworkClient.doConnect(NetworkClient.java:163)  
  [xmltask]   at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)  
  [xmltask]   at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)  
  [xmltask]   at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)  
  [xmltask]   at sun.net.www.http.HttpClient.New(HttpClient.java:306)  
  [xmltask]   at sun.net.www.http.HttpClient.New(HttpClient.java:323)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)  
  [xmltask]   at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.startEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLEntityManager.startDTDEntity(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDTDScannerImpl.setInputSource(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(Unknown Source)  
  [xmltask]   at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)  
  [xmltask]   at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.documentFromStream(XmlTask.java:356)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.documentFromFile(XmlTask.java:400)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.access$000(XmlTask.java:27)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask$InputFile.getDocument(XmlTask.java:216)  
  [xmltask]   at com.oopsconsultancy.xmltask.ant.XmlTask.execute(XmlTask.java:651)  
  [xmltask]   at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)  
  [xmltask]   at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)  
  [xmltask]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
  [xmltask]   at java.lang.reflect.Method.invoke(Method.java:597)  
  [xmltask]   at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)  
  [xmltask]   at org.apache.tools.ant.Task.perform(Task.java:348)  
  [xmltask]   at org.apache.tools.ant.Target.execute(Target.java:357)  
  [xmltask]   at org.apache.tools.ant.Target.performTasks(Target.java:385)  
  [xmltask]   at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)  
  [xmltask]   at org.apache.tools.ant.Project.executeTarget(Project.java:1306)  
  [xmltask]   at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)  
  [xmltask]   at org.apache.tools.ant.Project.executeTargets(Project.java:1189)  
  [xmltask]   at org.apache.tools.ant.Main.runBuild(Main.java:758)  
  [xmltask]   at org.apache.tools.ant.Main.startAnt(Main.java:217)  
  [xmltask]   at org.apache.tools.ant.launch.Launcher.run(Launcher.java:257)  
  [xmltask]   at org.apache.tools.ant.launch.Launcher.main(Launcher.java:104)  

what i did is as the tutorial dtd section suggested i have define <xmlcatalog> tag and map the local dtd source file to the public id like below example.


 <xmlcatalog id="dtd">  
   <dtd   
    publicId="-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   
    location="./servlet-2.3.dtd"/>   
 </xmlcatalog>  


and then it gives another error when the edited xml file is parsing by my another program. The error is due to <!DOCTYPE> declaration is missing.
What happen is when we use xmlcatalog to define the local path , and when we insert a xml code to the document and write it back to a file , it elemenates the <!DOCTYPE > declaration in the newly writing file. If we overide the exisiting file we loose it from the only file we have. So to overcome this problem what i did was insert public id and system uril inside the <xmltask> tag itself like below.

 <xmltask source="etc/hibernate.cfg.xml" dest="etc/hibernate.cfg.xml" public="-//Hibernate/Hibernate Configuration DTD 3.0//EN"   
          system="http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
                <xmlcatalog id="dtd">  

tomcat 7 taglib definition not consist issue

I have encountered this when i tried to port a java war file which is previously deployed in tomcat 6.0.13 to newest tomcat version tomcat 7.0.14

when the web container trying to deploy the .war file it throws an exception saying that

jndi:/localhost/application/WEB-INF/web.xml
java.lang.IllegalArgumentException: taglib definition not consistent with application version

and i when i googled for this problem i found only one mail thread regarding this tomcat 7 issue 

and i tried with all the options described their and finally found the solution that is write tags inside of which resolve the problem


  
  <jsp-config>
      <taglib>
          <taglib-uri>
              http://metawerx.net/mapp/taglibs
          </taglib-uri>
          <taglib-location>
              /WEB-INF/mapp.tld
          </taglib-location>
     </taglib>
  </jsp-config>


for more details about refer this site

printf("Hello World");



Although i have tried several times i could not continue blogging. But there is a huge need of blogging for me to document the problems that i have encountered and solutions i applied. After several unsuccessful attempts i decided to write this blog which i hope will be a purely technical one.

First 4 posts that will post in here be the ones i have written when i m doing my internship a year back. Those have been posted to a separate blog by me which of course have been down recently.

Thank you,
Have a fun.