Monday, April 28, 2008

Hibernate with sample application

Step1:

Download the Hibernate distribution from the Hibernate website. Extract the package and place all required libraries found in /lib into into the /lib directory of your new development working directory.

Step2: Writing POJO

Our first persistent class is a simple JavaBean class with some properties:

package events;
import java.util.Date;
public class Event {
private Long id;
private String title;
private Date date;
public Event() {}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

You can see that this class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields
Place this Java source file in a directory called src/Events in the development folder.

Step3: Mapping File












Just as with the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use. So, in this case, Hibernate will look for getDate()/setDate(), as well as getTitle()/setTitle().

This mapping file should be saved as Event.hbm.xml, right in the directory next to the Event Java class source file.

Step4: Hibernate Configuration File


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">






org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost
sa



1


org.hibernate.dialect.HSQLDialect


thread


org.hibernate.cache.NoCacheProvider


true


create







We configure Hibernate's SessionFactory - a global factory responsible for a particular database. If you have several databases, use several configurations, usually in several configuration files (for easier startup).

The first four property elements contain the necessary configuration for the JDBC connection. The dialect property element specifies the particular SQL variant Hibernate generates. Hibernate's automatic session management for persistence contexts will come in handy as you will soon see. The hbm2ddl.auto option turns on automatic generation of database schemas - directly into the database. This can of course also be turned off (by removing the config option) or redirected to a file with the help of the SchemaExport Ant task. Finally, we add the mapping file(s) for persistent classes to the configuration.

Copy this file into the source directory, so it will end up in the root of the classpath. Hibernate automatically looks for a file called hibernate.cfg.xml in the root of the classpath, on startup.

Step5 :building with Ant



















destdir="${targetdir}"
classpathref="libraries"/>












Run the build file C:\hibernateTutorial\>ant


Step6 :
create a HibernateUtil helper class which takes care of startup and makes accessing a SessionFactory convenient. Let's have a look at the implementation:

package util;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}
This class does not only produce the global SessionFactory in its static initializer (called once by the JVM when the class is loaded), but also hides the fact that it uses a static singleton. It might as well lookup the SessionFactory from JNDI in an application server.

Step7: Loading and storing objects


Finally, we can use Hibernate to load and store objects. We write an EventManager class with a main() method:

package events;
import org.hibernate.Session;

import java.util.Date;

import util.HibernateUtil;

public class EventManager {

public static void main(String[] args) {
EventManager mgr = new EventManager();

if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}

HibernateUtil.getSessionFactory().close();
}

private void createAndStoreEvent(String title, Date theDate) {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);

session.save(theEvent);

session.getTransaction().commit();
}

}
We create a new Event object, and hand it over to Hibernate. Hibernate now takes care of the SQL and executes INSERTs on the database. Let's have a look at the Session and Transaction-handling code before we run this.



add a new listEvents() method:

private List listEvents() {

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

List result = session.createQuery("from Event").list();

session.getTransaction().commit();

return result;
}

Linux Commands

