août

29

Posted by : admin | On : 29 août 2010

Pre-requis : install rootsh.install (that give you the hand into your device by typing sudo gainroot)

1 / How to Add 9 dektop into Nokia N900 ?

You can install Winscp on your PC and control your phone cell by intalling OpenSSH Server on your device .

a) Install OpenSSH on your device

b) open a SSH connection on port 22

c) make a find on one of your favorite wallpaper  for instance « digital_nature1_03.jpg »

ex :

sudo

gainroot

find / -name "MyBackground.jpg" -print 2>/dev/null

d) install hildon menu (you can find it into the apps manager)

gconftool -s /apps/osso/hildon-desktop/views/5/bg-image -t string "/home/user/MyDocs/.images/digital_nature2_02.jpg"
gconftool -s /apps/osso/hildon-desktop/views/6/bg-image -t string "/home/user/MyDocs/.images/digital_nature2_03.jpg"
gconftool -s /apps/osso/hildon-desktop/views/7/bg-image -t string "/home/user/MyDocs/.images/digital_nature4_02.jpg"
gconftool -s /apps/osso/hildon-desktop/views/8/bg-image -t string "/home/user/MyDocs/.images/digital_nature1_04.jpg"
gconftool -s /apps/osso/hildon-desktop/views/9/bg-image -t string "/home/user/MyDocs/.images/digital_nature1_03.jpg"
gconftool  -s  /apps/osso/hildon-desktop/views/active  -t  list  –list-type  int  [1,2,3,4,5,6,7,8,9]

Result : 9 nice desktop :D

août

14

Posted by : admin | On : 14 août 2010

Open a Notepad File Win key + Notepad

then copy these few lines :

  • Windows 32bits
SET vlcpath="%C:\Program Files\VideoLAN\VLC%"
CD %vlcpath%

start vlc.exe --open=http://mafreebox.freebox.fr/freeboxtv/playlist.m3u
  • Windows 64bits :
SET vlcpath="%C:\Program Files (x86)\VideoLAN\VLC%"
CD %vlcpath%

start vlc.exe --open=http://mafreebox.freebox.fr/freeboxtv/playlist.m3u

Save the file as for instance TV.bat on your desktop , and you’ll done !

Double click on the file you’ve just created, then the Tv provide by Free should open and launch on :) Enjoy !

Si vous êtes possesseur d’une Freebox et que vous souhaitez regarder la télé sur votre ordinateur, très simple copier coller le script ci dessus ;)

juin

17

Posted by : admin | On : 17 juin 2010

Configuration Realized :

Carte mère : Gigabyte GA-785GMT-USB3 =80€

Compatible : CPU AM3  : AMD 785G + SB710 Chipset

RAM : 4Go DDR3  :KINGSTON DDR3 HyperX 2×2 Go PC3-12800 (1600MHz) = 108€
CPU :AMD Phenom II X4 965 Black Edition (Socket AM3) =169€
Disque Dur Hitachi 1 To = 70€

Carte Graphique : ATI HD RADEON 5450 1Gb DDR3  =50€

OS : UBUNTU 10.04 LTS

COOLER MASTER Elite 334 + Alimentation 460 W

^o^ Possible to realise Dual Screen :) 24″ + 19″ or more.

COOLER MASTER Elite 334 + Alimentation 460 W

TOTAL : 534€

I found around the same configuration at DEll store at around 749€ / 949€ .

  • Other Advantages:

-Gobally the configuration doesn’t make any noise, I’ve choose  the Fan Enermax.

-Quality of the component used in the motherborad & saving  energy consumption

-Price

-USB 3.0

-Scapability of hardware configuration

  • Disadvantage :

-Have some knowledge in Electronic  to assemble the different components of the motherboard.

I strongly recommend to view the CPU LIST compabilty of the motherboe

Processor Support for AM3 processors: AMD Phenom™ II processor/ AMD Athlon™ II processor
Hyper Transport Bus 5200 MT/s
Chipset North Bridge: AMD 785G
South Bridge: AMD SB710
Memory 4 x 1.5V DDR3 DIMM sockets supporting up to 16 GB of system memory (Note 1)
Dual channel memory architecture
Support for DDR3 1800 (OC)/1666/1333/1066 MHz memory modules
Onboard Graphics Integrated in the North Bridge:
1 x D-Sub port
1 x DVI-D port (Note 2) (Note 3)
1 x HDMI port (Note 3)
Audio Realtek ALC889 codec
High Definition Audio
2/4/5.1/7.1-channel
Support for Dolby Home Theater
Support for S/PDIF In/Out
Support for CD In
LAN Realtek 8111D chip (10/100/1000 Mbit)
Expansion Slots 1 x PCI Express x16 slot, running at x16 (PCIEX16)
(The PCI Express x16 slot conforms to PCI Express 2.0 standard.)
1 x PCI Express x1 slot
2 x PCI slots
Storage Interface South Bridge:
1 x IDE connector supporting ATA-133/100/66/33 and up to 2 IDE devices
5 x SATA 3Gb/s connectors supporting up to 5 SATA 3Gb/s devices
1 x eSATA 3Gb/s port on the back panel supporting up to 1 SATA 3Gb/s device
Support for SATA RAID 0, RAID 1, RAID 10 and JBOD
iTE IT8720 chip:
1 x floppy disk drive connector supporting up to 1 floppy disk drive
USB South Bridge:
Up to 12 USB 2.0/1.1 ports (Note 4) (6 on the back panel, 6 via the USB brackets connected to the internal USB headers)
NEC D720200F1 chip:
Up to 2 USB3.0 ports on the back panel
IEEE 1394 T.I. TSB43AB23 chip:
Up to 2 IEEE 1394a ports (1 on the back panel, 1 via the IEEE 1394a bracket connected to the internal IEEE 1394a header)
Internal I/O Connectors 1 x 24-pin ATX main power connector
1 x 8-pin ATX 12V power connector
1 x floppy disk drive connector
1 x IDE connector
5 x SATA 3Gb/s connectors
1 x CPU fan header
1 x system fan header
1 x front panel header
1 x front panel audio header
1 x CD In connector
1 x S/PDIF In/Out header
3 x USB 2.0/1.1 headers
1 x IEEE 1394a header
1 x serial port header
1 x clearing CMOS jumper
Rear Panel I/O 1 x PS/2 keyboard port or PS/2 mouse port
1 x D-Sub port
1 x DVI-D port (Note 2)(Note 3)
1 x HDMI port (Note 3)
1 x optical S/PDIF Out connector
1 x eSATA 3Gb/s port
1 x IEEE 1394a port
4 x USB 2.0/1.1 ports
2 x USB 3.0/2.0 ports
1 x RJ-45 port
6 x audio jacks (Center/Subwoofer Speaker Out/Rear Speaker Out/Side Speaker Out/Line In/Line Out/Microphone)
I/O ITE IT8720 chip
H/W Monitoring System voltage detection
CPU/System temperature detection
CPU/System fan speed detection
CPU overheating warning
CPU/System/Power fan fail warning
CPU/System fan speed control (Note 5)
BIOS 2 x 8 Mbit flash
Use of licensed AWARD BIOS
Support for DualBIOS™
PnP 1.0a, DMI 2.0, SM BIOS 2.4, ACPI 1.0b
Unique Features Support for @BIOS
Support for Q-Flash
Support for Xpress BIOS Rescue
Support for Download Center
Support for Xpress Install
Support for Xpress Recovery2
Support for EasyTune (Note 6)
Support for Easy Energy Saver
Support for Time Repare
Support for Q-Share
Bundle Software Norton Internet Security (OEM version)
Operating System Support for Microsoft Windows 7/Vista/ XP
Form Factor Micro ATX Form Factor; 24.3cm x 24.3cm
Note (Note 1) Due to Windows Vista/XP 32-bit operating system limitation, when more than 4 GB of physical memory is installed, the actual memory size displayed will be less than 4 GB.
(Note 2) The DVI-D port does not support D-Sub connection by adapter.
(Note 3) Simultaneous output for DVI-D and HDMI is not supported.
(Note 4) Two share the same port with USB3.0.
(Note 5) Whether the CPU/system fan speed control function is supported will depend on the CPU/system cooler you install.
(Note 6) Available functions in EasyTune may differ by motherboard model.

