Hibernate operations (Data Deletion) - Part 4

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"


package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)


Data Deletion

Before writing codes for data deletion, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve,update and delete from db. If you do not have at least basis of the HQL please refer part 2 of this article series.


So, now let move to data deletion, this deletion is also a some kind of update to the db. Because deletion means removing specific field or fields from a table by changing its status (status means number of fields, file size, etc). Therefore the method that we used for update the db can be used for data deletion also. Here code for data deletion is not much differ from data updating.

Therefore the HQL query for data deletion is,

delete from Person

If we use this query itself for data deletion, the query will delete the current element from the table. But this thing won't be used for practical scenarios. Therefore we have to let it know 'what records to be deleted' by executing the query.

HQL query for data deletion with conditions

delete from Person as p where p.id = :key

Here I used the parameter(if you can remember) for this query named 'key'. (Need 'what is the parameter?' please refer part2 of this article series). Therefore the complete java code for this query is,


String searchId = "1";
String query = "
delete from Person as p where p.id = :key";

session.createQuery(query).setString("key",
searchId).executeUpdate();

Simply this is the way to update the database also, only change of this code is the word 'delete' in the query. Isn't it easy?...........But finally remember to commit the operation because 'we change the database's data'.

The complete java code for data deletion is,

package pkg;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
       
String searchId = "1";//this is the key id for field being updated
       
        //create the delete query
       
String query = "delete from Person as p where p.id = :key";
       
       
session.createQuery(query).setString("key", searchId).executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

If you execute this code segment the field with id of  "1" will be deleted (if exist).
Also I have to mention here the method createQuery() will return the number of fields that it changed by executing the query. Therefore if you want to get the number of fields that changed or check whether any changes had been done by the query, you can use that number. To do that first assign the number return by method to the int variable.

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

After that you can use this variable for get the number of fields that changed or check whether any changes had been done by the query.

For example,

int fieldCount = session.createQuery(query).setString("key", searchId).executeUpdate();

if(fieldCount > 0)
    System.out.printf("Number of fields changed %d\n", fieldCount);
else
    System.out.printf("No changes had been done\n");

Hmmmmm.... so this is the last article for hibernate operation article series. If you go through all the parts of this article series you will be able to do basic hibernate operations such as,
  • Data insertion.
  • Data updating
  • Data retrieving
  • Data deletion.


Related posts
Continue Reading...