alias Create an alias
apropos Search Help manual pages (man -k)
awk Find and Replace text, database sort/validate/index
break Exit from a loop
builtin Run a shell builtin
bzip2 Compress or decompress named file(s)
cal Display a calendar
case Conditionally perform a command
cat Display the contents of a file
cd Change Directory
cfdisk Partition table manipulator for Linux
chgrp Change group ownership
chmod Change access permissions
chown Change file owner and group
chroot Run a command with a different root directory
cksum Print CRC checksum and byte counts
clear Clear terminal screen
cmp Compare two files
comm Compare two sorted files line by line
command Run a command - ignoring shell functions
continue Resume the next iteration of a loop
cp Copy one or more files to another location
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
csplit Split a file into context-determined pieces
cut Divide a file into several parts
date Display or change the date & time
dc Desk Calculator
dd Data Dump - Convert and copy a file
ddrescue Data recovery tool
declare Declare variables and give them attributes
df Display free disk space
diff Display the differences between two files
diff3 Show differences among three files
dig DNS lookup
dir Briefly list directory contents
dircolors Colour setup for `ls'
dirname Convert a full pathname to just a path
dirs Display list of remembered directories
du Estimate file space usage
echo Display message on screen
egrep Search file(s) for lines that match an extended expression
eject Eject removable media
enable Enable and disable builtin shell commands
env Environment variables
ethtool Ethernet card settings
eval Evaluate several commands/arguments
exec Execute a command
exit Exit the shell
expand Convert tabs to spaces
export Set an environment variable
expr Evaluate expressions
false Do nothing, unsuccessfully
fdformat Low-level format a floppy disk
fdisk Partition table manipulator for Linux
fgrep Search file(s) for lines that match a fixed string
file Determine file type
find Search for files that meet a desired criteria
fmt Reformat paragraph text
fold Wrap text to fit a specified width.
for Expand words, and execute commands
format Format disks or tapes
free Display memory usage
fsck File system consistency check and repair
ftp File Transfer Protocol
function Define Function Macros
gawk Find and Replace text within file(s)
getopts Parse positional parameters
grep Search file(s) for lines that match a given pattern
groups Print group names a user is in
gzip Compress or decompress named file(s)
hash Remember the full pathname of a name argument
head Output the first part of file(s)
history Command History
hostname Print or set system name
id Print user and group id's
if Conditionally perform a command
ifconfig Configure a network interface
import Capture an X server screen and save the image to file
install Copy files and set attributes
join Join lines on a common field
kill Stop a process from running
less Display output one screen at a time
let Perform arithmetic on shell variables
ln Make links between files
local Create variables
locate Find files
logname Print current login name
logout Exit a login shell
look Display lines beginning with a given string
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
ls List information about file(s)
lsof List open files
make Recompile a group of programs
man Help manual
mkdir Create new folder(s)
mkfifo Make FIFOs (named pipes)
mkisofs Create an hybrid ISO9660/JOLIET/HFS filesystem
mknod Make block or character special files
more Display output one screen at a time
mount Mount a file system
mtools Manipulate MS-DOS files
mv Move or rename files or directories
netstat Networking information
nice Set the priority of a command or job
nl Number lines and write files
nohup Run a command immune to hangups
nslookup Query Internet name servers interactively
passwd Modify a user password
paste Merge lines of files
pathchk Check file name portability
ping Test a network connection
popd Restore the previous value of the current directory
pr Prepare files for printing
printcap Printer capability database
printenv Print environment variables
printf Format and print data
ps Process status
pushd Save and then change the current directory
pwd Print Working Directory
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas
ram ram disk device
rcp Copy files between two machines.
read read a line from standard input
readonly Mark variables/functions as readonly
remsync Synchronize remote files via email
return Exit a shell function
rm Remove files
rmdir Remove folder(s)
rsync Remote file copy (Synchronize file trees)
screen Terminal window manager
scp Secure copy (remote file copy)
sdiff Merge two files interactively
sed Stream Editor
select Accept keyboard input
seq Print numeric sequences
set Manipulate shell variables and functions
sftp Secure File Transfer Program
shift Shift positional parameters
shopt Shell Options
shutdown Shutdown or restart linux
sleep Delay for a specified time
sort Sort text files
source Run commands from a file `.'
split Split a file into fixed-size pieces
ssh Secure Shell client (remote login program)
strace Trace system calls and signals
su Substitute user identity
sum Print a checksum for a file
symlink Make a new name for a file
sync Synchronize data on disk with memory
tail Output the last part of files
tar Tape ARchiver
tee Redirect output to multiple files
test Evaluate a conditional expression
time Measure Program running time
times User and system times
touch Change file timestamps
top List processes running on the system
traceroute Trace Route to Host
trap Run a command when a signal is set(bourne)
tr Translate, squeeze, and/or delete characters
true Do nothing, successfully
tsort Topological sort
tty Print filename of terminal on stdin
type Describe a command
ulimit Limit user resources
umask Users file creation mask
umount Unmount a device
unalias Remove an alias
uname Print system information
unexpand Convert spaces to tabs
uniq Uniquify files
units Convert units from one scale to another
unset Remove variable or function names
unshar Unpack shell archive scripts
until Execute commands (until error)
useradd Create new user account
usermod Modify user account
users List users currently logged in
uuencode Encode a binary file
uudecode Decode a file created by uuencode
v Verbosely list directory contents (`ls -l -b')
vdir Verbosely list directory contents (`ls -l -b')
vi Text Editor
watch Execute/display a program periodically
wc Print byte, word, and line counts
whereis Report all known instances of a command
which Locate a program file in the user's path.
while Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
Wget Retrieve web pages or files via HTTP, HTTPS or FTP
xargs Execute utility, passing constructed argument list(s)
yes Print a string until interrupted
. Run a command script in the current shell
### Comment / Remark



if
Conditionally perform a command. SYNTAX
if test-commands; then
consequent-commands;
[elif more-test-commands; then
more-consequents;]
[else alternate-consequents;]
fi


case
Conditionally perform a command, case will selectively execute the command-list corresponding to the first pattern that matches word.
SYNTAX
case word in [ [(] pattern [ pattern]...) command-list ;;]... esac

The `' is used to separate multiple patterns, and the `)' operator terminates a pattern list. A list of patterns and an associated command-list is known as a clause. Each clause must be terminated with `;;'.