juin

02

Posted by : admin | On : 2 juin 2010

Extraire Mp3 du Flv

#!/bin/bash
find /home/$USER/Vidéos/youtube/*flv  -print | \
while read file
do
#Extract the mp3 file from flv
mplayer "$file" -dumpaudio -dumpfile "$file".mp3 2>/dev/null
echo "1 -> Extraction mp3 de $file "
user=`whoami`
echo "2 -> Changement des droits du fichiers extraits en $user"
sudo chown `whoami`:`whoami` "${file}".mp3
NomFichier=`echo ${file} | sed -e "s/^.*\/\([^\/]*\)$/\1/g"`
NomFichierTraite=`echo "${NomFichier}" | sed "s/_/ /g" | sed "s/.flv//g"`
CheminAbsolu=`pwd`
mv  "${file}.mp3" "${CheminAbsolu}/$NomFichierTraite.mp3"
echo "ø Fichier :" ${NomFichierTraite}.mp3
done

Iphone on ubuntu

Source http://fatbuttlarry.blogspot.com/2010/01/ipod-touch-iphone-3g-ubuntu-910-in-5.html

  1. If you’ve already tried using the iPhone with other tutorials, try reverting your changes. Andrew has outlined this for us very well here. Follow the first two steps. There is also an official French tutorial here that a 3.1.1 user alviju has had success with.
  2. Make sure you are connected to the internet.
  3. Open gnome-terminal through Applications –> Accessories –> Terminal
  4. Copy / paste the following in the console:

    sudo add-apt-repository ppa:pmcenery/ppa; sudo apt-get update; sudo apt-get install gvfs gvfs-backends gvfs-bin gvfs-fuse libgvfscommon0 ifuse libgpod-common libimobiledevice-utils libimobiledevice0 python-libimobiledevice libplist++1 libplist-utils python-plist libusb-1.0-0 libusbmuxd1 usbmuxd; sudo su -c « echo user_allow_other >> /etc/fuse.conf »

  5. You will be prompted to proceed. Type « Y » for yes and hit enter. This will take about 3 minutes on a broadband connection.*Note: This will 1. Automatically make the latest ifuse, aka « fusepod » application available for downlolad, 2. Download and install it, 3. Make it available for non-root users.
  6. Log out of the desktop by clicking the Ubuntu power button in the top Right corner of the desktop and clicking « Log out » (Optionally you may want to reboot).
    Note: Hugh only had success on an 8GB iPhone 3G running 3.1.2 after rebooting.
  7. Log back on to the desktop.
  8. Unlock and plug-in your iPod Touch / iPhone. You will be prompted several times to open the iPod. Click cancel.
  9. Open gnome-terminal through Applications –> Accessories –> Terminal
  10. Create the SysInfoExtended file on the iPod so that application such as RythmBox can use it by copy / paste the following into the console:

    sudo adduser « $USER » fuse; echo -e « \n\nPlease type the name of your ipod: »; read ipod_name; mkdir -p « $HOME/.gvfs/$ipod_name/iTunes_Control/Device/ »; ipod-read-sysinfo-extended `sudo lsusb -v | grep ‘iSerial’ | awk ‘length($0)>=68′ | awk ‘{print $3}’` « $HOME/.gvfs/$ipod_name/ »

  11. You will be prompted for the name of your iPod Touch / iPhone. This should match the name of the icon on your desktop.
    *Note: AJ suggests replacing all apostrophe’s in your iPod name with %27. Others suggest right click the desktop icon and copy the name from there. 

    Example:
    AJ’S IPOD
    replace with
    AJ%27S IPOD

    *Note: According to DFB, if you recieve error « can’t get debug descriptor: Connection timed out » check the iPod plugin in the RhythmBox plugins list.

  12. Log out and back into the desktop one last time.
  13. If MP3 support is desired, click this link to enable the « ubuntu-restricted-extras » packages (this can be done at any time).
  14. Launch RythmBox through Applications –> Sound and Video –> RythmBox. Your iPod should list on the left hand side. Drag files to and from as you would in iTunes.
    Note: Jon suggests using a Windows computer with iTunes to add at least one song to the iPhone via iTunes. This has helped some people create the necessary databases and files in the iPhone.
  15. If you have problems, try restarting your iPhone. If this does not help, please post a comment below.

Source : http://eric.cabrol.free.fr/unix.html#cut

Une petite compilation illustrée de
commandes Unix parfois utiles

uniq, tr, find, sort, csplit, cut, paste, join, patch

  • uniq : permet de supprimer des lignes identiques

Si l’on dispose d’un fichier fic qui ressemble à ceci :

AAAA
AAAA
BBBB
CCCC
CCCC
DDDD

la commande uniq fic renverra

AAAA
BBBB
CCCC
DDDD

Les lignes identiques doivent être adjacentes pour être supprimées.
L’option -u permet de n’afficher que les lignes présentes à l’origine en un seul exemplaire.
L’option -d permet de n’afficher que les lignes présentes initialement en plusieurs exemplaires.
Les options -f (resp. -s) permettent d’ignorer un certain nombre de champs (resp. de caractères) en début de chaque ligne avant d’entamer le processus de comparaison.

  • tr : transforme une liste de caractères en une autre.

Pour faire du Rot-13 sur un fichier in, par exemple :

tr [a-z] [n-za-m] < in > out

Pour convertir les majuscules en minuscules :

tr "[A-Z]" "[a-z]" < in > out

L’option  -d permet de supprimer la liste de caractères specifiée.

  • find

Permet de trouver des fichiers répondant à certains critères, et éventuellement d’effectuer certaines actions sur les fichiers répondant à la requête. Les critères peuvent se formuler en termes de nom (-name), de propriétaire (-user), de droits d’accès (-perm), de taille (-size), de nombre de liens (-links), de date d’accès/modification/changement (-atime, -mtime, -ctime

).

Par exemple, pour supprimer dans le répertoire courant les fichiers core ou ceux appartenant à l’utilisateur dilbert :

find . \( -name core -o -user dilbert \) -exec rm{}\;

Les parenthèses permettent de construire un critère « composé », l’option -o étant utilisée pour OR, le ! pour la négation, alors qu’une simple juxtaposition permet de traduire le AND.
D’autres exemples :
find . -mtime +3 # trouve les fichiers modifiés il y a plus de 3 jours
find . -newer fic # trouve les fichiers modifiés plus récemment que fic

  • sort

Permet d’effectuer un tri lexicographique (i.e selon l’ordre ASCII, ce qui signifie entre autres que la sequence « 12  » – notez l’espace – est considérée comme étant supérieure à 119), numérique (cf. option -n) ou chronologique (cf. option -M). Le séparateur de champs (l’espace, par défaut) peut etre modifié par l’option -t.
Si l’on veut trier un fichier fic sur la base du sixième champ, on tapera :

sort +5 fic

car les champs sont numérotés a partir de 0. Si l’on veut trier ce même fichier sur la base du huitième caractère du quatrième champ, la commande sera :

sort +3.7 fic

car les caractères à l’intérieur d’un champ sont également numérotés à partir de 0.

  • csplit

La commande csplit fic /regexp/+n permet d’éclater un fichier fic en plusieurs morceaux, la scission intervenant à la n-ième ligne après l’expression régulière passée en argument. Si l’argument n’est pas une regexp mais un numéro, csplit fonctionne comme split, et scinde le fichier en morceaux de n lignes.

  • cut

Permet d’extraire des parties de lignes d’un fichier. La commande cut -c1-5 fic extrait les 5 premiers caractères du fichier fic, alors que cut -f3,7 extrait les 3ème et 7ème champs (noter la différence entre la séparation par tiret et celle par virgule). Le séparateur par défaut est la tabulation, l’option -d permettant de le redéfinir.

  • paste

Cette commande permet de fusionner les lignes correspondantes de plusieurs fichiers. Ainsi, si le fichier fic1 contient
1
2
3
et que le fichier fic2 contient
4
5
6
la commande paste fic1 fic2 generera
1    4
2    5
3    6

L’entrée standard est passée en argument de paste par l’option tiret (-). Supposons que le répertoire courant ne contienne que trois fichiers fic1, fic2 et fic3. La commande ls fic? | paste - fic1 génèrera la sortie suivante :
fic1    1
fic2    2
fic3    3

    • join

Une fois encore, le plus simple est de prendre un exemple. Soit fic1 un fichier qui contient

Brésil 0
France 3

et fic2 un fichier qui contient

Brésil 1994
France 1998

La commande join -j1 1 fic1 fic2 genèrera

Brésil 0 1994
France 3 1998

L’option -j1 n permet de spécifier que c’est le n-ième champ de chacun des fichiers qui définit la relation.

mai

02

Posted by : admin | On : 2 mai 2010

tandis qu’un aspect est spécifié de façon autonome, implémentant un aspect technique particulier, par exemple la persistance ou encore la génération de trace.

Un ensemble de points d’insertions ou joinpoint en anglais sont ensuite définis pour établir la liaison entre l’aspect et le code métier ou un autre aspect.

* les points d’action (poincut), qui définissent les points de jonction satisfaisants aux conditions d’activation de l’aspect, donc le ou les moments où l’interaction va avoir lieu,
* les greffons c’est-à-dire les programmes (advice) qui seront activés avant, autour de ou après les points d’action défi

But d’un aspect est de factoriser au « maximum » des fonctionnalités transverses dans un projet informatique .

Exemple de fonctionnalité que l’on pourrait factorisées :

-Connexion et envoie de message JMS

-Sécurité

-Transactions

-Logger  etc …

Avantage :  (+)

-Uniformise le code dans un aspect

-pas de doublon, dans le code Java

Inconvenient (-) :

-Temps execution parfois lourd

Ecrire ses premiers AOP

Ecrire une fonction de log : transverse « à votre projet » :

Article

http://www.techfaq360.com/tutorial/spring/spring.jsp

http://code.google.com/p/arc-pocs/wiki/DIIntroTutorial

http://java.dzone.com/articles/introduction-spring-aop?page=0,0

http://java.dzone.com/articles/introduction-spring-aop

avr

24

Posted by : admin | On : 24 avril 2010

Preparation environnement J2EE

Telecharger
Maven2
Ant
Java
sun-java6-bin : Sun Java Runtime Environment (JRE) 6

=> sun-java6-demo : Sun Java Development Kit (JDK) 6 demos

=> sun-java6-jdk : Sun Java Development Kit (JDK) 6

=> sun-java6-jre : Sun Java Runtime Environment (JRE) 6
Voir ce site pour plus de détails :

export JAVA_HOME=/usr/lib/jvm/java-6-sun
export PATH=${JAVA_HOME}/bin:${PATH}

export ANT_HOME=/home/artaud/logiciels/apache-ant-1.8.1
export PATH=${ANT_HOME}/bin:${PATH}

export M2_HOME=/usr/local/apache-maven/
export M2=$M2_HOME/bin

export MAVEN_OPTS="-Xms512m -Xmx1024m"
export PATH=$M2:$PATH

Ecrire en japonais

Finalement j’y suis parvenu comme suit:

Dans Système->Administration->Prise en charge des langues, j’ai d’abord désinstallé le paquet de la langue japonaise, puis sélectionné le système de saisie au clavier ibus, puis réinstallé le paquet de la langue japonaise en cochant les trois cases « traductions », Méthodes de saisie » et « Polices supplémentaires ».
Redémarrage.
L’icone de ibus est apparue dans la zone de notification.
Click droit sur cet icone->préférences -> onglet méthode d’entrée -> Japonais -> Anthy->Ajouter

A partir de là dans une fenêtre de saisie (OpenOffice par exemple) CTL-Space pour activer désactiver. Les touches de basculement se déterminent dans l’onglet « Général » des préférences ibus.

references :

http://lejaponetmoi.blogspot.com/2009/11/ubuntu-910-et-le-japonais.html

http://forum.ubuntu-fr.org/viewtopic.php?id=352033

Source Liste

exemple :

 

echo "deb http://www.bashterritory.com/pytube/releases /" | sudo  tee -a /etc/apt/sources.list
 sudo aptitude install pytube

 

http://www.sourceslist.eu/notizie/sourceslist-table/

Nouveau depot Java Sun

Sous Lucid (Ubuntu 10.04), les paquets de sun-java 6 sont disponibles dans le dépôt partenaire qu’il faut activer pour pouvoir l’installer. Remarque : vous pouvez aussi utiliser l’alternative icedtea6

=> il suffit d’ajouter dans /etc/apt/sources.list ces deux liens

deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid partnerdeb-src http://archive.canonical.com/ubuntu lucid partner
sudo update-alternatives --config java

http://www.cyberciti.biz/faq/howto-ubuntu-linux-install-configure-jdk-jre/

Installer Avast Antivirus sur Amd64

apt-get install ia32-libs
 dpkg -i --force-architecture avast4workstation_1.0.8-2_i386.deb

Commande du quotidien

 

-Connaitre sa distribution :

lsb_release -c

-Installer un package

 sudo apt-get install --reinstall packagename

-Boucle de traitement :

for i in `ls`; do convert -resize 800x800 -quality 65 $i resized_$i; done

-Exemple de  PV Pipe Viewer:

tar -czf - . | pv > out.tgz
 tar -cf - . | pv  -s $(du -sb . | awk '{print $1}') | gzip > out.tgz

-Trouve tous les fichiers de format JPG ou jpg

 find . \( -name "*jpg" -o -name "*JPG" \) -type f

-Taille de tous les fichiers trouves :

find . \( -name "*jpg" -o -name "*JPG" \) -type f | du -sh

-Créer une Archive

tar -cvf toto.tar <Mes Fichiers>

-Tranfert SSH

ssh root@<ip_server> tar cf -toto | pv --wait > toto.ta

-Compter des fichiers

ls -l | wc -l

- Savoir quel est le user courant :

who am i | cut -f1 -d' '`

[/bash]

References :

http://www.smokinglinux.com/tutorials/howto-batch-image-resize-on-linux

http://doc.ubuntu-fr.org/imagemagick

Manuel

http://www.pixelbeat.org/cmdline.html

Find Command

 

find . -type f -name "*.php" -exec grep -il 'pattern' {} \;

find . -name "*.php" -print0 | xargs -0 egrep pattern

http://en.wikipedia.org/wiki/Find

Progress Bar and PV

http://www.korben.info/avoir-une-barre-de-progression-avec-la-commande-cp-sous-linux.html

http://www.ibm.com/developerworks/aix/library/au-spunix_pipeviewer/index.html

http://www.catonmat.net/blog/unix-utilities-pipe-viewer/

Autre

http://www.math.u-bordeaux1.fr/~foury/Info1/TP3/rappel.html

 #!/bin/sh
 cp_p()
 {
 set -e
 strace -q -ewrite cp -- "${1}" "${2}" 2>&1 \
 | awk '{
 count += $NF
 if (count % 10 == 0) {
 percent = count / total_size * 100
 printf "%3d%% [", percent
 for (i=0;i<=percent;i++)
 printf "="
 printf ">"
 for (i=percent;i<100;i++)
 printf " "
 printf "]\r"
 }
 }
 END { print "" }' total_size=$(stat -c '%s' "${1}") count=0
 }

Upgrade de votre distribution

http://planet.ubuntu-fr.org/

$sudo update-manager -c -d

Que faire quand Ubuntu plante ? via Hiko Seijûrô

Aucun système d'exploitation n'est parfait donc il arrive qu'Ubuntu plante. Mais heureusement, contrairement aux produits de Microsoft, on peut s'en sortir dans la plupart des cas avec Ubuntu (ou autres distributions Linux).

Tout est figé

Votre interface graphique est figé ? Seul la souris peut bouger ? N'éteignez pas brutalement votre ordinateur car il suffit de relancer l'environnement graphique. Pour cela il y a plusieurs solutions à essayer dans l'ordre suivant.
  1. On essaye un raccourci clavier bien utile : Alt + Impr écran + K [1] Cette combinaison de touches redémarre l'environnement graphique. Si vous avez une version d'Ubuntu inférieure à 9.04 (Jaunty Jackalope) il faut utiliser la combinaison Crtl + Alt + Backspace[2] devenue obsolète.
  2. Là on pas le choix il faut quitter cette interface graphique et se rendre dans un terminal. Pour cela il faut faire Ctrl + Alt + F1. On se retrouve alors dans le premier terminal[3] (tty1). On doit s'identifier donc tapez votre login et votre mot de passe. Puis entrez la commande suivante :
    sudo /etc/init.d/gdm restart

    Donnez votre mot de passe et patientez quelques secondes votre environnement graphique redémarre.

    GDM veut dire GNOME Display Manager et il est installé par défaut avec Ubuntu. Si vous utilisez un autre environnement graphique que GNOME remplacez gdm dans cette commande. Par exemple avec Kubuntu (environnement KDE) il faut remplacer par kdm.

  3. Si la commande précédente ne marche pas, ce qui m'est jamais arrivé, il faut redémarrer :
    sudo reboot

On doit sûrement pouvoir savoir pourquoi il y a eu un blocage en lisant les fichiers journaux (log) du système qui se situent dans le répertoire /var/log/. Mais je ne sais pas vraiment où trouver la bonne information. Je ne me suis pas vraiment penché sur le sujet.

http://www.pixelbeat.org/cmdline.html

mar

28

Posted by : admin | On : 28 mars 2010

REFERENCE DOCUMENTATION :

http://www.castor.org/reference/html-single/index.html#d0e18

http://www.castor.org/xml-mapping.html

http://www.castor.org/maven-integration.html

http://onjava.com/pub/a/onjava/2001/10/24/xmldatabind.html?page=2

To (un-)marshal data to and from XML, Castor XML can be used in one of three modes:

  • introspection mode
  • mapping mode
  • descriptor mode (aka generation mode)

Introspection Mode

Basicaly this mode is based on Java reflection to map the field in our Java Pojo classes and the XML .

Java reflection is a very powerful way to map that are located in the Java classes , however in many ways it can be versatile …

don’t forget to get in mind that java reflection is very costful in term of time treatement .

Classes to use :

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.XMLContext
  • In introspection mode , Castor XML uses Java reflection to establish the binding between the Java classes (and their properties) and the XML, following a set of (default) naming rules. Whilst it is possible to change to a different set of naming rules, there’s no way to override this (default) naming for individual artifacts. In such a case, a mapping file should be used.

mar

27

Posted by : admin | On : 27 mars 2010

First Spring roo Project

project --topLevelPackage com.springsource.pizzashop
persistence setup --provider HIBERNATE --database MYSQL
database properties set --key database.url --value jdbc:mysql://localhost:3306/pizza
database properties set --key database.username --value root
entity --class ~.domain.Topping --testAutomatically
field string --fieldName name --notNull --sizeMin 2
entity --class ~.domain.Base --testAutomatically
field string --fieldName name --notNull --sizeMin 2
entity --class ~.domain.Pizza --testAutomatically
field string --fieldName name --notNull --sizeMin 2
field number --type java.lang.Double --fieldName price --min 0 --primitive
field reference --type ~.domain.Base --fieldName base --notNull
field set --element ~.domain.Topping --fieldName toppings --cardinality MANY_TO_MANY
entity --class ~.domain.PizzaOrder –testAutomatically
field string --fieldName name --notNull --sizeMin 2
field string --fieldName address --sizeMax 50
field date --type java.util.Date --fieldName deliveryDate --class ~.domain.PizzaOrder
field set --element ~.domain.Pizza --fieldName pizzas --sizeMin 1
field number --type java.lang.Double --fieldName total --min 0 --primitive
controller all --package ~.web
logging setup --level DEBUG --package WEB
selenium test --controller com.springsource.pizzashop.web.BaseController
finder add --finderName findPizzasByToppingsAndPriceLessThan --class ~.domain.Pizza
security setup
controller scaffold --class ~.web.PublicPizzaController --path /public/pizza --disallowedOperations create,update,delete --entity
~.domain.Pizza
web flow

Introduction to Spring Roo

Introduction To Spring Roo 1.0.0 

View more presentations from Ben Alex.

Spring Roo 1.0.0 Technical Deep Dive

Spring Roo 1.0.0 Technical Deep Dive 

View more presentations from Ben Alex.
• Home → http://www.springsource.org/roo
– Contains links to all other resources
• Forum → http://forum.springsource.org
– Roo team actively monitor forum and answer queries
• Issues → http://jira.springframework.org/browse/ROO
• Twitter → #roo hash key 

mar

09

Posted by : admin | On : 9 mars 2010


 

In this article, we will walk through some of the capabilities provided by Spring batch Framework

 

Why use Spring Batch? Personally, when I sit down to work with batch, I get frustrated with the amount of code that you need to write to do simple things I/O, manage batches error cases  …

 

Spring batch let’s us use all capability of spring and provide powerful tool with few lines XML configuration.

 

Source :

 

You can checkout the source in Eclipse IDE using SVN here is the address of the source :

 

 

http://code.google.com/p/artaud/source/browse/#svn/springbatch

 

https://github.com/aartaud300/artaud

https://github.com/DoctusHartwald/artaud

In this article we’ll walk through these case :

 

-Case 1 : Hello World
-Case 2 : Import  CSV => Database
Case 3 : Export Database => flat file
-Case 4 : Export Database=> XML
-Case 5 : Couple Spring Batch and  Velocity template.
-Case 6 : export our database to a Jasper Report in PDF.

 

Technologies used :

 

I assume the reader to have good knowledge in basic Spring and Spring Annotations.

 

Spring

  1. Spring Annotation
  2. SpringBatch
  3. Spring OXM
  4. Spring Test

 

Related framework :

  1. Apache  Velocity
  2. Xstream /Stax  (for xml)
  3. Jasper

 

Database : MySQL

 

ENVIRONNEMENT

 

On windows :

 

JDK 5 or more
Apache Maven
MySQL or an other Database provider
Internet Connection

 

Eclipse

 

On Linux :

 

JDK 5 or more
Apache Maven
MySQL or an other Database provider
sudo apt-get  install apache2 mysql-server php5 php5-mysql phpmyadmin

 

Eclipse

 

APACHE MAVEN
In you ~/.bashrc add the following lines .

 

 

 

export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre
 export PATH=${PATH}:$JAVA_HOME/bin
 export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
 export M2=$M2_HOME/bin
 export MAVEN_OPTS="-Xms512m -Xmx1024m"
 export PATH=${PATH}:$M2
 export ROO_HOME=/home/<USER>/dev/spring-roo-1.0.2.RELEASE
 export ROO_OPTS="-Droo.bright=true"

 

RUN THE PROJET

SEE job.sh in in the folder documentation/ download the code source here.

Configuration of Maven2

First let’s see the pom.xml

 

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.batch</groupId>
 <artifactId>springbatch</artifactId>
 <name>SpringbatchDemo</name>
 <version>1.0</version>
 <packaging>jar</packaging>
 <description>Springbatch Sample Projet </description>
 <properties>
 <spring.version>2.5.6</spring.version>
 <!--<spring-batch.version>1.0.1.RELEASE</spring-batch.version>-->
 <spring-batch.version>2.1.0.RELEASE</spring-batch.version>
 <mysql-version>5.1.6</mysql-version>
 </properties>
 <dependencies>
 <!-- MySQL -->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>${mysql-version}</version>
 </dependency>
 <!-- SPRING -->
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jdbc</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.batch</groupId>
 <artifactId>spring-batch-core</artifactId>
 <version>${spring-batch.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aop</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-beans</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aspects</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jms</artifactId>
 <version>${spring.version}</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.ws</groupId>
 <artifactId>spring-oxm</artifactId>
 <version>1.5.5</version>
 <optional>true</optional>
 </dependency>
 <dependency>
 <groupId>org.springframework.osgi</groupId>
 <artifactId>spring-osgi-core</artifactId>
 <version>1.1.2</version>
 <optional>true</optional>
 </dependency>
 <!-- Log  -->
 <dependency>
 <groupId>commons-logging</groupId>
 <artifactId>commons-logging</artifactId>
 <version>1.1.1</version>
 </dependency>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.14</version>
 <optional>true</optional>
 </dependency>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.13</version>
 </dependency>
 <!-- Junit -->
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>org.springframework.test</artifactId>
 <version>2.5.6</version>
 <scope>test</scope>
 </dependency>
 <!-- Jasper report -->
 <dependency>
 <groupId>jasperreports</groupId>
 <artifactId>jasperreports</artifactId>
 <version>3.1.2</version>
 </dependency>
 <!-- XML STAX -->
 <dependency>
 <groupId>stax</groupId>
 <artifactId>stax</artifactId>
 <version>1.2.0</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.batch</groupId>
 <artifactId>spring-batch-test</artifactId>
 <version>${spring-batch.version}</version>
 </dependency>
 <dependency>
 <groupId>commons-lang</groupId>
 <artifactId>commons-lang</artifactId>
 <version>2.4</version>
 </dependency>
 <!-- Velocity -->
 <dependency>
 <groupId>org.apache.velocity</groupId>
 <artifactId>velocity</artifactId>
 <version>1.6.3</version>
 </dependency>
 <dependency>
 <groupId>org.apache.velocity</groupId>
 <artifactId>velocity-tools</artifactId>
 <version>1.3</version>
 </dependency>
 </dependencies>
 <distributionManagement>
 <repository>
 <id>spring-release</id>
 <name>Spring Release Repository</name>
 <url>s3://maven.springframework.org/release</url>
 </repository>
 <snapshotRepository>
 <id>spring-snapshot</id>
 <name>Spring Snapshot Repository</name>
 <url>s3://maven.springframework.org/snapshot</url>
 </snapshotRepository>
 </distributionManagement>
 <repositories>
 <repository>
 <id>objectstyle</id>
 <name>ObjectStyle.org Repository</name>
 <url>http://objectstyle.org/maven2</url>
 <snapshots>
 <enabled>false</enabled>
 </snapshots>
 </repository>
 <repository>
 <id>com.springsource.repository.bundles.release</id>
 <name>EBR Spring Release Repository</name>
 <url>http:// repository.springsource.com/maven/bundles/release</url>
 </repository>
 <repository>
 <id>com.springsource.repository.bundles.external</id>
 <name>EBR External Release Repository</name>
 <url>http:// repository.springsource.com/maven/bundles/external</url>
 </repository>
 <repository>
 <id>codehaus</id>
 <name>Maven Codehaus repository</name>
 <url>http://repository.codehaus.org/</url>
 </repository>
 </repositories>
 <pluginRepositories>
 <pluginRepository>
 <id>com.springsource.repository.bundles.milestone</id>
 <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Milestones</name>
 <url>http://repository.springsource.com/maven/bundles/milestone</url>
 <snapshots>
 <enabled>false</enabled>
 </snapshots>
 </pluginRepository>
 <pluginRepository>
 <id>com.springsource.repository.bundles.snapshot</id>
 <name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Snapshots</name>
 <url>http://repository.springsource.com/maven/bundles/snapshot</url>
 </pluginRepository>
 </pluginRepositories>
 <ciManagement>
 <system>Hudson</system>
 </ciManagement>

 <build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <configuration>
 <source>1.5</source>
 <target>1.5</target>
 </configuration>
 </plugin>
 <plugin>
 <artifactId>maven-surefire-plugin</artifactId>
 <version>2.4.3</version>
 <configuration>
 </configuration>
 </plugin>
 <!--
 Decomment this blog if you want to run it with
 -Dexec.mainClass="org.springframework.batch.core.launch.support.CommandLineJobRunner"
 -Dexec.args="com/batch/simpletask/simpletaskletcontext.xml
 simpleJob"
 -->
 <plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>exec-maven-plugin</artifactId>
 <executions>
 <execution>
 <id>glue-processing</id>
 <phase>install</phase>
 <goals>
 <goal>exec</goal>
 </goals>
 </execution>
 </executions>
 <configuration>
 <debug>true</debug>
 <executable>java</executable>
 <mainClass>app_example2.Example2</mainClass>
 <!--
 <mainClass>org.springframework.batch.core.launch.support.CommandLineJobRunner</mainClass>
 <arguments>
 <argument>com/batch/simpletask/simpletaskletcontext.xml</argument>
 <argument>simpleJob</argument> </arguments>
 -->
 </configuration>
 </plugin>
 </plugins>
 </build>
 </project>

 

 

We’ll use Spring annotation couple with standard Spring to realize our sample project

create a package src/main/java/com.batch

these 2  class AppJobExecutionListener and ItemFailureLoggerListener let us log the job execution.

 

 
 package com.batch;
 import org.apache.log4j.Logger;
 import org.springframework.batch.core.BatchStatus;
 import org.springframework.batch.core.JobExecution;
 import org.springframework.batch.core.JobExecutionListener;
 import org.springframework.stereotype.Component;
 @Component("appJobExecutionListener")
 public class AppJobExecutionListener implements JobExecutionListener {
 private final static Logger logger = Logger
 .getLogger(AppJobExecutionListener.class);
 public void afterJob(JobExecution jobExecution) {
 if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
 logger.info("Job completed: " + jobExecution.getJobId());
 } else if (jobExecution.getStatus() == BatchStatus.FAILED) {
 logger.info("Job failed: " + jobExecution.getJobId());
 }
 }
 public void beforeJob(JobExecution jobExecution) {
 if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
 logger.info("Job completed: " + jobExecution.getJobId());
 } else if (jobExecution.getStatus() == BatchStatus.FAILED) {
 logger.info("Job failed: " + jobExecution.getJobId());
 }
 }
 }
 package com.batch;
 import org.apache.log4j.Logger;
 import org.springframework.batch.core.listener.ItemListenerSupport;
 import org.springframework.stereotype.Component;
 @Component("itemFailureLoggerListener")
 public class ItemFailureLoggerListener extends ItemListenerSupport {
 private final static Logger logger = Logger
 .getLogger(ItemFailureLoggerListener.class);
 public void onReadError(Exception ex) {
 logger.error("Encountered error on read", ex);
 }
 public void onWriteError(Exception ex, Object item) {
 logger.error("Encountered error on write", ex);
 }
 }

 

 

First example in Spring Batch

HelloWorld in Spring Batch

Create a package name com.batch.simpletask under src/main/java

 

 

package com.batch.simpletask;
 import org.springframework.batch.core.StepContribution;
 import org.springframework.batch.core.scope.context.ChunkContext;
 import org.springframework.batch.core.step.tasklet.Tasklet;
 import org.springframework.batch.repeat.RepeatStatus;
 public class HelloTask implements Tasklet {
 private String taskStartMessage;
 public void setTaskStartMessage(String taskStartMessage) {
 this.taskStartMessage = taskStartMessage;
 }
 public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
 throws Exception {
 System.out.println(taskStartMessage);
 return RepeatStatus.FINISHED;
 }
 }

 

 

package com.batch.simpletask;
 import java.util.Calendar;
 import org.springframework.batch.core.StepContribution;
 import org.springframework.batch.core.scope.context.ChunkContext;
 import org.springframework.batch.core.step.tasklet.Tasklet;
 import org.springframework.batch.repeat.RepeatStatus;
 public class TimeTask implements Tasklet {
 public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
 throws Exception {
 System.out.println(Calendar.getInstance().getTime());
 return RepeatStatus.FINISHED;
 }
 }

 

 

Spring Configuration

 

 
 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:batch="http://www.springframework.org/schema/batch"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
 http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 <!-- 1) USE ANNOTATIONS TO IDENTIFY AND WIRE SPRING BEANS. -->
 <!-- We indicate to Spring that we scan @Component annotation based on package com.batch -->
 <context:component-scan base-package="com.batch" />
 <bean id="transactionManager"
 class="org.springframework.batch.support.transaction.ResourcelessTransactionManager">
 </bean>
 <!-- 3) JOB REPOSITORY - WE USE IN-MEMORY REPOSITORY FOR OUR EXAMPLE -->
 <bean id="jobRepository"
 class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
 <property name="transactionManager" ref="transactionManager" />
 </bean>
 <!-- 4) LAUNCH JOBS FROM A REPOSITORY -->
 <bean id="jobLauncher"
 class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
 <property name="jobRepository" ref="jobRepository" />
 </bean>
 <!-- 5) Beans representing the 2 job steps. -->
 <!-- Step1 - print hello world -->
 <bean id="helloTask">
 <property name="taskStartMessage" value="Hello World - the time is now " />
 </bean>
 <!-- Step2 - print current time -->
 <bean id="timeTask" />
 <!-- 6) FINALLY OUR JOB DEFINITION. THIS IS A 2 STEP JOB -->
 <batch:job id="simpleJob">
 <batch:listeners>
 <batch:listener ref="appJobExecutionListener" />
 </batch:listeners>
 <batch:step id="step1" next="step2">
 <batch:tasklet ref="helloTask" />
 </batch:step>
 <batch:step id="step2">
 <batch:tasklet ref="timeTask" />
 </batch:step>
 </batch:job>
 </beans>

 

 

Test our Case 1 :

 

 package com.batch.simpletask;
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.springframework.batch.core.Job;
 import org.springframework.batch.core.JobParameters;
 import org.springframework.batch.core.launch.JobLauncher;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 import org.springframework.util.StopWatch;
 @ContextConfiguration(locations = "classpath*:com/batch/simpletask/simpletaskletcontext.xml")
 @RunWith(SpringJUnit4ClassRunner.class)
 public class SimpleTaskletTestCase extends
 AbstractDependencyInjectionSpringContextTests {
 private final static Logger logger = Logger
 .getLogger(SimpleTaskletTestCase.class);
 @Autowired
 private JobLauncher launcher;
 @Autowired
 private Job job;
 private JobParameters jobParameters = new JobParameters();
 @Before
 public void setup() {
 //PropertyConfigurator.configure("C:/Users/admin/workspace-test/springbatch2/src/com/batch/log4j.properties");
 }
 @Test
 public void testLaunchJob() throws Exception {
 StopWatch sw = new StopWatch();
 sw.start();
 launcher.run(job, jobParameters);
 sw.stop();
 logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
 }
 @Autowired
 public void setLauncher(JobLauncher bootstrap) {
 this.launcher = bootstrap;
 }
 @Autowired
 public void setJob(Job job) {
 this.job = job;
 }
 }

 

 

Install a LAMP server

  • on Linux :

 

sudo apt-get isntall apache2 mysql-server php5 php5-mysql phpmyadmin

 

Check that the process are running

 

 

sudo /etc/init.d/apache2 start
 sudo /etc/init.d/mysql restart

 

  • on Window

Download EasyPHP or Xampp and launch the application

Connect to MySQL

Connect to MySql whether by prompt or via Phpmyadmin http://localhost/phpmyadmin

Create a new user

  • via phpmyadmin

Enter login : test / password testand tick the right rules on the database as the following screenshot

Via prompt :

 

sudo mysql -u root -p

 

CREATE USER 'test'@'%' IDENTIFIED  BY  '***';
 GRANT  SELECT ,
 INSERT ,
 UPDATE ,
 DELETE ,
 CREATE ,
 DROP ,
 FILE ,
 INDEX ,
 ALTER ,
 CREATE  TEMPORARY  TABLES ,
 CREATE  VIEW ,
 EVENT,
 TRIGGER,
 SHOW  VIEW ,
 CREATE ROUTINE,
 ALTER ROUTINE,
 EXECUTE  ON  *  .  *  TO  'test'@'%' IDENTIFIED  BY  '***' WITH  MAX_QUERIES_PER_HOUR 0  MAX_CONNECTIONS_PER_HOUR 0  MAX_UPDATES_PER_HOUR 0  MAX_USER_CONNECTIONS 0 ;

 

 

Create a Database

  • create a new database name seamdb
 CREATE  DATABASE  `seamdb` ;

Create a new Table

[sql]

create table ledger (

ID INT NOT NULL AUTO_INCREMENT,

rcv_dt date,

mbr_nm VARCHAR(100) not null,

chk_nbr VARCHAR(10) not null,

chk_dt date,

pymt_typ VARCHAR(50) not null,

dpst_amt double,

pymt_amt double,

comments VARCHAR(100),

PRIMARY KEY (ID)

);

[/sql]

Example 2: CSV to Database

create a new package com.batch.todb in /src/main/java

Create a Model Bean call Ledger

 

package com.batch.todb;

import java.util.Date;

public class Ledger {

private int id;

private Date receiptDate;

private String memberName;

private String checkNumber;

private Date checkDate;

private String paymentType;

private double depositAmount;

private double paymentAmount;

private String comments;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public Date getReceiptDate() {

return receiptDate;

}

public void setReceiptDate(Date receiptDate) {

this.receiptDate = receiptDate;

}

public String getMemberName() {

return memberName;

}

public void setMemberName(String memberName) {

this.memberName = memberName;

}

public String getCheckNumber() {

return checkNumber;

}

public void setCheckNumber(String checkNumber) {

this.checkNumber = checkNumber;

}

public Date getCheckDate() {

return checkDate;

}

public void setCheckDate(Date checkDate) {

this.checkDate = checkDate;

}

public String getPaymentType() {

return paymentType;

}

public void setPaymentType(String paymentType) {

this.paymentType = paymentType;

}

public double getDepositAmount() {

return depositAmount;

}

public void setDepositAmount(double depositAmount) {

this.depositAmount = depositAmount;

}

public double getPaymentAmount() {

return paymentAmount;

}

public void setPaymentAmount(double paymentAmount) {

this.paymentAmount = paymentAmount;

}

public String getComments() {

return comments;

}

public void setComments(String comments) {

this.comments = comments;

}

}

package com.batch.todb;

public interface LedgerDAO {

public void save(final Ledger note);

}

package com.batch.todb;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.PreparedStatementSetter;

import org.springframework.stereotype.Component;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

@Component

public class LedgerDAOImpl extends JdbcTemplate implements LedgerDAO {

@Autowired

public void setDataSource(DataSource dataSource) {

super.setDataSource(dataSource);

}

@Transactional(propagation = Propagation.REQUIRED)

public void save(final Ledger item) {

super

.update(

« insert into ledger (rcv_dt, mbr_nm, chk_nbr, chk_dt, pymt_typ, dpst_amt, pymt_amt, comments) values(?,?,?,?,?,?,?,?) »,

new PreparedStatementSetter() {

public void setValues(PreparedStatement stmt)

throws SQLException {

stmt.setDate(1, new java.sql.Date(item

.getReceiptDate().getTime()));

stmt.setString(2, item.getMemberName());

stmt.setString(3, item.getCheckNumber());

stmt.setDate(4, new java.sql.Date(item

.getCheckDate().getTime()));

stmt.setString(5, item.getPaymentType());

stmt.setDouble(6, item.getDepositAmount());

stmt.setDouble(7, item.getPaymentAmount());

stmt.setString(8, item.getComments());

}

});

}

}

package com.batch.todb;

import java.text.DecimalFormat;

import java.text.ParseException;

import org.springframework.batch.item.file.mapping.FieldSetMapper;

import org.springframework.batch.item.file.transform.FieldSet;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Service;

@Component(« ledgerMapper »)

public class LedgerMapper implements FieldSetMapper {

private final static String DATE_PATTERN = « mm/DD/yy »;

private final static String DOLLAR_PATTERN = « $###,###.### »;

public Object mapFieldSet(FieldSet fs) {

Ledger item = new Ledger();

int idx = 0;

item.setReceiptDate(fs.readDate(idx++, DATE_PATTERN));

item.setMemberName(fs.readString(idx++));

item.setCheckNumber(fs.readString(idx++));

item.setCheckDate(fs.readDate(idx++, DATE_PATTERN));

item.setPaymentType(fs.readString(idx++));

// deposit amount

try {

DecimalFormat fmttr = new DecimalFormat(DOLLAR_PATTERN);

Number number = fmttr.parse(fs.readString(idx++));

item.setDepositAmount(number.doubleValue());

} catch (ParseException e) {

item.setDepositAmount(0);

}

// payment amount

try {

DecimalFormat fmttr = new DecimalFormat(DOLLAR_PATTERN);

Number number = fmttr.parse(fs.readString(idx++));

item.setPaymentAmount(number.doubleValue());

} catch (ParseException e) {

item.setPaymentAmount(0);

}

//

return item;

}

}

package com.batch.todb;

import java.util.Iterator;

import java.util.List;

import org.springframework.batch.item.ItemWriter;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component(« itemWriter »)

public class LedgerWriter implements ItemWriter {

@Autowired

private LedgerDAO itemDAO;

public void write(List items) throws Exception {

for (Iterator<Ledger> iterator = items.iterator(); iterator.hasNext();) {

Ledger item = iterator.next();

itemDAO.save(item);

}

}

}

Launch Junit Test

In src/test/java create this class of Test

We’ll launch our test using Spring Test framework by using these annotations :

[java]

<pre>@ContextConfiguration(locations = « classpath:com/batch/todb/contextToDB.xml »)

@RunWith(SpringJUnit4ClassRunner.class)

@TransactionConfiguration(transactionManager = « transactionManager », defaultRollback = false)</pre>

[/java]

[java]

package com.batch.todb;

import org.apache.log4j.Logger;

import org.apache.log4j.PropertyConfigurator;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.batch.core.Job;

import org.springframework.batch.core.JobParameters;

import org.springframework.batch.core.launch.JobLauncher;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.test.context.transaction.TransactionConfiguration;

import org.springframework.util.StopWatch;

@ContextConfiguration(locations = « classpath:com/batch/todb/contextToDB.xml »)

@RunWith(SpringJUnit4ClassRunner.class)

@TransactionConfiguration(transactionManager = « transactionManager », defaultRollback = false)

public class ToDBBatchTestCase extends

AbstractTransactionalJUnit4SpringContextTests {

private final static Logger logger = Logger.getLogger(ToDBBatchTestCase.class);

@Autowired

private JobLauncher launcher;

@Autowired

private Job job;

private JobParameters jobParameters = new JobParameters();

@Before

public void setup() {

//PropertyConfigurator.configure(« C:/Users/admin/workspace-test/springbatch2/src/com/batch/log4j.properties »);

}

@Test

public void testLaunchJob() throws Exception {

StopWatch sw = new StopWatch();

sw.start();

launcher.run(job, jobParameters);

sw.stop();

logger.info(« >>> TIME ELAPSED: » + sw.shortSummary());

}

@Autowired

public void setLauncher(JobLauncher bootstrap) {

this.launcher = bootstrap;

}

@Autowired

public void setJob(Job job) {

this.job = job;

}

}

[/java]

Case 3 : Export Database => flat file

Case 4 : Export Database=> XML

Case 5 : Couple Spring Batch and  Velocity template.

the source are locate into com/batch/velocity

The apache Velocity framework is issue from Jakarta project and is a powerful tool for generating SQL code,Java class C++ , whatever ..

Aim :

In this study case I propose to see how with Spring batch we can couple the two framework together.

We could also use different implementation of  ItemProcessor<T,V> between the ItemReader<T> and ItemWriter<T>  provided by Spring batch , but in this study case it’s not the purpose.

The purpose it to respond fast to our need , generate a bunch of file according to a pattern file .

For instance , you want to generate « a large and complex bouchon class » or « the same SQL code a number of time «   .

The problem is that in a project time is precious so you don’t want to waste it by doing long and repetitif task . I think you grab I want to say ;)

in this sample I start from CSV file and want to replace two variable $name and $ project using this file pattern (the .vm file in Apache Velocity)

Raw input that I have

-Input :

Apache Velocity,Jakarta

Spring batch,Spring source

Spring Roo,Spring Source

-Output expected by the client :

Hello from $name in the $project project.

Spring configuration

What we need is to configure a of a velocityEngine and ItemReader to read our CSV .

Configuration of Velocity Engine

[xml]

<bean id= »velocityEngine »

>

<property name= »velocityProperties »>

<value>

resource.loader=class

class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

</value>

</property>

</bean>

[/xml]

Configuration of the ItemReader

[xml]

<bean id= »itemReader »>

<property name= »resource » value= »classpath:com/batch/velocity/project.txt » />

<!– property name= »linesToSkip » value= »1″ /–>

<property name= »lineMapper »>

<bean>

<property name= »lineTokenizer »>

<bean

class= »org.springframework.batch.item.file.transform.DelimitedLineTokenizer »>

<property name= »names » value= »name,project » />

</bean>

</property>

<property name= »fieldSetMapper » ref= »projectMapper » />

</bean>

</property>

</bean>

[/xml]

Full spring configuration

[xml]

<?xml version= »1.0″ encoding= »UTF-8″?>

<beans xmlns= »http://www.springframework.org/schema/beans »

xmlns:xsi= »http://www.w3.org/2001/XMLSchema-instance » xmlns:p= »http://www.springframework.org/schema/p »

xmlns:aop= »http://www.springframework.org/schema/aop » xmlns:tx= »http://www.springframework.org/schema/tx »

xmlns:batch= »http://www.springframework.org/schema/batch »

xmlns:context= »http://www.springframework.org/schema/context »

xmlns:jms= »http://www.springframework.org/schema/jms » xmlns:amq= »http://activemq.apache.org/schema/core »

xmlns:util= »http://www.springframework.org/schema/util »

xsi:schemaLocation= »http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/jms

http://www.springframework.org/schema/jms/spring-jms.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

« >

<!– 1) USE ANNOTATIONS TO CONFIGURE SPRING BEANS –>

<context:component-scan base-package= »com.batch.velocity » />

<!– Author Artaud Antoine  –>

<bean id= »velocityEngine »

class= »org.springframework.ui.velocity.VelocityEngineFactoryBean »>

<property name= »velocityProperties »>

<value>

resource.loader=class

class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

</value>

</property>

</bean>

<bean id= »itemReader »>

<property name= »resource » value= »classpath:com/batch/velocity/project.txt » />

<!– property name= »linesToSkip » value= »1″ /–>

<property name= »lineMapper »>

<bean>

<property name= »lineTokenizer »>

<bean

class= »org.springframework.batch.item.file.transform.DelimitedLineTokenizer »>

<property name= »names » value= »name,project » />

</bean>

</property>

<property name= »fieldSetMapper » ref= »projectMapper » />

</bean>

</property>

</bean>

</beans>

[/xml]

Case 6 : export our database to a Jasper Report in PDF.

Case 7 : Couple Spring Batch and  Velocity template + treatement

-Aim : use the 2 framework together and add some basic treatement on data you receive from a CSV file for instance

The configuration XML is the same as previously.

- the only difference reside in the vm template (VTL) that we write in Apache Velocity template .

[xml]

<?xml version= »1.0″ encoding= »UTF-8″?>

<beans xmlns= »http://www.springframework.org/schema/beans »

xmlns:xsi= »http://www.w3.org/2001/XMLSchema-instance » xmlns:p= »http://www.springframework.org/schema/p »

xmlns:aop= »http://www.springframework.org/schema/aop » xmlns:tx= »http://www.springframework.org/schema/tx »

xmlns:batch= »http://www.springframework.org/schema/batch »

xmlns:context= »http://www.springframework.org/schema/context »

xmlns:jms= »http://www.springframework.org/schema/jms » xmlns:amq= »http://activemq.apache.org/schema/core »

xmlns:util= »http://www.springframework.org/schema/util »

xsi:schemaLocation= »http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/jms

http://www.springframework.org/schema/jms/spring-jms.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

« >

<!– 1) USE ANNOTATIONS TO CONFIGURE SPRING BEANS –>

<context:component-scan base-package= »com.batch.velocity.genClass » />

<!– Author Artaud Antoine  –>

<bean id= »velocityEngine »

class= »org.springframework.ui.velocity.VelocityEngineFactoryBean »>

<property name= »velocityProperties »>

<value>

resource.loader=cla

ss

class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

</value>

</property>

</bean>

<bean id= »itemReader »>

<property name= »resource » value= »classpath:com/batch/velocity/genClass/dataTest.csv » />

<!– property name= »linesToSkip » value= »1″ /–>

<property name= »lineMapper »>

<bean>

<property name= »lineTokenizer »>

<bean>

<!–<property name= »delimiter » value= »MonDel »/> –>

<property name= »names » value= »champ1,data1Type,documentation1,champ2,data2Type,documentation2″ />

</bean>

</property>

<property name= »fieldSetMapper » ref= »genMapperFactoryMapper » />

</bean>

</property>

</bean>

</beans>

[/xml]

Apache Velocity template

what interest us is the bold part of the bellow code .It indicate to apache Velocity that you call this custom metod treatement on the data you furnish on the « pipe ».

SEE the it /src/test/ressources/com/batch/velocity/genClass/example2.vm

[bash]

/**

*

*/