Hibernate operations (Data Retriving) - Part 3

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data retrieving through hibernate. (Data insertion article can be found at Part 1 of this series and data update article can be found at Part 2 of this article series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Retriving
Before writing codes for data retrieving, you should have a knowledge about HQL for the hibernate. This HQL can be use to data retrieve from db. If you do not have at least basis of the HQL please refer part 2 of this article series.

It is very easy to retrieve data from the db by just executing HQL query but getting data in java program from the result of the executed query is some what hard.

The query for retrieve all data from Person class is,

from Person

This query can be execute by executing following java code segment.

String query = "from Person";
session.createQuery(query);

These codes will be executed successfully but where is the result which returned from the executed query?
In hibernate the result of the HQL query can be caught by java.util.List. Therefore code for retrieving data can be update as follows.


Now list object hold the all of data which return from the executed query.

Now let's see how to access to the list in order to get the real data. To acquire this we have to use java.util.Iterator class. So do not forget this is Hibernate(a ORM tool) therefore we can use getters from 'Person' class to get the particular data. If we going to use getters, it should be included some data into instance variables in the class. Therefore we can assign data into Person type object.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

Person obj = (Person) iterator.next();//cast and assign data to Person type object

System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");

We can use while loop to view all data on the result set.

String query = "from Person";
List list = session.createQuery(query).list();
       
Iterator iterator = list.iterator();

while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

Also you can implement conditional retrieving using 'where' keyword.

String searchId = "1";
String query = "from Person as p where p.id = :sId";
List list = session.createQuery(query)
        .setString("sId", searchId).list();
       
Iterator iterator = list.iterator();
       
while (iterator.hasNext()) {
        Person obj = (Person) iterator.next();//cast and assign data to Person type object
           
        System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
}

The complete java code for data retrieving is,

apackage pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
//import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
             
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();


        session.beginTransaction();

        String searchId = "1";
        String query = "from Person as p where p.id = :sId";
        List list = session.createQuery(query)
                    .setString("sId", searchId).list();
       
        Iterator iterator = list.iterator();
       
        while (iterator.hasNext()) {//is next data exist? then loop
            Person obj = (Person) iterator.next();//cast and assign next data to Person type object
           
            System.out.print(obj.getId() + "\t" + obj.getAge() + "\t" + obj.getName() + "\n");
        }
       
        session.close();

Now as an example let's consider our table data are looks like this,

+----+-----+-------------------+
| id | age | name              |
+----+-----+-------------------+
|  1 |  23 | Milinda           |
|  2 |  24 | Milinda Aruna     |
|  4 |  25 | Aruna Milinda UWU |
|  5 |  25 | Aruna UWU Milinda |
+----+-----+-------------------+
The output of this code segment is,

1    23    Milinda

Related posts
Continue Reading...

Hibernate operations (Data Update) - Part 2

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data update through hibernate. (Data insertion article can be found at Part 1 of this series)

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.
(This class is identical to the class that we used in part 1)

Data Update
Before writing codes for updating let me introduce the HQL for the hibernate. This HQL can be use to update the db. It is essential to get know about HQL  before move to further operations of hibernate.

HQL - The Hibernate Query Language
HQL is similar in appearance to SQL that can be used as a a powerful query language for Hibernate.HQL is a case insensitive query language. Therefore as an example the keyword fRoM, FrOm, from and FROM are identical for a query.

The first HQL query.

from
from is the simplest possible Hibernate query. Let's clarify this by using few examples.

from Person

This will return all the data from Person table. The equaling sql query is,

/*this is equaling sql query for 'from Person'*/
select * from Person

In order to refer to the Person in other parts of the query, you can assign an alias for Person using 'as' keyword.

from Person as P
/*Now P refer the Person table*/

Also this can be acquired without using 'as' keyword.

from Person P
/*Now P refer the Person table*/

Parameters
These parameters can be used within the the query to pass values when they are executing in the java program.

The sign  :  used to define the parameters.

from Person as p where p.id = :personId

Here 'personId' is a parameter. Now lets execute a HQL query in java. Basically to execute a HQL query the method 'createQuery' in the class 'org.hibernate.classic.Session' is used.

String searchId = "1";
String query = "from Person as p where p.id = :personId";

session.createQuery(query).setString("personId", searchId);

When call the method 'createQuery' the value of 'searchId' will assign to the parameter 'personId' in the query. Finally the query for execute is,

from Person as p where p.id = 1

Now let's combine update and these 2 concepts to execute the update query. 'createQuery' method can be used execute the update query. A update query uses the keyword 'update' as follows


'keyId' is a parameter for the query which can be used to pass a value when it execute.

The complete java program for the update is,

package pkg;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

    public static void main(String[] args) {
       
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Person.class);
        config.configure("hibernate.cfg.xml");
       
        SessionFactory factory = config.buildSessionFactory();
             
        //beginning of the session
        Session session = factory.openSession();
        session.beginTransaction();//beginning of the transaction
       
        String name = "New_Milinda";//this is new name for 'id'
        String id = "1";//this is the key id for field being updated
       
        //create the update query
        String query = "update Person as p set p.name = :newName where p.id = :keyId";
       
        session.createQuery(query)
            .setString("newName", name)//this will set the string 'newName' to name variable
            .setString("keyId", id)
            .executeUpdate();
        

        session.getTransaction().commit();//end of transaction
        session.close();//end of  session
       
       
        }

}

After this code segment run the data's which having id equal 1 will change its name into 'New_Milinda'. Here I used 'where' keyword to implement the condition for the update. (similar method used in mysql queries)

Finally the query to be executed is,

update Person as p set p.name = New_Milinda where p.id = 1

Also this is the query after setting all the parameters(newName and keyId).


I hope to post more articles for other operations of hibernate such as
  • Data retrieve
  • Data delete
from the db. Will be soon........

Related posts

Continue Reading...

Hibernate operations (Data insertion) - Part 1

Hibernate is an object-relational mapping (ORM) library for the Java language. Hibernate provides data query and retrieval facilities that significantly reduce the development time. Hibernate facilitates you to develop persistent classes following an object-oriented styles such as inheritance, polymorphism, composition, association, and collections.

This article only concern about data insertion to the db through hibernate.