Here is an example using case in a script that could be used to describe one interesting feature of an animal:

echo -n "Enter the name of an animal: "
read ANIMAL
echo -n "The $ANIMAL has "
case $ANIMAL in
horse dog cat) echo -n "four";;
man kangaroo ) echo -n "two";;
*) echo -n "an unknown number of";;
esac


echo " legs."The return status is zero if no pattern is matched. Otherwise, the return status is the exit status of the command-list executed.

eval
Evaluate several commands/arguments
SYNTAX
eval [arguments]


expr
Evaluate expressions, evaluates an expression and writes the result on standard output.
SYNTAX
expr expression...

for
Expand words, and execute commands once for each member in the resultant list, with name bound to the current member.

Syntax
for name [in words ...]; do commands; done
for (( expr1 ; expr2 ; expr3 )) ; do commands ; done

gawk (gnu awk)
Find and Replace text, database sort/validate/index

Syntax
awk 'Program' Input-File1 Input-File2 ...
awk -f PROGRAM-FILE Input-File1 Input-File2 ...

m4
macro processor

SYNTAX
m4 [Options...] [Macro-Definitions...] [Input-File...]


grep
Search file(s) for specific text.

SYNTAX
grep "Search String" [filename]
grep [-e pattern] [file...]
grep [-f file] [file...]
A simple example:
$grep “Needle in a Haystack” /etc/*

egrep
Search file(s) for lines that match an extended expression (extended grep)
SYNTAX
egrep [ options ] 'PATTERN' files ...

fgrep
Search file(s) for lines that match a fixed string

SYNTAX
fgrep ...

fgrep is the same as `grep -F'
all other options are the same as grep
It's a popular fallacy that `fgrep' stands for fast-grep.In fact `fgrep' means fixed-string grep, it has no performance boost over `grep'

Monday, March 31, 2008

UNIX






The UNIX operating system is made u
p of three parts; the kernel, the shell and the programs.

The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.

As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.

The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems).

Files and processes
Everything in UNIX is either a file or a process.
A process is an executing program identified by a unique PID (process identifier).
A file is a collection of data. They are created by users using text editors, running compilers etc.
Examples of files:
a document (report, essay etc.)
the text of a program written in some high-level programming language
instructions comprehensible directly to the machine and incomprehensible to a casual user, for example, a collection of binary digits (an executable or binary file);
a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.
The Directory Structure
All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / )


The full path to the file report.doc is "/home/its/ug1/ee51vn/report.doc"


Listing files and directories
ls (list)
The ls command lists the contents of your current working directory.

There may be no files visible in your home directory, in which case, the UNIX prompt will be returned. Alternatively, there may already be some files inserted by the System Administrator when your account was created.

Files beginning with a dot (.) are known as hidden files and usually contain important program configuration information.

% ls -a
To list all files in your home directory including those whose names begin with a dot,files that are normally hidden

mkdir (make directory)
To make a subdirectory called unixstuff in your current working directory type

% mkdir unixstuff

cd (change directory)
To change to the directory you have just made, type

% cd unixstuff

The current directory (.)
In UNIX, (.) means the current directory, so typing
% cd .

The parent directory (..)
(..) means the parent of the current directory, so typing

% cd ..

will take you one directory up the hierarchy (back to your home directory).

Note: typing cd with no argument always returns you to your home directory. This is very useful if you are lost in the file system.

pwd (print working directory)
to find out the absolute pathname of your home-directory, type cd to get back to your home-directory and then type
% pwd

The full pathname will look something like this -
/home/its/ug1/ee51vn

which means that ee51vn (your home directory) is in the sub-directory ug1 (the group directory),which in turn is located in the its sub-directory, which is in the home sub-directory, which is in the top-level root directory called " / " .

Home directories can also be referred to by the tilde ~ character. It can be used to specify paths starting at your home directory. So typing

% ls ~/unixstuff

will list the contents of your unixstuff directory, no matter where you currently are in the file system.

cp (copy)
cp file1 file2
is the command which makes a copy of file1 in the current working directory and calls it file2

mv (move)
mv file1 file2 moves (or renames) file1 to file2

rm (remove), rmdir (remove directory)
% rm tempfile.txt

clear (clear screen)
% clear
This will clear all text and leave you with the % prompt at the top of the window.

cat (concatenate)
The command cat can be used to display the contents of a file on the screen. Type:
% cat science.txt

http://www.ee.surrey.ac.uk/Teaching/Unix/unix2.html