public class $name {

#foreach( $element in $mylist )

private  $element.Data1Type   $element.champ1;

/**

*

* Map : $element.champ1,$element.data1Type,$element.documentation1

* To : $element.champ2,$element.data2Type,$element.documentation2

* $element.documentation1

* @return the $element.champ1

*

*/

public $element.data1Type <strong>get${utility.getInputU($element.champ1)}</strong>() {

return  $element.champ1;

}

/**

* Map : $element.champ1,$element.data1Type,$element.documentation1

* To : $element.champ2,$element.data2Type,$element.documentation2

* $element.documentation1

* @param $element.champ1 the $element.champ1 to set

* #set( $setter = « set » )

*/

public void  <strong>set${utility.getInputU($element.champ1)}</strong>($element.data1Type $element.champ1) {

this.$element.champ1 = $element.champ1;

}

#end

}

[/bash]

Bellow the Java code that is being called by Apache Velocity

[java]

public class GeneratorUtility {

/**

* set$utility.firstToUpperCase($att.Name)

* @param input the input to set

*/

public String  <strong>getInput</strong>U(String pInput) {

pInput.split(« _ »);

return StringUtils.capitalizeFirstLetter(pInput);

}

}

[/java]

Junit Test

[java]

@ContextConfiguration(locations = « classpath:com/batch/velocity/genClass/contextVelocity.xml »)