And also I have to mention here this article not describing all the hibernate from the beginning. Therefore this is not the best way to start your first hibernate java project. Simply this article very much suitable for the people those who having basis of the hibernate.

Hibernate is a ORM tool. Therefore it is not necessary to care about db type (whether MySql or derbydb or another) when you programming a application for a db. But you have to concern only about the 'connection.driver_class' and 'connection.url' in the 'hibernate.cfg.xml' file to match the db type.

Therefore you can change your database type at anytime without changing whole java codes or queries written for da operations. It is the power of Hibernate.

To start these all the sample programs you should do the initial thing such as adding related jar files, referring those jars, establish MySql db connection(from eclipse or netbeans to view db's data), etc.


Initiating............
First let's create java class which used as a persistent class.
Create a java class named "Person.java"

package pkg;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {
 private int id;
 private String name;
 private int age;

 @Id
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

This class is now persistent class through annotations.

Data insertion
Data insertion can be done using this persistent class's object. Following sample code shows the way to insert data to a database through hibernate.

 Create a java class named "TestPerson.java" with main method.

package pkg;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestPerson {

 public static void main(String[] args) {

  //create configurations for Person class
  AnnotationConfiguration config = new AnnotationConfiguration();
  config.addAnnotatedClass(Person.class);
  config.configure("hibernate.cfg.xml");

  //create new schema(db and table)
  new SchemaExport(config).create(true, true);//comment this line if you already created the table Person
 
  SessionFactory factory = config.buildSessionFactory();
  Session session = factory.getCurrentSession();
 
  session.beginTransaction();//begin the db operations
 
  //Insertion to the table
  Person person = new Person();//create the object from persistent class
  //set data that you want to store in db
  person.setId(1);
  person.setName("Milinda");
  person.setAge(24);
  
  session.save(person);//save the object to db
 
  session.getTransaction().commit();//save permanently to db(end of db operations)
 }
}

Now data(id=1, name=Milinda and age=24) will be stored in the 'Person' table. Finally the 'Person' table's data can be shows as follows.

+----+-----+----------+
| id | age | name     |
+----+-----+----------+
|  3 |  24 | Milinda  |
+----+-----+----------+

Note- You can remove(or comment) the code line new SchemaExport(config).create(true, true); if you already create the db and particular tables.(This code line responsible for create tables on th db)

I hope to post more articles for other operations of hibernate such as
  • Data update
  • Data retrieve
  • Data delete
from the db. Will be soon........


Related posts
Continue Reading...

Add Hibernate javadoc to eclipse

Javadoc is a convenient way to learn and get help from documents which are provided by the programmer. These javadoc can be added to Eclipse IDE to view appropriate javadoc for a particular class or method or interface etc. These javadocs views on eclipse when auto complete (or content assist) appear. You can view the content assist by pressing 'Ctrl+Space'.

 
You can see the javadoc window on right hand side of this figure.

By default the javadoc for hibernate distribution does not exists. To add the javadoc to eclipse follow these steps.

Step 1
Download javadoc jar file from following link
hibernate-3.2.2.ga-javadoc.jar
Any how you should download the hibernate-3.2.2.ga-javadoc.jar file.

Step2 
Open eclipse and add above jar file to hibernate3.jar as a javadoc for it. To do that follow the steps explained below.

Step 3
Right click on 'hibernate3.jar' by expanding user library which contain all your hibernate reference jar files. And select 'Properties'.

Step 4
Select 'Javadoc Location' from side pane and click on 'Javadoc in archive' to select it.

Step 5
Browse for downloaded jar file and add that jar file location as javadoc location for 'hibernate3.jar'.

Step 6
Click 'Apply' and 'OK' to save the changes.


Now it is done you can view javadoc from eclipse.


Continue Reading...

Usefull PIC programming tips for PIC16f877A

This article totally depends on my experiences when I doing some microcontroller projects based on PIC16f877A. Further more following article describe the answers which I found for following questions.

Make RA4(4th bit of PORTA) as a digital output.

All the bits on all the ports in PIC16f877A microcontroller can be configure as digital input or output except RA4. All other bits on ports can be configure as a digital I/O by changing its TRIS register's values and configuring ADCON1 register(for analog input pins). But if we consider about RA4 pin, its behavior different than other I/O pins.
RA4 is an open collector I/O pin. Therefore when we want to use RA4 as a digital output, we have to pull up RA4 by a resistor. This approach can be understand by following example.
This is an example program to use RA4 as a digital output using Hi-Tech C.

#include <htc.h>
#define _XTAL_FREQ 4000000
void main(){
    TRISA = 0;//PORTA is output
   
    //configure ADCON1 to set PORTA as digital I/O
    PCFG0 = 0;
    PCFG1 = 1;
    PCFG2 = 1;
    PCFG3 = 0;
   
    ADON = 0;//ADC modulde is off
   
    while(1){
        RA4 = 1;//Now LED will off
        __delay_ms(100);
        __delay_ms(100);
        __delay_ms(100);
        RA4 = 0;//Now LED will on
        __delay_ms(100);
        __delay_ms(100);
        __delay_ms(100);
    }
}

Finally what we have to do is, supply a current to LED attached to RA4 and change the logic to on and off the LED.

Status on RA4 LED status
1 (High) Off
0 (Low) On

References and further readings-
The best source for understand the behavior of the PIC is "Data sheet".

This is a cropped part from PIC16f877A data sheet.



All the bits on PROTB can be used as digital input except RB3. Because by default the Low-Voltage ICSP Programming (LVP) is enabled in PIC16f877A which lead to disable RB3 I/O function. If you do not use LVP, you can disable LVP by following these steps in MPLAB IDE.

  1. Configure
  2. Configuration bit.
  3. Uncheck Configuration Bits set in code.
  4. Select disable on LVP field.
  5. Close and recompile the code.
Now you can use RB3's input function by changing TRISB's 3rd bit into 1.(TRISB3 = 1)

References and further readings-
The best source for understand the behavior of the PIC is "Data sheet".

  This is a cropped part from PIC16f877A data sheet.
Continue Reading...

Create your own ant build file to create a jar file.


Apache Ant is a build tool mainly focus on Java to build Java applications. Ant uses the xml script file to perform tasks such as,
  • compiling source code, 
  • running software tests, 
  • creating jar files, 
  • creating Javadocs, and 
  • keeping your own file structure within the project folder.
 As I earlier explained Ant uses simple xml file to perform its tasks. Therefore let's see how to write a simple xml file for Ant to compile and create a jar file using Java source classes.
I have to mention here there are 2 kind of jar files,
  1. jar file which can be use as a library to another program.
  2. jar file which can be run (runnable) on the operating system.
Ant can use to either create jar file or runnable jar file. First let's create a jar file(not a runnable jar file).

Structure of the xml file.
Ant xml file includes mainly  three elements,
  1. Property - can be consider as a variable of the xml file.
  2. Target - can be consider as a function in C which can be reuse and modularized.
  3. Task - can be consider as a command on the terminal or C.
Initially let's start with a simple task.

First create a file named 'build.xml' and type following codes.


<project default="final" name="yourProjectName">

</project>

Code explanation........
name in project tag-
Name of your project should be here
default in project tag-
Default target script will start to run(Explained later)
Now create a simple target(function) to execute task(command). As a first step let's echo some text to terminal.


<project default="final" name="yourProjectName">
           <target name="final" description="this is a function to echo some text">
                    <echo message="Hello world..."/>
           </target>
</project>

Code explanation........
name in target tag-
Name of this target(function) this name can be use to recall the target
echo-
Use to print text on terminal
Now run the xml file
  • In terminal,
    • change the directory to directory which include the build.xml file(using 'cd' command) and type ant and press enter.
  • In Eclipse,
    • Right click on source file, select Run as -> Ant Build file
It will print Hello world... on the terminal/console screen.

Now let's consider about two targets (functions).

<project default="final" name="yourProjectName">
           <target name="initial" description="this is a function to echo some text">
                    <echo message="Hello world..."/>
           </target>

          <target name="final" depends="initial" description="this is a function to echo some text">
                    <echo message="Hello world..."/>
           </target>

</project>


Code explanation........
depends in target tag-
This is very important attribute to make our program flow correctly. Here first, program will direct to default target which is defined in project tag. Now program wait until the 'initial' target finish its tasks at 'final' target. ('final' target depends on 'initial' target therefore after finishing 'initial' target's tasks, the target 'final' can be started). Finally program flow will be firstly 'initial' target and then 'final' target.
Now let's try to crate jar file using Ant

Create jar file using ant

In order to create jar file there should be some requirements,
  • Basically, Java source code file(s).
  • compile versions of these Java source files.
  • well understood file structure within the project folder.

Therefore first organize our project folder by creating folders and placing our files into correct locations.

src folder use to place Java source files.
lib folder use to place all necessary external jar files.
build folder use to place temporary class files(compiled files)
dist folder use to place final jar file which is created by Ant


After organizing the project folder, place your build.xml file in the directory which all the above folders included.

Initially, let's compile our Java source files to create class files. To accomplish that the task(command) 'javac' can be used. javac is a task which is defined in Ant(more details can be found at Ant reference manual)

syntax-
<javac srcdir="sourceDir" destdir="destinationDir"/>
srcdir-
full path to the directory which include Java source file(s)
destdir-
full path to the directory, compiled file(s) to be created(destination to create .class files)
Now full code to compile Java source file(s) looks like follow,

<project default="final" name="yourProjectName">
           <target name="final" description="this is a function to compile Java source files">
                    <javac srcdir="sourceDir" destdir="destinationDir"/>
           </target>
</project>


 Code explanation........
Here, javac task simply embed into a target in order to make program more clear. This code can be expect some exception, generating destination directory not found or something like that. To prevent that exception we should create a destination folder(because destination folder does not exist in the project folder)

mkdir task can be used to create a new directory.

<project default="compileMe" name="yourProjectName">
           <target name="compileMe" description="this is a function to compile Java source files">
                     <mkdir dir="destinationDir"/>
                    <javac srcdir="sourceDir" destdir="destinationDir"/>
           </target>
</project>


Code explanation........
mkdir-
make a new directory, name defined by dir attribute

As you can see here, still we did not use any real path for codes. Because the path is depend on user's disk names, disk letter, user names, etc.
The best way to give a path is give it as a relative path to the task. Now property element take place to create relational variable based on paths(locations on the disk). So if we declare an relative variable who is the referrer? OR the variable relative to what?
Therefore we have to give base directory to the program to refer that location and create relative variables for location.

Declare properties and compile Java source file(s)

<project default="compileMe" name="yourProjectName" basedir=".">
    
            <property name="srcDir" location="src"/>
            <property name="buildDir" location="build"/>

           <target name="compileMe" description="this is a function to compile Java source files">
                     <mkdir dir="${buildDir}"/>
                    <javac srcdir="${srcDir}" destdir="${buildDir}"/>
           </target>
</project>


Code explanation........
basedir in project tag-
base directory of all the location property(Here it is '.' that is the directory  itself which save the build.xml file)
name in property tag-
Name of the property(can give any meaningful name)
location in property tag-
Relative location of the disk. As an example, let's say my basedir is '/home/milinda/workspace/AntTest' when Ant assign value to srcDir it concatenate base directory and relative property's location to make absolute path of the directory. Finally srcDir = '/home/milinda/workspace/AntTest/src'
${buildDir}-
This is the way to access to a property in Ant build file(here ${buildDir}=/home/milinda/workspace/AntTest/build and ${srcDir}=/home/milinda/workspace/AntTest/src)

Now this Ant file will run correctly on any directory with the src (java source file directory) directory.


Create jar file using Ant

jar is the task which is defined by Ant to create jar file by using Java class files and other configuration files.

Syntax-
<jar jarfile="destinationDir/jarfileName.jar" basedir="baseOnWhatDir">

destinationDir/jarfileName.jar-
full path of jar file to be created.
basedir-
full path to the directory which compiled file(s) are located.
Now we can create another directory for save the jar file which can be created by using compiled Java files from 'build' directory. Finally code for making jar file is looks like.


<project default="makeJar" name="yourProjectName" basedir=".">
    
            <property name="srcDir" location="src"/>
            <property name="buildDir" location="build"/>
            <property name="distDir" location="dist"/>

           <target name="compileMe" description="this is a function to compile Java source files">
                     <mkdir dir="${buildDir}"/>
                     <javac srcdir="${srcDir}" destdir="${buildDir}"/>
           </target>

           <target name="makeJar" depends="compileMe" description="this is a function to make jar file">
                      <mkdir dir="${distDir}"/>
                      <jar jarfile="${distDir}/finalRelease.jar" basedir="${buildDir}"/>
            </target>
</project>





Continue Reading...

Set custom pictures for slide show in ubuntu desktop wallpapers

Is that possible to change your desktop wallpaper automatically after some specific time period in Ubuntu environment?
Yes, it is.
To do that you should create xml file that contain all the information about,
  • picture files which you going to add for slide show,
  • time duration for each wallpaper can appear,
  • time for transition from one wallpaper to another.
This xml file should be written manually when you want to create custom slide show using your own picture files and your own configurations(such as durations).

Don't worry it is not a difficult thing since I have a script file to create that xml file easily.

Follow these steps to create your own fully customized slide show for Ubuntu desktop wallpaper.

Step 1 - Download my 'Script file' which can generate the xml file automatically.

Step 2 - Copy downloaded script file to folder which contain picture files(jpg or png or bmp format).

Step 3 - Make sure your picture files those you want to add to your slide show and script file is located in the same folder.

Step 4 - Double click on the script file and run it in terminal.
OR
you can use following commands to run script file in terminal
  1. Open terminal (By pressing Alt+Ctrl+T or selecting 'Terminal' from application)
  2. Direct your working directory to folder which contain downloaded script file and picture files.(By using cd command ex:- cd '/home/milinda/Desktop/My show')
  3. Run the script file by using ./Script command.(if any permission problem occur use chmod 700 Script command to set permission of the file before calling ./Script command)
Step 5 - Enter relevant durations when request by the terminal.(firstly time duration for each wallpaper can appear, and secondly time for transition from one wallpaper to another.)

Now you can see xml file which created by the script on the relevant directory. Named background-1.xml.

Step 6 - Right click on the desktop select Change Desktop Background from the pop up menu.

Step 7 - Navigate to Background tab and click on Add.. button.

Step 8 - Open the generated xml file(background-1.xml file).

Now you can see your slide show appear in the preview area. you can set this slide show as your current desktop slide show by clicking on it.

Finally you have your own fully customized slide show for Ubuntu desktop.


Note -
  • Script file involve only for generate the xml file it self. It does not affect to your system.
  • When you want to add picture files or change your picture files which run on slide show, you should respectively copy or delete and just rerun the script file.
Bugs -
  • In order to create xml file, any picture file's name should not include spaces. Therefore make sure any of your picture files does not include space(s).[Bug fixed in 1.1 version you can now download newest version]
  • This script can only handle maximum of 255 picture files. Therefore do not copy more then 255 number of picture files into the folder.

 Downloads
Continue Reading...

How to install Adobe Flash Player plugin on Ubuntu for Firefox

NOTE Click here for latest version of this article. This is only valid for older version of Firefox.

Adobe flash player is also a plug-in for for Mozilla Firefox to view flash videos (ex: youtube videos) and play flash on-line games, etc. Therefore flash player became essential plug-in for most of the web browsers until HTML 5 take place (because HTML 5 has new capabilities those can challenge to flash player such as video playing).

This article describe how to install Adobe Flash Player plug-in for Firefox on Ubuntu

You might be think, is this a very harder thing?

Yes, some times.

Because, Ubuntu software center and Synaptic package manager can use to install flash player plug-in for some Ubuntu versions and it will simply works. But some Ubuntu distribution such as Ubuntu 11.04 natty 64-bit needs to follow following few steps to make it work correctly.

Step 1- Download latest Adobe Flash Player Plug-in form here.(Select download option as 'tar.gz for other Linux')
Step 2- Extract downloaded file into any directory. (extracted file should be .so format)

Step 3- Open terminal (Application --> Accessories --> Terminal or Ctrl+Alt+T)

Step 4- Type following command

sudo -i

Now it will prompt you the Password. Now enter the password and press enter  

Step 5- Goto directory that contain extracted .so file using cd command (Ex: cd Downlods)

Step 6- Copy that .so file into /usr/lib/mozilla/plugins directory. To copy that file use following command.

cp [fileName].so /usr/lib/mozilla/plugins

(Ex: cp libflashplayer.so /usr/lib/mozilla/plugins)

Step 7- Restart the system to make changes appear to Firefox.

It is better to close all the Firefox related windows before copy the .so file. Remember you should restart the system to make plug-in work correctly (Not only restart Firefox)

If this article helpful to some one please do not forget to comment about it.
Continue Reading...