@RunWith(SpringJUnit4ClassRunner.class)

public class VelocityCodeTemplateGenClassGenerator {

@Autowired

private VelocityEngine velocityEngine;

@Autowired

private FlatFileItemReader vFlatFileItemReader;

@Test

public void testFlatReaderItemToVelocityProcessor(){

System.out.println(« [INFO] ———————————————————————————- »);

System.out.println(« [INFO] Running test : testFlatReaderItemToVelocityProcessor / « + getClass().getName());

System.out.println(« [INFO] ———————————————————————————- »);

vFlatFileItemReader.open(new ExecutionContext());

boolean hasNext = true ;

GenMapperFactory  vGenMapperFactory = null;

GeneratorUtility vUtility = new GeneratorUtility();

List<GenMapperFactory> vGenMapperFactoryList = new ArrayList<GenMapperFactory>();

//vMyClasseGen.setGenMapperFactory(new ArrayList<GenMapperFactory>());

while (hasNext) {

try {

vGenMapperFactory = (GenMapperFactory) vFlatFileItemReader.read();

vGenMapperFactoryList.add(vGenMapperFactory);

} catch (UnexpectedInputException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

if (vGenMapperFactory == null) {

hasNext = false;

}

else {

Map model = new HashMap();

model.put(« utility », vUtility);

model.put(« mylist », vGenMapperFactoryList);

model.put(« name », « ClassDeTest »);

String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, « com/batch/velocity/genClass/example2.vm », model);

System.out.println( » « +text);

System.out.println(vGenMapperFactory.toString());

}

}

}

}

[/java]

mar

07

Posted by : admin | On : 7 mars 2010

Clam AntiVirus (ClamAV) is a free, cross-platform antivirus software tool-kit capable of detecting many types of malicious software, including viruses. One of its main uses is on mail servers as a server-side email virus scanner. The application was developed for Unix and has third party versions available for AIX, BSD, HP-UX, Linux, Mac OS X, OpenVMS, OSF and Solaris

Edit /etc/apt/sources.list

deb http://ppa.launchpad.net/ubuntu-clamav/ppa/ubuntu jaunty main

sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 0xf80220d0e695a455e651ac4d8ab767895adc2037
wget -q http://www.debian.org/volatile/etch-volatile.asc -O- | sudo apt-key add -
sudo apt-get update
sudo apt-get install clamav-freshclam

Mise a jour de lantivirus

freshclam

Lancer un scan des fichiers :

clamscan -r /home/utilisateur