mardi 7 décembre 2010

unix / linux : éditer la ligne d'une commande en mode console

il suffit d’utiliser les mêmes commandes que sous VI :

find . -name '*.sh' -exec grep -v 'test'

Si je souhaite revenir, et éditer la ligne il suffit de faire :

Escape+H : pour aller à guache
Escape+L : pour aller à droite
Escape+x : pour supprimer
etc ..

oracle : retrouver facilement une colonne d'un type"donné" ou d'un nom donné

Voici une requête simple permettant de retrouver des colonnes d'un type données, exemple, la recherche de toutes les tables contenant des CLOB


select * from user_tab_columns where data_type like '%CLOB%'




select * from user_tab_columns where column_name like '%ILR%'

jeudi 2 décembre 2010

oracle : in avec plusieurs champs

Il peut -être utile de faire des requêtes avec des in et avec plusieurs champs :

Voici un exemple de requêtes qui prend dans le IN les champs id_composant et id_versi_composant.

Attention à ne pas oublier les parenthèses :


select * from TBOT_VERSTARIF_VERSCOMP where (id_composant,id_versi_composant) in
(select id_composant,id_versi_composant from TBOTVERS_COMPOSANT where id_composant in (select id_composant from TBOTCOMPOSANT where type_composant in ('2')) and dh_prod >= TO_DATE('01/01/2009','DD/MM/YYYY'))

java : jvm utiliser JConsole ou Java Visual Viewer

Pour des JVM 1.5 ou plus, il est possible de monitorer la JVM :
- CPU
- thread dump
- mémoire (heap, permGen, etc plus eden, etc ...)

Pour cela il faut configurer le JMX :

Voici, un exemple simple :

-Dcom.sun.management.jmxremote.port=7001 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false

Ensuite configurer la Java VM :

- Ajouter la configuration et faire un remote debug

java : JVM et log du "garbage collector"

Voici, pour rappel les options à utiliser pour logger l'activité du "garbage collector"

-Xloggc:/var/run/log/java.loggc-monAppli-app.txt.20101130.142937 -XX:+PrintGCTimeStamps -XX:+PrintGCDetails


A noter qu'il existe une appli super pour les visulaiser (GCViewer)

GCViewer

Le télécharger à

java : rappel sur les options PermGen et Heap

Il peut parfois arriver d'avoir des erreurs de type OutOfMemory : Perm Gen Space ...

Le Head contient les instances en cours, et est "Garbage Collectée". En cas d'OutOfMemory, la taille peut-être simplement modifié via les optionq de JVM suivantes :

-Xms512m
-Xmx1400m


Un moyen simple pour régler ce problème est d'utilser des options non standard (<=> -X: ou -XX: mais présente sur les JVM Sun) et d'augmenter les tailles du permGen:


-XX:PermSize=128M
-XX:MaxPermSize=256M


Qu'est ce que cela signifie ?

Si je regarde la consommation de mon programme ... je m'aperçoit que le HEAP ne consomme que 5% de la mémoire !!! or j'ai un OutOfMemory.

Ce qu'il faut comprendre c'est que le PermGen est la zone mémoire ou sont stockés les classes chargées, les méthodes, les Strings, les annotations, et les membres static !!! Et surtout, contrairement au Heap, elle ne sont pas "Garbage Collecté". Du coup, cette mémoire ne peut qu'augmenter !!:

Du coup, si un membre "static" est un singleton , qui a un rôle de cache par exemple, ce dernier peut-être très gourmand et conduire à ce genre d'erreur. De plus, lors de la compilation de JSP, ces dernières sont compilées et transformées en servlet, et donc chargée dans le "PermGen".

De plus, il est à noter qu'à chaque modification d'une méthode ou d'une classe, cette dernière est de nouveau chargée en "PermGen".

Ceci peut donc être catastrophique,lorsque l'on utilise des librairies qui modifient les classes comme par exemple :
- les librairies d'instrumentation de code
- ou qui de programmation par aspect ... (Spring, bcel, cglib, asm, etc...)

Lors de ce genre de problème, il faut tout de même se poser la question, de savoir si cette augmentation de la taille de la mémoire est justifiée (ex: singleton de chargement d'un référentiel) , ou si elle provient d'un problème plus profond de conception.

java : rappel sur les paramètres de la JVM

tout est sur le site d'oracle

Ou cet autre très bon lien :
ou sur le blog de SUN

Rappel des options


Behavioral Options

Option and Default Value Description
-XX:-AllowUserSignalHandlers Do not complain if the application installs signal handlers. (Relevant to Solaris and Linux only.)
-XX:AltStackSize=16384 Alternate signal stack size (in Kbytes). (Relevant to Solaris only, removed from 5.0.)
-XX:-DisableExplicitGC Disable calls to System.gc(), JVM still performs garbage collection when necessary.
-XX:+FailOverToOldVerifier Fail over to old verifier when the new type checker fails. (Introduced in 6.)
-XX:+HandlePromotionFailure The youngest generation collection does not require a guarantee of full promotion of all live objects. (Introduced in 1.4.2 update 11) [5.0 and earlier: false.]
-XX:+MaxFDLimit Bump the number of file descriptors to max. (Relevant to Solaris only.)
-XX:PreBlockSpin=10 Spin count variable for use with -XX:+UseSpinning. Controls the maximum spin iterations allowed before entering operating system thread synchronization code. (Introduced in 1.4.2.)
-XX:-RelaxAccessControlCheck Relax the access control checks in the verifier. (Introduced in 6.)
-XX:+ScavengeBeforeFullGC Do young generation GC prior to a full GC. (Introduced in 1.4.1.)
-XX:+UseAltSigs Use alternate signals instead of SIGUSR1 and SIGUSR2 for VM internal signals. (Introduced in 1.3.1 update 9, 1.4.1. Relevant to Solaris only.)
-XX:+UseBoundThreads Bind user level threads to kernel threads. (Relevant to Solaris only.)
-XX:-UseConcMarkSweepGC Use concurrent mark-sweep collection for the old generation. (Introduced in 1.4.1)
-XX:+UseGCOverheadLimit Use a policy that limits the proportion of the VM's time that is spent in GC before an OutOfMemory error is thrown. (Introduced in 6.)
-XX:+UseLWPSynchronization Use LWP-based instead of thread based synchronization. (Introduced in 1.4.0. Relevant to Solaris only.)
-XX:-UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1)
-XX:-UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.)
-XX:-UseSerialGC Use serial garbage collection. (Introduced in 5.0.)
-XX:-UseSpinning Enable naive spinning on Java monitor before entering operating system thread synchronizaton code. (Relevant to 1.4.2 and 5.0 only.) [1.4.2, multi-processor Windows platforms: true]
-XX:+UseTLAB Use thread-local object allocation (Introduced in 1.4.0, known as UseTLE prior to that.) [1.4.2 and earlier, x86 or with -client: false]
-XX:+UseSplitVerifier Use the new type checker with StackMapTable attributes. (Introduced in 5.0.)[5.0: false]
-XX:+UseThreadPriorities Use native thread priorities.
-XX:+UseVMInterruptibleIO Thread interrupt before or with EINTR for I/O operations results in OS_INTRPT. (Introduced in 6. Relevant to Solaris only.)
Back to Options

Performance Options

Option and Default Value Description
-XX:+AggressiveOpts Turn on point performance compiler optimizations that are expected to be default in upcoming releases. (Introduced in 5.0 update 6.)
-XX:CompileThreshold=10000 Number of method invocations/branches before compiling [-client: 1,500]
-XX:LargePageSizeInBytes=4m Sets the large page size used for the Java heap. (Introduced in 1.4.0 update 1.) [amd64: 2m.]
-XX:MaxHeapFreeRatio=70 Maximum percentage of heap free after GC to avoid shrinking.
-XX:MaxNewSize=size Maximum size of new generation (in bytes). Since 1.4, MaxNewSize is computed as a function of NewRatio. [1.3.1 Sparc: 32m; 1.3.1 x86: 2.5m.]
-XX:MaxPermSize=64m Size of the Permanent Generation. [5.0 and newer: 64 bit VMs are scaled 30% larger; 1.4 amd64: 96m; 1.3.1 -client: 32m.]
-XX:MinHeapFreeRatio=40 Minimum percentage of heap free after GC to avoid expansion.
-XX:NewRatio=2 Ratio of new/old generation sizes. [Sparc -client: 8; x86 -server: 8; x86 -client: 12.]-client: 4 (1.3) 8 (1.3.1+), x86: 12]
-XX:NewSize=2.125m Default size of new generation (in bytes) [5.0 and newer: 64 bit VMs are scaled 30% larger; x86: 1m; x86, 5.0 and older: 640k]
-XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 48m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.]
-XX:SurvivorRatio=8 Ratio of eden/survivor space size [Solaris amd64: 6; Sparc in 1.3.1: 25; other Solaris platforms in 5.0 and earlier: 32]
-XX:TargetSurvivorRatio=50 Desired percentage of survivor space used after scavenge.
-XX:ThreadStackSize=512 Thread Stack Size (in Kbytes). (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]
-XX:+UseBiasedLocking Enable biased locking. For more details, see this tuning example. (Introduced in 5.0 update 6.) [5.0: false]
-XX:+UseFastAccessorMethods Use optimized versions of GetField.
-XX:-UseISM Use Intimate Shared Memory. [Not accepted for non-Solaris platforms.] For details, see Intimate Shared Memory.
-XX:+UseLargePages Use large page memory. (Introduced in 5.0 update 5.) For details, see Java Support for Large Memory Pages.
-XX:+UseMPSS Use Multiple Page Size Support w/4mb pages for the heap. Do not use with ISM as this replaces the need for ISM. (Introduced in 1.4.0 update 1, Relevant to Solaris 9 and newer.) [1.4.1 and earlier: false]
-XX:+UseStringCache Enables caching of commonly allocated strings.

-XX:AllocatePrefetchLines=1 Number of cache lines to load after the last object allocation using prefetch instructions generated in JIT compiled code. Default values are 1 if the last allocated object was an instance and 3 if it was an array.

-XX:AllocatePrefetchStyle=1 Generated code style for prefetch instructions.
0 - no prefetch instructions are generate*d*,
1 - execute prefetch instructions after each allocation,
2 - use TLAB allocation watermark pointer to gate when prefetch instructions are executed.

-XX:-XX:+UseCompressedStrings Use a byte[] for Strings which can be represented as pure ASCII. (Introduced in Java 6 Update 21 Performance Release)

-XX:+OptimizeStringConcat Optimize String concatenation operations where possible. (Introduced in Java 6 Update 20)


Back to Options

Debugging Options

Option and Default Value Description
-XX:-CITime Prints time spent in JIT Compiler. (Introduced in 1.4.0.)
-XX:ErrorFile=./hs_err_pid.log If an error occurs, save the error data to this file. (Introduced in 6.)
-XX:-ExtendedDTraceProbes Enable performance-impacting dtrace probes. (Introduced in 6. Relevant to Solaris only.)
-XX:HeapDumpPath=./java_pid.hprof Path to directory or filename for heap dump. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:-HeapDumpOnOutOfMemoryError Dump heap to file when java.lang.OutOfMemoryError is thrown. Manageable. (Introduced in 1.4.2 update 12, 5.0 update 7.)
-XX:OnError=";" Run user-defined commands on fatal error. (Introduced in 1.4.2 update 9.)
-XX:OnOutOfMemoryError=";
" Run user-defined commands when an OutOfMemoryError is first thrown. (Introduced in 1.4.2 update 12, 6)
-XX:-PrintClassHistogram Print a histogram of class instances on Ctrl-Break. Manageable. (Introduced in 1.4.2.) The jmap -histo command provides equivalent functionality.
-XX:-PrintConcurrentLocks Print java.util.concurrent locks in Ctrl-Break thread dump. Manageable. (Introduced in 6.) The jstack -l command provides equivalent functionality.
-XX:-PrintCommandLineFlags Print flags that appeared on the command line. (Introduced in 5.0.)
-XX:-PrintCompilation Print message when a method is compiled.
-XX:-PrintGC Print messages at garbage collection. Manageable.
-XX:-PrintGCDetails Print more details at garbage collection. Manageable. (Introduced in 1.4.0.)
-XX:-PrintGCTimeStamps Print timestamps at garbage collection. Manageable (Introduced in 1.4.0.)
-XX:-PrintTenuringDistribution Print tenuring age information.
-XX:-TraceClassLoading Trace loading of classes.
-XX:-TraceClassLoadingPreorder Trace all classes loaded in order referenced (not loaded). (Introduced in 1.4.2.)
-XX:-TraceClassResolution Trace constant pool resolutions. (Introduced in 1.4.2.)
-XX:-TraceClassUnloading Trace unloading of classes.
-XX:-TraceLoaderConstraints Trace recording of loader constraints. (Introduced in 6.)
-XX:+PerfSaveDataToFile Saves jvmstat binary data on exit.

mercredi 1 décembre 2010

unix / linux : compter le nombre de lignes

Une très bonne astuce, pour compter le nombre de lignes d'un programme. Par exemple, le nombre de ligne de java :

find . -name '*.java'-exec cat '{}' \; | wc -l

unix / linux : trouver informations sur la machine hardware

Une commande utile pour trouver des informations sur le hardware d'une machine:

Sur Unix Sun Solaris :
psrinfo -v

Sur Linux :

Pour la mémoire :
cat cat /proc/meminfo

Pour les infos CPU :
cat /proc/cpuinfo

ou une autre commande fort utile "dmesg". Cependant cette dernière envoie beaucoup d'informations et un grep est souvent nécessaire :
dmesg | grep cpu

mercredi 24 novembre 2010

svn : migration svn cvs

Comment migrer un repo svn :

Il faut utiliser cvs2svn. Néanmoins ce script est en python et nécessite python ... Il faut donc, le télécharger et le copier dans un répertoire ou on possède les droits d'écritures.

puis lancer make install en "root"
sudo make install

Pour cela je posséder un user qui posséder les droits sudo. Ceci m'a permis de rechercher et d'installer les packages manquants via :

sudo yum list available | grep ncompress
sudo yum install ncompress

Note: une façon de se connecter avec n'importe quel user est d'utiliser sudo :

sudo su - toto

Et voila je suis logger en toto ... et plus de problème de droits ... et de création de fichiers et répertoires appartenant à "root"

mardi 23 novembre 2010

Linux : C++ edition des liens / librairie pkg-config

Voici un programme qui va vous changer la vie. Ce dernier permet de faire simplement une edition des liens en C/C++ sous Linux ... éh oui ...

Il s'agit de pkg-config ... qui non seulement vous crée les bonnes options , mais en plus ajoute les options préconnisées par les développeurs de la librairie !!!

exemple pour opencv sous ubuntu:


g++ face.c `pkg-config --libs --cflags opencv` -o face.exe

Pour info : la commande `pkg-config --libs --cflags opencv` retourne `-I/usr/include/opencv`

En fait pour les options de compilation , on utilise "--cflags":
`pkg-config --cflags gtk+-2.0`

En fait pour les options de linkage, on utilise "--libs":
`pkg-config --cflags gtk+-2.0`

Par exemple, il faut mettre chacune des commandes précédentes dans code block (onglet "compiler option" pour les premières, et la seconde dans "linker option".

mercredi 17 novembre 2010

oracle : sqlloader exemple

Voici les données charger via SQLLoader

Le fichier de données (trafic.csv)

1;2387;9287;0087;;;;;;;;01012008;;;;
1;9287;2387;0087;;;;;;;;01012008;;;;
1;3105;0087;3093;;;;;;;;01012008;;;;
1;0087;3105;3093;;;;;;;;01012008;;;;
8;0054;0087;3093;;;;;;;;01012008;;;;
8;0087;0054;3093;;;;;;;;01012008;;;;
0;3195;0087;;;;;;;;;01012008;;;;
0;0087;3195;;;;;;;;;01012008;;;;
0;0087;3192;;;;;;;;;01012008;;;;
0;3192;0087;;;;;;;;;01012008;;;;
10;2155;0087;2181;9687;2180;;;;;;01012008;;;;
10;0087;2155;2180;9687;2181;;;;;;01012008;;;;


Voici un exemple de fichier ctl de contrôle :


LOAD DATA
INFILE 'codetrafic.csv'
REPLACE
INTO TABLE TBOR_CODE_TRAFIC_MAJ
FIELDS TERMINATED BY ';'
TRAILING NULLCOLS
(
CODE_TRAFIC CHAR (2) NULLIF (CODE_TRAFIC =BLANKS)
,IF_DEBUT CHAR (4) NULLIF (IF_DEBUT =BLANKS)
,IF_FIN CHAR (4) NULLIF (IF_FIN =BLANKS)
,IF_1 CHAR (4) NULLIF (IF_1 =BLANKS)
,IF_2 CHAR (4) NULLIF (IF_2 =BLANKS)
,IF_3 CHAR (4) NULLIF (IF_3 =BLANKS)
,IF_4 CHAR (4) NULLIF (IF_4 =BLANKS)
,IF_5 CHAR (4) NULLIF (IF_5 =BLANKS)
,IF_6 CHAR (4) NULLIF (IF_6 =BLANKS)
,IF_7 CHAR (4) NULLIF (IF_7 =BLANKS)
,IF_8 CHAR (4) NULLIF (IF_8 =BLANKS)
, D_DEB DATE "DDMMYYYY" NULLIF (D_DEB=BLANKS)
, D_FIN DATE "DDMMYYYY" NULLIF (D_FIN=BLANKS)
, PAYS_DEST INTEGER EXTERNAL NULLIF (PAYS_DEST =BLANKS)
, TAG_MAJ CHAR (200)NULLIF (TAG_MAJ =BLANKS)
)


Un exemple de commande de lancement :
host sqlldr $test/$test log=codeitigeo.log bad=codeitigeo.bad discard=codeitigeo.txt data=codeitigeo.csv control=update_code_iti.ctl errors=0

java : un bon site

Un super site pour le java en general ...

http://www.javapractices.com/home/HomeAction.do

mardi 16 novembre 2010

unix /linux : shell exemple divers


#!/bin/bash

# declaration functions
function erreurChoix()
{
echo "$1 n'est pas une valeur authorisée, veuillez saisir une valeur comprise";
}

function menu()
{
# affichage des choix
echo "chosissez le traitement"
echo "1) recherche et archivage des mp3"
echo "2) comptage des mp3 et avi"
echo "3) sortir"

read choix
# boucle de saisie
while [ "$choix" = "" ]
do
erreurChoix $choix
read choix
done
# case
case $choix in
1)
if [ -f archive.tar ]
then
rm -v archive.tar
exit 2
fi
find . \( -name "*.mp3" -o -name "*.avi" \) -exec tar -uvf archive.tar {} \;
exit 0;;
2)
LISTE=`find . \( -name "*.mp3" -o -name "*.avi" \) -exec ls -al {} \;`
NB=`echo $LISTE | wc -l`
echo "fichiers trouves = $NB"
exit 0;;
3)
echo "sortir"
exit 0;;
*)
erreurChoix $choix;
exit 2;;
esac
}

set -x
# controle du nombre d'argument
if [ $# -neq 0 ]
then
echo "le nombre d'argument est de 0"
exit 2
else
menu
fi

unix / linux : commande eval et sed avec regex


#+---------------------------------------------------------------------------+
#! _GetDate : Récupérer la date d'un jour précédent ou suivant !
#! parametres : nombre de jour (+/-) et le format désiré !
#+---------------------------------------------------------------------------+
_GetDate()
{ # GetDate nDays [format]
# Exemple d'utilisation: export NAMEDIR=$(GetDate -1 '+%Y.%m.%d')

typeset -i nDays=$1
typeset format=$2

eval $(echo $TZ | sed '
s!\([^-0-9]*\)\([-0-9]*\)\(.*\)!typeset -i localOffset=\2;zon1=\1;zon2=\3!')
TZ=$zon1$((localOffset-24*nDays))$zon2 date $format

return 0
}

lundi 15 novembre 2010

unix / linux : commande cut

Voici, un exemple de la commande cut :

pour les delimiter, il faut préciser le champ vise avec f1 ou f2 :


echo "monEar.ear" | cut -f1 -d'.'

ce qui donne :

monEar




echo "monEar.ear" | cut -f2 -d'.'

ce qui donne :

ear

jeudi 11 novembre 2010

java : maven tomcat embedded

Voici un plugin qui embarque un tomcat 6 ... , c'est tout de même surper pratique, et très rapide (toutes les infos ici ...:


Ajouter le plugin dans le pom.xml, puis:


...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<warFile>path/to/my/warFile.war</warFile>
</configuration>
</plugin>
...


lancer les commandes suivantes:

en mode war exploded :
mvn war:inplace tomcat:inplace

en mode classique :
mvn tomcat:run

deployer un context.xml
mvn tomcat:deploy

mercredi 10 novembre 2010

java : performance thread dump

Pour les JVM récentes:

Tester sur jvm 1.6

Il est aussi possible de faire un kill -QUIT pid ou un kill -3 pid, ceci permet fait un dump de la JVM et le redirige vers le STDOUT. Attention, sur un serveur, STDOUT est souvent redirigée vers un fichier de log général (ex: log du domaine, ou server.log pour tomcat).

Note : sous windows la combinaison Ctrl+Break (sur mon calvier Ctrl+Pause) ... affiche le thread dump dans la console.


java -Xloggc:logs/gc-thb1_81pappsn03-statistic.log -verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails


pour une jvm jrockit 1.4:

java -Xverboselog:/users/enwoo/loggc_appli.log -Xverbosetimestamp -Xverbose:memory -Xgcpause

lundi 8 novembre 2010

windows : dos script shell

Un rappel sur les scripts DOS :

des call, des boucles for, des if ... de tout quoi ...


@ECHO OFF
SET RETURN_CODE=
SETLOCAL

SET WL_HOME=D:\bea\weblogic81

SET JAVA_VENDOR=Sun
SET JAVA_HOME=D:\bea\jdk142_05

CALL "%WL_HOME%\common\bin\commEnv.cmd"
FOR %%i IN ("%WL_HOME%") DO SET WL_HOME=%%~fsi
FOR %%i IN ("%JAVA_HOME%") DO SET JAVA_HOME=%%~fsi
SET JAVA_VENDOR=

SET DATABASES=pointbase oracle mssql db2 sybase informix
CALL %WL_HOME%\common\bin\configDB.cmd %DATABASES%

SET CLASSPATH=.;3rdparty.jar;config.jar;comdev.jar;wizard.jar;%DATABASE_CLASSPATH%;%WL_HOME%\server\lib\weblogic.jar;%WL_HOME%\server\lib\ant\ant.
IF DEFINED DATABASE_PATH SET PATH=%DATABASE_PATH%;%PATH%

PUSHD %WL_HOME%\common\lib

IF "%1" == "" (
%JAVA_HOME%\bin\javaw %MEM_ARGS% com.bea.plateng.wizard.WizardController
) ELSE (
%JAVA_HOME%\bin\java %MEM_ARGS% com.bea.plateng.wizard.WizardController %*
)

SET RETURN_CODE=%ERRORLEVEL%
POPD

ENDLOCAL & SET RETURN_CODE=%RETURN_CODE%
SET RETURN_CODE
exit /B %RETURN_CODE%

linux : shell script killer les process fils

Voici un petit script permettant de killer un process et ses nombruex enfants, exemple le nodeManager de weblogic :

Pour info, le PID


#/bin/bash
#set -x

PIDS=`ps -edf | grep NodeManager | grep -v grep | grep -v STIME | grep 7667 | cut -c 10-14`

for PID in $PIDS
do
kill -9 $PID
done

dimanche 7 novembre 2010

svn : créer un repository rapidement

Voici, un petit script qui permet de commencer rapidement à travailler avec un repo SVN correctement créer:

c'est à dire avec un trunk, tags, branches


#!/bin/bash
#set -x
# variables
NOM_PROJET=followMe
SOURCE_HOME=/home/enwoo/projets/workspacePerso/quickstart
SVN_REPO=/home/enwoo/repositorySVN
# debut script
svnadmin create $SVN_REPO/$NOM_PROJET
svn mkdir -m 'ajout du trunk' file://$SVN_REPO/$NOM_PROJET/trunk
svn mkdir -m 'ajout des branches' file://$SVN_REPO/$NOM_PROJET/branches
svn mkdir -m 'ajout du tags' file://$SVN_REPO/$NOM_PROJET/tags
svn import -m 'init import' $SOURCE_HOME file://$SVN_REPO/$NOM_PROJET/trunk

# ajouter les droits

mardi 2 novembre 2010

ant : rappels (ant-contrib sshexec ftp)

Ant est un outil très pratique qui permet d'automatiser pas mal de tache, et qui est portable et peut être appelé de maven.

Il permet notamment des connexion ftp et ssh à condition d'ajouter dans le classpath ou dans le $ANT_HOME/lib, les librairies adéquates.

Exemple pour ant 1.8.1 :
- jsch-0.1.42.jar pour ssh
- commons-net-1.4.1.jar et oro-2.0.7.jar pour FTP.


Des extensions sont possible comme la possibilité de faire des boucles for et des if simplement avec ant-contrib

Voici un exemple sur ant-contrib:

Tout d'abord ajouter le jar dans le classpath

<path id="project.class.path">
<pathelement location="${basedir}/cmd/lib/ant-contrib-1.0b3.jar" />
<pathelement location="${basedir}/cmd/lib/ojdbc14.jar" />
</path>
<!-- Déclaration des tâches définies dans la lib ant-contrib.
>
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath refid="project.class.path" />
</taskdef>


Ou avec un chemin en dur comme suit:

<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="D:/apache-ant-1.8.1-bin/apache-ant-1.8.1/lib/ant-contrib-1.0b3.jar"/>
</classpath>
</taskdef>


Puis, il est possible de faire des boucles sur l'ensembles des environnements :

<target name="stopAll">
<echo message="The first five letters of the alphabet are:"/>
<for list="bod2,bod3,bod4,bod5,bod6" param="environnement">
<sequential>
<property file="@{environnement}" id="specific"/>
<echo>Arret de @{environnement}</echo>
<antcall target="stopServeur" />
</sequential>
</for>
</target>



Pour rappel :

Chargement des fichiers de propriétés (un spécifique possitionné par une variable d'environnement et un autre général):


<property file="${config.file}" id="specific"/>
<property file="global.properties" id="global"/>


ant -d -Dconfig.file=maCibleValidation.properties -f build.xml startServeur

Et voici, le fichier de confiruration spécifique (nommé maCibleValidation.properties)


#propriete SSH
serveur.ssh.url=maCible.fr
serveur.ssh.port=22
serveur.ssh.user=monUser
serveur.ssh.password=monPassword

#propriete FTP
serveur.ftp.url=maCible.fr
serveur.ftp.port=21
serveur.ftp.user=monUserSSH
serveur.ftp.password=monPasswordSSH
serveur.ftp.remoteDir=/devel/bo/monUser/exe/earHudson

#propriete lie a la construction du ZIP
project.home=D:/program/Industrialisation/MigJava6
project.home.dist=${project.home}/dist

# port admin weblogic
weblogic.admin.port=11141



et le fichier global:

#propriete SSH
remote.java.home=/produits/dev/bea/jrockit81sp5_142_08
weblogic.home=/produits/dev/wls81sp4
weblogic.username=weblogic
weblogic.password=weblogic
weblogic.server.valo=serverCalcul
weblogic.server.orchestre=serverJSP


Voici, la construction d'une commande d'arret du serveur serverCalcul qui sera lancé en SSH :

Tout d'abord la connexion SSH avec l'option TRUST qui permet de faire conficance quand on pas de clé privée installé :


<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="${stopOrchestre}" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />



<property name="stopValo" value="${remote.java.home}/bin/java -cp ${weblogic.home}/server/lib/weblogic.jar weblogic.Admin -url ${serveur.ssh.url}:${weblogic.admin.port} -username ${weblogic.username} -password ${weblogic.password} FORCESHUTDOWN ${weblogic.server.valo}" />


Voici, un exemple complet de taches qui permet de d'automatiser le deplacement d'EAR sur un serveur maCible, par un transfert de zip, puis, permet l'arrêt et la relance des 2 serveurs nommés respectivement serveurCalcul et serveurJSP

Un exemple de lancement en ligne de commande (je le lance via DOS car avec eclipse y'a des soucis bizarre ...)

ant -d -Dconfig.file=maCibleValidation.properties -f build.xml startServeur


<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================
27 oct. 2010 13:53:59
ic CIBLE
permet le deploiement des EAR CIBLEs

lducamp
====================================================================== -->
<project name="ic CIBLE" default="deployEAR">
<description>
permet le deploiement des EAR CIBLEs
</description>

<property file="${config.file}" id="specific"/>
<property file="global.properties" id="global"/>
<property name="startValo" value="${remote.java.home}/bin/java -cp ${weblogic.home}/server/lib/weblogic.jar weblogic.Admin -url ${serveur.ssh.url}:${weblogic.admin.port} -username ${weblogic.username} -password ${weblogic.password} START ${weblogic.server.valo}" />
<property name="startOrchestre" value="${remote.java.home}/bin/java -cp ${weblogic.home}/server/lib/weblogic.jar weblogic.Admin -url ${serveur.ssh.url}:${weblogic.admin.port} -username ${weblogic.username} -password ${weblogic.password} START ${weblogic.server.orchestre}" />

<property name="stopValo" value="${remote.java.home}/bin/java -cp ${weblogic.home}/server/lib/weblogic.jar weblogic.Admin -url ${serveur.ssh.url}:${weblogic.admin.port} -username ${weblogic.username} -password ${weblogic.password} FORCESHUTDOWN ${weblogic.server.valo}" />
<property name="stopOrchestre" value="${remote.java.home}/bin/java -cp ${weblogic.home}/server/lib/weblogic.jar weblogic.Admin -url ${serveur.ssh.url}:${weblogic.admin.port} -username ${weblogic.username} -password ${weblogic.password} FORCESHUTDOWN ${weblogic.server.orchestre}" />

<!-- - - - - - - - - - - - - - - - - -
target: init
- - - - - - - - - - - - - - - - - -->
<target name="init">
<echo>${startValo}</echo>
<echo>${startOrchestre}</echo>
</target>


<!-- =================================
target: deployEAR
================================= -->
<target name="deployEAR" description="permet le deploiement des EAR CIBLEs">
<!-- tar.gz des EARs -->
<echo>tar.gz des EARs ${}</echo>
<antcall target="zipEAR" />
<!-- transfert des ears par FTP -->
<echo>transfert des EARs</echo>
<antcall target="ftp" />
<!-- arret des serveurs Weblogic -->
<echo>arret des serveurs </echo>
<antcall target="stopServeur"/>
<!-- demarrage des serveurs Weblogic -->
<echo>arret des serveurs </echo>
<antcall target="startServeur"/>
</target>

<!-- =================================
target: ftp
================================= -->
<target name="ftp" description="execution distante">

<ftp password="${serveur.ftp.password}" server="${serveur.ftp.url}" userid="${serveur.ftp.user}" port="${serveur.ftp.port}" binary="true" action="put" remotedir="${serveur.ftp.remoteDir}" newer="yes" verbose="true">
<fileset dir="${project.home.dist}">
<include name="*.tar.gz" />
</fileset>
</ftp>
</target>

<!--
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" commandResource="stop.sh" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
-->
<target name="stopServeur">
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="${stopOrchestre}" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="${stopValo}" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
</target>

<target name="startServeur">
<!--
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
-->
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="${startValo}" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
<sshexec host="${serveur.ssh.url}" username="${serveur.ssh.user}" password="${serveur.ssh.password}" trust="true" command="${startOrchestre}" port="${serveur.ssh.port}" failonerror="true" verbose="false" output="ssh.log" />
</target>


<!-- - - - - - - - - - - - - - - - - -
target: zipEAR
- - - - - - - - - - - - - - - - - -->
<target name="zipEAR" >
<mkdir dir="${project.home.dist}" />
<copy todir="${project.home.dist}" failonerror="yes">
<fileset dir="${project.home}/generation/generation-ear/target">
<filename name="generation-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/orchestre/orchestre-ear/target">
<filename name="orchestre-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/orchestre/orchestre-ear/target">
<filename name="orchestre-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/orchestre-mq/orchestre-mq-ear/target">
<filename name="orchestre-mq-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/referentiel/referentiel-ear/target">
<filename name="referentiel-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/tarification/tarification-ear/target">
<filename name="tarification-ear-1.0-SNAPSHOT.ear" />
</fileset>
<fileset dir="${project.home}/valorisation/valorisation-ear/target">
<filename name="valorisation-ear-1.0-SNAPSHOT.ear" />
</fileset>
</copy>

<tar destfile="${project.home.dist}/ear.tar">
<fileset dir="${project.home.dist}" id="id">
<include name="**/*.ear" />
</fileset>
</tar>
<gzip destfile="${project.home.dist}/ear.tar.gz" src="${project.home.dist}/ear.tar" />
</target>

</project>

mercredi 27 octobre 2010

linux : shell script

Voici quelques exemples sympa de remplacements ...


grep -He tarif-applique.[0-9]*..tarif-applique $1/RAV9*.xml | sed "s/.*RAV\([0-9\-]*\).*:.*tarif-applique.\([0-9]*\)..tarif-applique.*/RAV \1 = \2 /" >> listeRAV-tarif.tmp

# puis on va chercher le RV la version du tarifs appliqué (si elle existe sinon ...A VOIR ...)
while read line
do
# creation d'un tableau, chaque espace sert de delimiter pour un futur element du tableau
arrLine=( $line)
# il peut y avoir plusieurs balise (avec les PANS) mais la version du tarifs du RV sera la dernière du fichier
version=( `grep -e version-tarif.[0-9]*..version-tarif $2/RV${arrLine[1]}.xml | sed "s/.*version-tarif.\([0-9]*\)..version-tarif.*/\1/"`)
# pour lister les tarifs des PANS
tarif=( `grep -e tarif-applique.[0-9]*..tarif-applique $2/RV${arrLine[1]}.xml | sed "s/.*tarif-applique.\([0-9]*\)..tarif-applique.*/\1/"`)
if [ ${#version[*]} -eq 0 ]
then
aff_version=" non trouve (inexistant, ou date incompatible, ...)"
elif [ ${#version[*]} -eq 1 ]
then
aff_version=" version ${version[0]}"
else
aff_version=" version ${version[$((${#version[*]}-1))]}"
# affichage des des tarifs des PANS
nb=0
while [ $nb -lt $((${#tarif[*]})) ]
do
echo "RV${arrLine[1]} PAN $((nb+1)) = ${tarif[nb]} version ${version[nb]}" >> listeRV-PAN-tarif-version.tmp
nb=$((nb+1))
done
fi
echo "RV${arrLine[1]} = ${arrLine[3]} $aff_version" >> listeRV-tarif-version.tmp
done < listeRAV-tarif.tmp

cat listeRV-tarif-version.tmp | sed "s/.*=\(.*\)/\1/" > listeTarifBrute.tmp
cat listeRV-PAN-tarif-version.tmp | sed "s/.*=\(.*\)/\1/" >> listeTarifBrute.tmp

nbTests=`cat listeRAV-tarif.tmp | wc -l`
nbId=`cat listeRAV-tarif.tmp | sed "s/.*=\(.*\)/\1/" | sort -u | wc -l`
nbTarifs=`cat listeRV-tarif-version.tmp | sed "s/.*=\(.*\)/\1/" | sort -u | wc -l`
nbTarifsPAN=`cat listeRV-PAN-tarif-version.tmp | sed "s/.*=\(.*\)/\1/" | sort -u | wc -l`

mardi 19 octobre 2010

migration CVS a SVN : rappel ...

Pour migrer simplement un projet CVS sous SVN, il existe un outil en python nommé :
cvs2svn

Pour créer un nouveau dépôt Subversion en convertissant un dépôt CVS existant, exécutez le script comme ceci:

Attention, il ne faut pas hésiter à faire une copie de sauvegarde du repos CVS ;-)

$ Cvs2svn-s NEW_SVNREPOS CVSREPOS
Pour créer un nouveau référentiel Subversion malle contenant seulement commet, et en omettant toutes les branches et les étiquettes à partir de CVS, ne

$ Cvs2svn - coffre-que-s NEW_SVNREPOS CVSREPOS
Pour créer un fichier de sauvegarde Subversion (svnadmin appropriée à la charge) à partir d'un dépôt CVS, exécutez-le comme ceci:

$ Cvs2svn - dump-only - dumpfile DUMPFILE CVSREPOS

Attention a préciser l'encoding (par ex : pour windows). De plus, si des erreurs se produisent le cvs2svn s'interrompt ... :
$ cvs2svn -v --encoding=cp1252 -s /repos/BOC201010 /repos/tmp/BOC201010/java
$ Cvs2svn --encoding=utf_8 -s NEW_SVNREPOS CVSREPOS


Une fois la commande utilisé, il faut se rendre sous le nouveau repo svn, et y ajouter les droits adéquates ... Par exemple :

Et on donne les accès dans le fichier access
sudo nano ../access
[svnrepo:/]
@dev = rw
* = r

maven : publier un catlogue d'archetypes

Comment créer un catalogue d'archetypes ?

Pour cela, il faut générer un fichier xml partuiculier. Un moyen simple est l'utilisation du goal "archetype:crawl" scan votre repository local à la recherche de vos archetypes :

mvn archetype:crawl

Un lien avec une explication complète

maven : les archetypes interessants

un super lien sur maven et les archetypes notables

Voici un petit résumé des archetypes les plus utiles :


* maven-archetype-quickstart (un simple jar)

* maven-archetype-webapp (une simple webapp)

* maven-archetype-mojo (un plugin maven)



En résumé AppFuse, c'est Spring / hibernate / (JSF, struts ou tapestry)) et MySQL le quickstart AppFuse est nécessaire

* appfuse-basic-jsf et appfuse-modular-jsf
Application complète utilisant JSF (Java Server Faces) comme couche de présentation.

* appfuse-basic-spring et appfuse-modular-spring
Application complète utilisant Spring MVC comme couche de présentation.

* appfuse-basic-struts et appfuse-modular-struts
Application complète utilisant Struts 2 comme couche de présentation.

* appfuse-basic-tapestry et appfuse-modular-tapestry
Application complète utilisant Tapestry comme couche de présentation.

* appfuse-core (Modèle objet et sa couche de persistance sans couche présentation.)


Voici un petit exemple :


mvn archetype:generate \
-DarchetypeArtifactId=appfuse-modular-spring \
-DarchetypeGroupId=org.appfuse.archetypes \
-DgroupId=org.sonatype.mavenbook \
-DartifactId=mod-spring \
-Dversion=1.0-SNAPSHOT \
-DinteractiveMode=false

Ou avec Tapestry :
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-basic-tapestry-archetype -DarchetypeVersion=2.1.0-M1 -DgroupId=com.mycompany -DartifactId=myproject



Rappel pour MySQL et AppFuse

Il faut un "user mySQL" root avec un password vide

MySQL Security
Running MySQL using root with no password is not the most secure thing to do. Once your database is created, you can change the root password using the command below:
mysql --user=root --pass='' mysql -e "update user set password=password('newpw') \
where user='root'; flush privileges;"
AppFuse uses the username "root" and a blank password by default. To change these values, modify the and properties in your project's pom.xml (at the bottom).

lundi 18 octobre 2010

unix : conversion en UTF-8 ou autre

Il arrive souvent que l'on ait des soucis d'encodage lorsque l'on développe sous windows avec eclipse et sous Linux ... Pour parer à toute enventualités, il est fréquent de devoir réencoder les fichiers en UTF-8 (par exemple pour maveniser l'application).

Voici un petit script sous cygwin qui fait cela tout seul


in/bash

function print_usage()
{
echo "$`basename $0` nomDuRepertoire"
}

set -x
if [ $# -lt 1 ]
then
print_usage
else
rm -ivf *.old
FILES=`find . -type f \( -name '*.txt' -o -name '*.properties' -o -name '*.txt' -o -name '*.local' \)`

for FILE in $FILES
do
if [ -e $FILE ]
then
iconv -f cp1252 -t UTF-8 $FILE > "$FILE.new"
mv "$FILE" "$FILE.old"
mv "$FILE.new" "$FILE"
fi
done
fi

vendredi 15 octobre 2010

unix shell ksh : switch example

Voici, un petit exemple de switch case en ksh


if [ $# -lt 2 ]; then
print_usage
exit $STATE_OK
fi

while test -n "$1"; do
case "$1" in
--help)
print_usage
exit $STATE_OK
;;
-h)
print_usage
exit $STATE_OK
;;
-a)
ServerName=$2
shift
;;
*)
echo "Unknown argument: $1"
print_usage
exit $STATE_UNKNOWN
;;
esac
shift
done

mercredi 13 octobre 2010

java : client webservice avec maven et jax-ws

Voici, le pom permettant de générer le code client via "wsimport"


<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>testJaxWS</groupId>
<artifactId>testJaxWS</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>testJaxWS</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>

<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
</execution>
</executions>
<configuration>
<wsdlUrls>
<wsdlUrl>
http://unServeur:20010/liaisons/services/Fourniture?wsdl

</wsdlUrl>
<!-- ${basedir}/src/main/resources/fourniture.wsdl -->
</wsdlUrls>
<packageName>com.proto.ws.fourniture</packageName> <!-- The name of your generated source package -->
</configuration>

<!--
if you want to use a specific version of JAX-WS, you can do so like

this

-->
<dependencies>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>
</plugin>

<!-- Don't forget Java 5!! -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>



De plus, il est possible de générer la partie serveur avec wsgen :


<plugin>
<groupId>org.codehaus.mojo</groupId>

<artifactId>jaxws-maven-plugin</artifactId>
<executions>
<execution>

<goals>
<goal>wsgen</goal>
</goals>

<configuration>
<packageName>com.weflex.service</packageName>
<!-- The name of your generated source package -->
<sei>com.welflex.soap.ws.OrderWebService</sei>

<keep>true</keep>
<genWsdl>true</genWsdl>
</configuration>
</execution>

</executions>

java : un super site

Le site javaranch est vraiment très bien !!!
- il dispose de nombreuses FAQ
- et articles technique très à jour


javaranch

mardi 12 octobre 2010

J2EE : envoyer un message JMS

Voici la marche à suivre :

1) récuperer le contexte JNDI
(ex: de valeurs:
- pour weblo l'url de t3://orchestre.si.fr:11133
- jndi.jms.fileretourvaloClassique=jms/retourValorisationQueue


jndiContext = InitialContextManager.getInitialContext(urlAnnuaireJndiDestination);


2) récupérer la "connexion factory" et la queue :

connectionFactory = (QueueConnectionFactory)
jndiContext.lookup(PropertiesManager.getInstance().getString(
"jndi.jms.connectionfactory"));

destQueue = (Queue) jndiContext.lookup(nomJndiFileDestination);


3) Une fois la connexion factory, recupérer la queue Session, et un sender, message

connection = connectionFactory.createQueueConnection();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

qSender = session.createSender(destQueue);

ObjectMessage message = session.createObjectMessage();
message.setJMSCorrelationID(idMessage);
message.setObject(objetAEnvoyer);




Voici un exemple complet:


/**
*
* @param urlAnnuaireJndiDestination String serveur (jndi)
* @param nomJndiFileDestination String file JMS (jndi)
* @throws ServiceJMSException
*/
public void init(String urlAnnuaireJndiDestination,
String nomJndiFileDestination) throws ServiceJMSException {
try {
//On garde ces 2 paramètres pour faire un réinit si besoin
urlAnnuaireJndiDestinationReinit=urlAnnuaireJndiDestination;
nomJndiFileDestinationReinit=nomJndiFileDestination;

jndiContext = InitialContextManager.getInitialContext(
urlAnnuaireJndiDestination);
connectionFactory = (QueueConnectionFactory)
jndiContext.lookup(PropertiesManager.getInstance().getString(
"jndi.jms.connectionfactory"));

destQueue = (Queue) jndiContext.lookup(nomJndiFileDestination);
logger.info("JMS Initialisation terminée");
}
catch (Exception e) {
logger.fatal("JMS Initialisation en erreur",e);
throw new ServiceJMSException(e);
}

private synchronized void essayerEnvoyerMessage(Serializable objetAEnvoyer, String idMessage,String replyServerName, String replyQueueName) throws JMSException, ServiceJMSException {
if(connectionFactory==null ){
logger.error("JMS Connection Factory null, tentative de réinitialisation.");
init(urlAnnuaireJndiDestinationReinit, nomJndiFileDestinationReinit);
}

connection = connectionFactory.createQueueConnection();
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

qSender = session.createSender(destQueue);

ObjectMessage message = session.createObjectMessage();
message.setJMSCorrelationID(idMessage);
message.setObject(objetAEnvoyer);

//message.setJMSExpiration(30000);

if(replyServerName!=null){
message.setStringProperty(REPLY_SERVER_NAME,replyServerName);
}
if(replyQueueName!=null){
message.setStringProperty(REPLY_QUEUE_NAME,replyQueueName);
}

qSender.send(message);

// Release Sender
if (qSender != null) {
try {
qSender.close();
} catch (JMSException vJMSException) {
logger.error("Error close QueueSender " + vJMSException.getStackTrace());
}
}

//Release QueueSession
if (session != null) {
try {
session.close();
} catch (JMSException vJMSException) {
logger.error("Error close QueueSession " + vJMSException.getStackTrace());
}
}

//Release QueueConnection
if (connection != null) {
try {
connection.close();
} catch (JMSException vJMSException) {
logger.error("Error close QueueConnection " + vJMSException.getStackTrace());
}
}
}

windows : script shell

Voici des petits exemples de script sous windows ...


Tout d'abord le set ...

@rem Choose proper WebLogic jni libraries
set WL_USE_X86DLL=true
set WL_USE_IA64DLL=false
@rem Set Ant Home
set ANT_HOME=%MODULES_DIR%\org.apache.ant_1.7.1



Puis, le if, et un jump a "noReset" ...

@rem Reset JAVA_HOME, JAVA_VENDOR and PRODUCTION_MODE unless JAVA_HOME and
@rem JAVA_VENDOR are defined already.
if DEFINED JAVA_HOME if DEFINED JAVA_VENDOR goto noReset

...

:noReset


Un second if avec un test

if "%JAVA_VENDOR%" == "Sun" goto sun


Puis un if qui test si un fihcier exist, et si oui, l'appel :

@rem setup patch related class path, library path, path and extension dirs options
if exist "%WL_HOME%\common\bin\setPatchEnv.cmd" call "%WL_HOME%\common\bin\setPatchEnv.cmd"


Puis, un if not ...


IF NOT "%DERBY_PRE_CLASSPATH%"=="" (
set DERBY_CLASSPATH=%DERBY_PRE_CLASSPATH%;%DERBY_CLASSPATH%
)

...

IF NOT EXIST %WL_HOME%\common\eval\pointbase goto endpointbase


Puis une boucle :

set ANT_HOME=%MODULES_DIR%\org.apache.ant_1.7.1
FOR %%i IN ("%ANT_HOME%") DO SET ANT_HOME=%%~fsi


Une fonction complexe:

:SETARG
SET ARGNAME=%1
SET ARGVALUE=%2
SHIFT
SHIFT
FOR %%I IN (%ARGVALUE%) DO SET ARGVALUE=%%~I
IF /i "%ARGNAME%"=="-log" (
IF "%ARGVALUE:~1,1%"==":" (
SET ARGUMENTS=%ARGUMENTS% %ARGNAME%=%ARGVALUE%
) ELSE (
SET ARGUMENTS=%ARGUMENTS% %ARGNAME%=%MYPWD%\%ARGVALUE%
)
GOTO :PARSEARGS
) ELSE (
IF /i "%ARGNAME%"=="-silent_script" (
IF "%ARGVALUE:~1,1%"==":" (
SET ARGUMENTS=%ARGUMENTS% %ARGNAME%=%ARGVALUE%
) ELSE (
SET ARGUMENTS=%ARGUMENTS% %ARGNAME%=%MYPWD%\%ARGVALUE%
)
GOTO :PARSEARGS
) ELSE (
IF /i "%ARGNAME%"=="-useXACML" (
SET MEM_ARGS=%MEM_ARGS% -DuseXACML=%ARGVALUE%
) ELSE (
SET ARGUMENTS=%ARGUMENTS% %ARGNAME%="%ARGVALUE%"
)
GOTO :PARSEARGS
)
)

vendredi 8 octobre 2010

javascript : exemples complexes


/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.

Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:

http://dojotoolkit.org/community/licensing.shtml
*/

dojo.provide("dojo.html.style");
dojo.require("dojo.html.common");
dojo.require("dojo.uri.Uri");

dojo.html.getClass = function(/* HTMLElement */node){
// summary
// Returns the string value of the list of CSS classes currently assigned directly
// to the node in question. Returns an empty string if no class attribute is found;
node = dojo.byId(node);
if(!node){ return ""; }
var cs = "";
if(node.className){
cs = node.className;
}else if(dojo.html.hasAttribute(node, "class")){
cs = dojo.html.getAttribute(node, "class");
}
return cs.replace(/^\s+|\s+$/g, ""); // string
}

dojo.html.getClasses = function(/* HTMLElement */node) {
// summary
// Returns an array of CSS classes currently assigned directly to the node in question.
// Returns an empty array if no classes are found;
var c = dojo.html.getClass(node);
return (c == "") ? [] : c.split(/\s+/g); // array
}

dojo.html.hasClass = function(/* HTMLElement */node, /* string */classname){
// summary
// Returns whether or not the specified classname is a portion of the
// class list currently applied to the node. Does not cover cascaded
// styles, only classes directly applied to the node.
return (new RegExp('(^|\\s+)'+classname+'(\\s+|$)')).test(dojo.html.getClass(node)) // boolean
}

dojo.html.prependClass = function(/* HTMLElement */node, /* string */classStr){
// summary
// Adds the specified class to the beginning of the class list on the
// passed node. This gives the specified class the highest precidence
// when style cascading is calculated for the node. Returns true or
// false; indicating success or failure of the operation, respectively.
classStr += " " + dojo.html.getClass(node);
return dojo.html.setClass(node, classStr); // boolean
}

dojo.html.addClass = function(/* HTMLElement */node, /* string */classStr){
// summary
// Adds the specified class to the end of the class list on the
// passed &node;. Returns &true; or &false; indicating success or failure.
if (dojo.html.hasClass(node, classStr)) {
return false;
}
classStr = (dojo.html.getClass(node) + " " + classStr).replace(/^\s+|\s+$/g,"");
return dojo.html.setClass(node, classStr); // boolean
}

dojo.html.setClass = function(/* HTMLElement */node, /* string */classStr){
// summary
// Clobbers the existing list of classes for the node, replacing it with
// the list given in the 2nd argument. Returns true or false
// indicating success or failure.
node = dojo.byId(node);
var cs = new String(classStr);
try{
if(typeof node.className == "string"){
node.className = cs;
}else if(node.setAttribute){
node.setAttribute("class", classStr);
node.className = cs;
}else{
return false;
}
}catch(e){
dojo.debug("dojo.html.setClass() failed", e);
}
return true;
}

dojo.html.removeClass = function(/* HTMLElement */node, /* string */classStr, /* boolean? */allowPartialMatches){
// summary
// Removes the className from the node;. Returns true or false indicating success or failure.
try{
if (!allowPartialMatches) {
var newcs = dojo.html.getClass(node).replace(new RegExp('(^|\\s+)'+classStr+'(\\s+|$)'), "$1$2");
} else {
var newcs = dojo.html.getClass(node).replace(classStr,'');
}
dojo.html.setClass(node, newcs);
}catch(e){
dojo.debug("dojo.html.removeClass() failed", e);
}
return true; // boolean
}

dojo.html.replaceClass = function(/* HTMLElement */node, /* string */newClass, /* string */oldClass) {
// summary
// Replaces 'oldClass' and adds 'newClass' to node
dojo.html.removeClass(node, oldClass);
dojo.html.addClass(node, newClass);
}

// Enum type for getElementsByClass classMatchType arg:
dojo.html.classMatchType = {
ContainsAll : 0, // all of the classes are part of the node's class (default)
ContainsAny : 1, // any of the classes are part of the node's class
IsOnly : 2 // only all of the classes are part of the node's class
}


dojo.html.getElementsByClass = function(
/* string */classStr,
/* HTMLElement? */parent,
/* string? */nodeType,
/* integer? */classMatchType,
/* boolean? */useNonXpath
){
// summary
// Returns an array of nodes for the given classStr, children of a
// parent, and optionally of a certain nodeType
// FIXME: temporarily set to false because of several dojo tickets related
// to the xpath version not working consistently in firefox.
useNonXpath = false;
var _document = dojo.doc();
parent = dojo.byId(parent) || _document;
var classes = classStr.split(/\s+/g);
var nodes = [];
if( classMatchType != 1 && classMatchType != 2 ) classMatchType = 0; // make it enum
var reClass = new RegExp("(\\s|^)((" + classes.join(")|(") + "))(\\s|$)");
var srtLength = classes.join(" ").length;
var candidateNodes = [];

if(!useNonXpath && _document.evaluate) { // supports dom 3 xpath
var xpath = ".//" + (nodeType || "*") + "[contains(";
if(classMatchType != dojo.html.classMatchType.ContainsAny){
xpath += "concat(' ',@class,' '), ' " +
classes.join(" ') and contains(concat(' ',@class,' '), ' ") +
" ')";
if (classMatchType == 2) {
xpath += " and string-length(@class)="+srtLength+"]";
}else{
xpath += "]";
}
}else{
xpath += "concat(' ',@class,' '), ' " +
classes.join(" ') or contains(concat(' ',@class,' '), ' ") +
" ')]";
}
var xpathResult = _document.evaluate(xpath, parent, null, XPathResult.ANY_TYPE, null);
var result = xpathResult.iterateNext();
while(result){
try{
candidateNodes.push(result);
result = xpathResult.iterateNext();
}catch(e){ break; }
}
return candidateNodes; // NodeList
}else{
if(!nodeType){
nodeType = "*";
}
candidateNodes = parent.getElementsByTagName(nodeType);

var node, i = 0;
outer:
while(node = candidateNodes[i++]){
var nodeClasses = dojo.html.getClasses(node);
if(nodeClasses.length == 0){ continue outer; }
var matches = 0;

for(var j = 0; j < nodeClasses.length; j++){
if(reClass.test(nodeClasses[j])){
if(classMatchType == dojo.html.classMatchType.ContainsAny){
nodes.push(node);
continue outer;
}else{
matches++;
}
}else{
if(classMatchType == dojo.html.classMatchType.IsOnly){
continue outer;
}
}
}

if(matches == classes.length){
if( (classMatchType == dojo.html.classMatchType.IsOnly)&&
(matches == nodeClasses.length)){
nodes.push(node);
}else if(classMatchType == dojo.html.classMatchType.ContainsAll){
nodes.push(node);
}
}
}
return nodes; // NodeList
}
}
dojo.html.getElementsByClassName = dojo.html.getElementsByClass;

dojo.html.toCamelCase = function(/* string */selector){
// summary
// Translates a CSS selector string to a camel-cased one.
var arr = selector.split('-'), cc = arr[0];
for(var i = 1; i < arr.length; i++) {
cc += arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
}
return cc; // string
}

dojo.html.toSelectorCase = function(/* string */selector){
// summary
// Translates a camel cased string to a selector cased one.
return selector.replace(/([A-Z])/g, "-$1" ).toLowerCase(); // string
}

dojo.html.getComputedStyle = function(/* HTMLElement */node, /* string */cssSelector, /* integer? */inValue){
// summary
// Returns the computed style of cssSelector on node.
node = dojo.byId(node);
// cssSelector may actually be in camel case, so force selector version
var cssSelector = dojo.html.toSelectorCase(cssSelector);
var property = dojo.html.toCamelCase(cssSelector);
if(!node || !node.style){
return inValue;
} else if (document.defaultView && dojo.html.isDescendantOf(node, node.ownerDocument)){ // W3, gecko, KHTML
try{
// mozilla segfaults when margin-* and node is removed from doc
// FIXME: need to figure out a if there is quicker workaround
var cs = document.defaultView.getComputedStyle(node, "");
if(cs){
return cs.getPropertyValue(cssSelector); // integer
}
}catch(e){ // reports are that Safari can throw an exception above
if(node.style.getPropertyValue){ // W3
return node.style.getPropertyValue(cssSelector); // integer
} else {
return inValue; // integer
}
}
} else if(node.currentStyle){ // IE
return node.currentStyle[property]; // integer
}

if(node.style.getPropertyValue){ // W3
return node.style.getPropertyValue(cssSelector); // integer
}else{
return inValue; // integer
}
}

dojo.html.getStyleProperty = function(/* HTMLElement */node, /* string */cssSelector){
// summary
// Returns the value of the passed style
node = dojo.byId(node);
return (node && node.style ? node.style[dojo.html.toCamelCase(cssSelector)] : undefined); // string
}

dojo.html.getStyle = function(/* HTMLElement */node, /* string */cssSelector){
// summary
// Returns the computed value of the passed style
var value = dojo.html.getStyleProperty(node, cssSelector);
return (value ? value : dojo.html.getComputedStyle(node, cssSelector)); // string || integer
}

dojo.html.setStyle = function(/* HTMLElement */node, /* string */cssSelector, /* string */value){
// summary
// Set the value of passed style on node
node = dojo.byId(node);
if(node && node.style){
var camelCased = dojo.html.toCamelCase(cssSelector);
node.style[camelCased] = value;
}
}

dojo.html.setStyleText = function (/* HTMLElement */target, /* string */text) {
// summary
// Try to set the entire cssText property of the passed target; equiv of setting style attribute.
try {
target.style.cssText = text;
} catch (e) {
target.setAttribute("style", text);
}
}

dojo.html.copyStyle = function(/* HTMLElement */target, /* HTMLElement */source){
// summary
// work around for opera which doesn't have cssText, and for IE which fails on setAttribute
if(!source.style.cssText){
target.setAttribute("style", source.getAttribute("style"));
}else{
target.style.cssText = source.style.cssText;
}
dojo.html.addClass(target, dojo.html.getClass(source));
}

dojo.html.getUnitValue = function(/* HTMLElement */node, /* string */cssSelector, /* boolean? */autoIsZero){
// summary
// Get the value of passed selector, with the specific units used
var s = dojo.html.getComputedStyle(node, cssSelector);
if((!s)||((s == 'auto')&&(autoIsZero))){
return { value: 0, units: 'px' }; // object
}
// FIXME: is regex inefficient vs. parseInt or some manual test?
var match = s.match(/(\-?[\d.]+)([a-z%]*)/i);
if (!match){return dojo.html.getUnitValue.bad;}
return { value: Number(match[1]), units: match[2].toLowerCase() }; // object
}
dojo.html.getUnitValue.bad = { value: NaN, units: '' };

dojo.html.getPixelValue = function(/* HTMLElement */node, /* string */cssSelector, /* boolean? */autoIsZero){
// summary
// Get the value of passed selector in pixels.
var result = dojo.html.getUnitValue(node, cssSelector, autoIsZero);
// FIXME: there is serious debate as to whether or not this is the right solution
if(isNaN(result.value)){
return 0; // integer
}
// FIXME: code exists for converting other units to px (see Dean Edward's IE7)
// but there are cross-browser complexities
if((result.value)&&(result.units != 'px')){
return NaN; // integer
}
return result.value; // integer
}

dojo.html.setPositivePixelValue = function(/* HTMLElement */node, /* string */selector, /* integer */value){
// summary
// Attempt to set the value of selector on node as a positive pixel value.
if(isNaN(value)){return false;}
node.style[selector] = Math.max(0, value) + 'px';
return true; // boolean
}

dojo.html.styleSheet = null;

// FIXME: this is a really basic stub for adding and removing cssRules, but
// it assumes that you know the index of the cssRule that you want to add
// or remove, making it less than useful. So we need something that can
// search for the selector that you you want to remove.
dojo.html.insertCssRule = function(/* string */selector, /* string */declaration, /* integer? */index) {
// summary
// Attempt to insert declaration as selector on the internal stylesheet; if index try to set it there.
if (!dojo.html.styleSheet) {
if (document.createStyleSheet) { // IE
dojo.html.styleSheet = document.createStyleSheet();
} else if (document.styleSheets[0]) { // rest
// FIXME: should create a new style sheet here
// fall back on an exsiting style sheet
dojo.html.styleSheet = document.styleSheets[0];
} else {
return null; // integer
} // fail
}

if (arguments.length < 3) { // index may == 0
if (dojo.html.styleSheet.cssRules) { // W3
index = dojo.html.styleSheet.cssRules.length;
} else if (dojo.html.styleSheet.rules) { // IE
index = dojo.html.styleSheet.rules.length;
} else {
return null; // integer
} // fail
}

if (dojo.html.styleSheet.insertRule) { // W3
var rule = selector + " { " + declaration + " }";
return dojo.html.styleSheet.insertRule(rule, index); // integer
} else if (dojo.html.styleSheet.addRule) { // IE
return dojo.html.styleSheet.addRule(selector, declaration, index); // integer
} else {
return null; // integer
} // fail
}

dojo.html.removeCssRule = function(/* integer? */index){
// summary
// Attempt to remove the rule at index.
if(!dojo.html.styleSheet){
dojo.debug("no stylesheet defined for removing rules");
return false;
}
if(dojo.render.html.ie){
if(!index){
index = dojo.html.styleSheet.rules.length;
dojo.html.styleSheet.removeRule(index);
}
}else if(document.styleSheets[0]){
if(!index){
index = dojo.html.styleSheet.cssRules.length;
}
dojo.html.styleSheet.deleteRule(index);
}
return true; // boolean
}

dojo.html._insertedCssFiles = []; // cache container needed because IE reformats cssText when added to DOM
dojo.html.insertCssFile = function(/* string */URI, /* HTMLDocument? */doc, /* boolean? */checkDuplicates, /* boolean */fail_ok){
// summary
// calls css by XmlHTTP and inserts it into DOM as
if(!URI){ return; }
if(!doc){ doc = document; }
var cssStr = dojo.hostenv.getText(URI, false, fail_ok);
if(cssStr===null){ return; }
cssStr = dojo.html.fixPathsInCssText(cssStr, URI);

if(checkDuplicates){
var idx = -1, node, ent = dojo.html._insertedCssFiles;
for(var i = 0; i < ent.length; i++){
if((ent[i].doc == doc) && (ent[i].cssText == cssStr)){
idx = i; node = ent[i].nodeRef;
break;
}
}
// make sure we havent deleted our node
if(node){
var styles = doc.getElementsByTagName("style");
for(var i = 0; i < styles.length; i++){
if(styles[i] == node){
return;
}
}
// delete this entry
dojo.html._insertedCssFiles.shift(idx, 1);
}
}

var style = dojo.html.insertCssText(cssStr, doc);
dojo.html._insertedCssFiles.push({'doc': doc, 'cssText': cssStr, 'nodeRef': style});

// insert custom attribute ex dbgHref="../foo.css" usefull when debugging in DOM inspectors, no?
if(style && djConfig.isDebug){
style.setAttribute("dbgHref", URI);
}
return style; // HTMLStyleElement
}

dojo.html.insertCssText = function(/* string */cssStr, /* HTMLDocument? */doc, /* string? */URI){
// summary
// Attempt to insert CSS rules into the document through inserting a style element
// DomNode Style = insertCssText(String ".dojoMenu {color: green;}"[, DomDoc document, dojo.uri.Uri Url ])
if(!cssStr){
return; // HTMLStyleElement
}
if(!doc){ doc = document; }
if(URI){// fix paths in cssStr
cssStr = dojo.html.fixPathsInCssText(cssStr, URI);
}
var style = doc.createElement("style");
style.setAttribute("type", "text/css");
// IE is b0rken enough to require that we add the element to the doc
// before changing it's properties
var head = doc.getElementsByTagName("head")[0];
if(!head){ // must have a head tag
dojo.debug("No head tag in document, aborting styles");
return; // HTMLStyleElement
}else{
head.appendChild(style);
}
if(style.styleSheet){// IE
var setFunc = function(){
try{
style.styleSheet.cssText = cssStr;
}catch(e){ dojo.debug(e); }
};
if(style.styleSheet.disabled){
setTimeout(setFunc, 10);
}else{
setFunc();
}
}else{ // w3c
var cssText = doc.createTextNode(cssStr);
style.appendChild(cssText);
}
return style; // HTMLStyleElement
}

dojo.html.fixPathsInCssText = function(/* string */cssStr, /* string */URI){
// summary
// usage: cssText comes from dojoroot/src/widget/templates/Foobar.css
// it has .dojoFoo { background-image: url(images/bar.png);} then uri should point to dojoroot/src/widget/templates/
if(!cssStr || !URI){ return; }
var match, str = "", url = "", urlChrs = "[\\t\\s\\w\\(\\)\\/\\.\\\\'\"-:#=&?~]+";
var regex = new RegExp('url\\(\\s*('+urlChrs+')\\s*\\)');
var regexProtocol = /(file|https?|ftps?):\/\//;
regexTrim = new RegExp("^[\\s]*(['\"]?)("+urlChrs+")\\1[\\s]*?$");
if(dojo.render.html.ie55 || dojo.render.html.ie60){
var regexIe = new RegExp("AlphaImageLoader\\((.*)src\=['\"]("+urlChrs+")['\"]");
// TODO: need to decide how to handle relative paths and AlphaImageLoader see #1441
// current implementation breaks on build with intern_strings
while(match = regexIe.exec(cssStr)){
url = match[2].replace(regexTrim, "$2");
if(!regexProtocol.exec(url)){
url = (new dojo.uri.Uri(URI, url).toString());
}
str += cssStr.substring(0, match.index) + "AlphaImageLoader(" + match[1] + "src='" + url + "'";
cssStr = cssStr.substr(match.index + match[0].length);
}
cssStr = str + cssStr;
str = "";
}

while(match = regex.exec(cssStr)){
url = match[1].replace(regexTrim, "$2");
if(!regexProtocol.exec(url)){
url = (new dojo.uri.Uri(URI, url).toString());
}
str += cssStr.substring(0, match.index) + "url(" + url + ")";
cssStr = cssStr.substr(match.index + match[0].length);
}
return str + cssStr; // string
}

dojo.html.setActiveStyleSheet = function(/* string */title){
// summary
// Activate style sheet with specified title.
var i = 0, a, els = dojo.doc().getElementsByTagName("link");
while (a = els[i++]) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")){
a.disabled = true;
if (a.getAttribute("title") == title) { a.disabled = false; }
}
}
}

dojo.html.getActiveStyleSheet = function(){
// summary
// return the title of the currently active stylesheet
var i = 0, a, els = dojo.doc().getElementsByTagName("link");
while (a = els[i++]) {
if (a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("title")
&& !a.disabled
){
return a.getAttribute("title"); // string
}
}
return null; // string
}

dojo.html.getPreferredStyleSheet = function(){
// summary
// Return the preferred stylesheet title (i.e. link without alt attribute)
var i = 0, a, els = dojo.doc().getElementsByTagName("link");
while (a = els[i++]) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
){
return a.getAttribute("title"); // string
}
}
return null; // string
}

dojo.html.applyBrowserClass = function(/* HTMLElement */node){
// summary
// Applies pre-set class names based on browser & version to the passed node.
// Modified version of Morris' CSS hack.
var drh=dojo.render.html;
var classes = {
dj_ie: drh.ie,
dj_ie55: drh.ie55,
dj_ie6: drh.ie60,
dj_ie7: drh.ie70,
dj_iequirks: drh.ie && drh.quirks,
dj_opera: drh.opera,
dj_opera8: drh.opera && (Math.floor(dojo.render.version)==8),
dj_opera9: drh.opera && (Math.floor(dojo.render.version)==9),
dj_khtml: drh.khtml,
dj_safari: drh.safari,
dj_gecko: drh.mozilla
}; // no dojo unsupported browsers
for(var p in classes){
if(classes[p]){
dojo.html.addClass(node, p);
}
}
};

mercredi 6 octobre 2010

java : weblogic script commandes via API console

Voici un résumé des commandes weblogic (lorsque l'on fonctionne en mode managé et que le serveur d'administration serveurAdmin est lancé)


java weblogic.Admin -url monNomDeServeur:11131 -username weblogic -password secret ALL


Voici, un Arret forcé sans attente des déconnexion des users (par opposition au gracefull shutdown)

java weblogic.Admin -url monNomDeServeur:11131 -username weblogic -password secret FORCESHUTDOWN valo


Voici le lancement d'une commande START à un serveur "serveurAdmin" pour démarrer un serveur nommé "monNomDeServeur"

java weblogic.Admin -url monNomDeServeur:11131 -username weblogic -password secret START valo



Une autre méthode qui passe par le node manager,et est parfois utilisée mais ne fonctionne pas bien

java -Dweblogic.Name=bocorchestre -Dweblogic.management.server.url=cronos:11131 weblogic.Server >/var/TRACES/wlsbod3/bocorchestre.log &




Usage: java [] weblogic.Admin
[ [-url | -adminurl] [://]:]
-username [-password ]



Where commands and arguments are:

********** Managing the Server Life Cycle **********

UNLOCK
RESUME []
FORCESHUTDOWN []
SHUTDOWN [-ignoreExistingSessions] [-timeout ] []
OR
(Deprecated) SHUTDOWN [ [""]] []
LOCK [""]
START
(Deprecated) STARTINSTANDBY
DISCOVERMANAGEDSERVER [-serverName [-listenPort ] [-listenAddress ] [-listenPortSecure]]

********** Retrieving Information about WebLogic Server **********

GETSTATE []
HELP []
CONNECT []
LICENSES
LIST []
PING [] []
THREAD_DUMP
VERSION
SERVERLOG [ []]

********** Working with JDBC Connection Pools **********

SUSPEND_POOL -poolName
(Deprecated) DISABLE_POOL -poolName [true | false]
RESET_POOL -poolName
CREATE_POOL
(Deprecated) DESTROY_POOL [true | false]
SHUTDOWN_POOL -poolName
RESUME_POOL -poolName
TEST_POOL -poolName
EXISTS_POOL -poolName
(Deprecated) ENABLE_POOL -poolName
DELETE_POOL -poolName

********** Managing WebLogic Server MBeans **********

GET [-pretty] {-type |-mbean } [-property ]...
CREATE {-name -type } | {-mbean }
INVOKE {-type |-mbean }
-method [...]
BATCHUPDATE -batchFile [-continueOnError] [-batchCmdVerbose]
DELETE {-type | -mbean }
QUERY [-pretty] -pattern
SET {-type |-mbean } [-property []]...

********** Working with Clusters **********

VALIDATECLUSTERCONFIG -configPath
CLUSTERSTATE -clusterName
STOPCLUSTER -clusterName
MIGRATE [-jta] -migratabletarget { | } -destination [-sourcedown] [-destinationdown]
STARTCLUSTER -clusterName

********** Managing the Admin Configuration **********

STOREUSERCONFIG -username -password [-userconfigfile ] [-userkeyfile ]**************** SSL Trust Options **************** If the domain-wide administration port is enabled, or if you are connecting to a server through some other SSL port, you might need to include Java options to indicate which host the weblogic.Admin utility trusts. For example, if the server to which you are connecting is using the demonstration SSL keys and certificates, you must include the TrustKeyStore option as follows: java -Dweblogic.security.TrustKeyStore=DemoTrust weblogic.Admin [<...>] For more information, refer to the WebLogic Server security documentation.

mardi 5 octobre 2010

javascript : petits et divers exemples



<script type="text/javascript" language="javascript">
function etatModifie(obj, numLigne){
obj.className = "CelluleLineModifiee";
document.getElementById("boutonModifier_" + numLigne).src = "img/gif/ico_enregistrer_on.gif";
document.getElementById("boutonModifier_" + numLigne).className = 'boutonActive';
/* document.getElementById("boutonModifier_" + numLigne).onclick=function() {
document.forms[0].dispatch.value = "onModifier";
args = createArgsArrayModification(document.forms[0], numLigne);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
};*/
document.getElementById("modifiee_" + numLigne).value = '1';
}

function etatModifieVerifDate(obj, numLigne){
var ok

if(obj.value == "") {
ok = 1;
}
else {
ok = CheckDate(obj);
}
if(ok == 1) {
if(numLigne != -1) {
obj.className = "CelluleLineModifiee";
document.getElementById("boutonModifier_" + numLigne).src = "img/gif/ico_enregistrer_on.gif";
document.getElementById("boutonModifier_" + numLigne).className = 'boutonActive';
document.getElementById("modifiee_" + numLigne).value = '1';
}
/*document.getElementById("boutonModifier_" + numLigne).onclick=function() {
document.forms[0].dispatch.value = "onModifier";
args = createArgsArrayModification(document.forms[0], numLigne);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
};*/

}
else {
if(numLigne != -1) {
obj.className = "CelluleErronee";
document.getElementById("boutonModifier_" + numLigne).src = "img/gif/ico_enregistrer_off.gif";
document.getElementById("boutonModifier_" + numLigne).className = 'boutonDesactive';
document.getElementById("modifiee_" + numLigne).value = '0';
}
else {
obj.className = "CelluleNewErronee";
}
}
}

function openPopup(url, popW, popH){
var winleft = (screen.width - popW) / 2;
var winUp = (screen.height - popH) / 2;
popup = window.open(url, '1', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=1,width='+popW+',height='+popH+',left='+winleft+',top='+winUp);
popup.resizeTo(popW,popH);
popup.focus();
}

function log(){
document.forms[0].dispatch.value = "onValider";
document.forms[0].submit();
return false;
}

function majChamps(){
if(document.getElementById("champs") != null) {
var str = "";
var strChoix = document.getElementById("choix").value;
var i = 0;



if(strChoix == "ReseauDium") {
if( "Réseau Ferroviaire" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "ReseauDium") {
if( "Libellé" != "") {
i++;
str = str + '&nbsp;Libellé :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "ReseauDium") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "ReseauDium") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "Réseau Ferroviaire" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "Code Gare" != "") {
i++;
str = str + '&nbsp;Code Gare :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "Libellé" != "") {
i++;
str = str + '&nbsp;Libellé :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "Zone géographique" != "") {
i++;
str = str + '&nbsp;Zone géographique :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "GaresDium") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "Réseau Ferroviaire" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "Point Frontière" != "") {
i++;
str = str + '&nbsp;Point Frontière :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "Libellé" != "") {
i++;
str = str + '&nbsp;Libellé :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "Zone géographique" != "") {
i++;
str = str + '&nbsp;Zone géographique :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "PtsFront") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "Réseau Ferroviaire Gare" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire Gare :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "Gare" != "") {
i++;
str = str + '&nbsp;Gare :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "Réseau Ferroviaire PF" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire PF :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "PF" != "") {
i++;
str = str + '&nbsp;PF :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistGares") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "Réseau Ferroviaire Entrant" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire Entrant :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "PF Entrant" != "") {
i++;
str = str + '&nbsp;PF Entrant :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "Réseau Ferroviaire Sortant" != "") {
i++;
str = str + '&nbsp;Réseau Ferroviaire Sortant :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "PF Sortant" != "") {
i++;
str = str + '&nbsp;PF Sortant :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistPF") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "Etablissement Ferroviaire" != "") {
i++;
str = str + '&nbsp;Etablissement Ferroviaire :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "Lieu" != "") {
i++;
str = str + '&nbsp;Lieu :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "Distance" != "") {
i++;
str = str + '&nbsp;Distance :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "GRF" != "") {
i++;
str = str + '&nbsp;GRF :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatAddi") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatGrf") {
if( "GRF 1" != "") {
i++;
str = str + '&nbsp;GRF 1 :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatGrf") {
if( "GRF 2" != "") {
i++;
str = str + '&nbsp;GRF 2 :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatGrf") {
if( "Distance" != "") {
i++;
str = str + '&nbsp;Distance :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatGrf") {
if( "Date de validité" != "") {
i++;
str = str + '&nbsp;Date de validité :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}

if(strChoix == "DistNatGrf") {
if( "" != "") {
i++;
str = str + '&nbsp; :&nbsp;<input type="text" name="input' + i + '"/>&nbsp';
}
else {
i++;
str = str + '<input type="hidden" name="input' + i + '" value="">';
}
}



document.getElementById("champs").innerHTML = str;
}
return false;
}

function makeRequest(type) {
if(type == 'recherche') {
// mise à jour de la variable contenant le type de donnée actuellement affiché

document.forms[0].typeDonneesAffichees.value = document.forms[0].choix.value;

document.forms[0].dispatch.value = "onValider";
args = createArgsArrayRecherche(document.forms[0]);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
}
else if(type == 'ajout') {
document.forms[0].dispatch.value = "onAjouter";
args = createArgsArrayAjout(document.forms[0]);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
}
}

function makeRequestAjout() {
document.forms[0].dispatch.value = "onAjouter";
args = createArgsArrayAjout(document.forms[0]);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);

}

function makeRequestModification(ligne) {
if(document.getElementById("modifiee_" + ligne).value == '1') {
document.forms[0].dispatch.value = "onModifier";
args = createArgsArrayModification(document.forms[0], ligne);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
}
}

function makeRequestSuppression(ligne) {
document.forms[0].dispatch.value = "onSupprimer";
args = createArgsArrayModification(document.forms[0], ligne);
sendRequest("/bocreferentiel/accueilReferentiel.do", args);
}

function CheckDate(d) {
// Cette fonction vérifie le format JJ/MM/AAAA saisi et la validité de la date.
// Le séparateur est défini dans la variable separateur


if(d.value != null && d.value != "") {

var amin=1980; // année mini

var amax=2099; // année maxi

var separateur="/"; // separateur entre jour/mois/annee

var j=(d.value.substring(0,2));
var m=(d.value.substring(3,5));
var a=(d.value.substring(6));
var ok=1;
if ( ((isNaN(j))||(j<1)||(j>31)) && (ok==1) ) {
alert("Le jour n'est pas correct, date non valide.\nEntrez une date valide ou supprimez cette valeur avant de poursuivre."); ok=0;
}
if ( ((isNaN(m))||(m<1)||(m>12)) && (ok==1) ) {
alert("Le mois n'est pas correct, date non valide.\nEntrez une date valide ou supprimez cette valeur avant de poursuivre."); ok=0;
}
if ( ((isNaN(a))||(a<amin)||(a>amax)) && (ok==1) ) {
alert("L'année n'est pas correcte, date non valide.\nEntrez une date valide ou supprimez cette valeur avant de poursuivre."); ok=0;
}
if ( ((d.value.substring(2,3)!=separateur)||(d.value.substring(5,6)!=separateur)) && (ok==1) ) {
alert("Les séparateurs doivent être des "+separateur+".\nEntrez une date valide ou supprimez cette valeur avant de poursuivre."); ok=0;
}
if (ok==1) {
var d2=new Date(a,m-1,j);
j2=d2.getDate();
m2=d2.getMonth()+1;
a2=d2.getFullYear();
if (a2<=100) {a2=1900+a2}
if ( (j!=j2)||(m!=m2)||(a!=a2) ) {
alert("La date "+d.value+" n'existe pas.\nEntrez une date valide ou supprimez cette valeur avant de poursuivre.");
ok=0;
}
}
return ok;
}
}
function CheckDateFocus(d) {
// Cette fonction donne le focus à l'input d si la date qu'il contient n'est

// pas valide

// Le séparateur est défini dans la variable separateur


if(d.value != null && d.value != "") {

var amin=1980; // année mini

var amax=2099; // année maxi

var separateur="/"; // separateur entre jour/mois/annee

var j=(d.value.substring(0,2));
var m=(d.value.substring(3,5));
var a=(d.value.substring(6));
var ok=1;
if ( ((isNaN(j))||(j<1)||(j>31)) && (ok==1) ) {
ok=0;
}
if ( ((isNaN(m))||(m<1)||(m>12)) && (ok==1) ) {
ok=0;
}
if ( ((isNaN(a))||(a<amin)||(a>amax)) && (ok==1) ) {
ok=0;
}
if ( ((d.value.substring(2,3)!=separateur)||(d.value.substring(5,6)!=separateur)) && (ok==1) ) {
ok=0;
}
if (ok==1) {
var d2=new Date(a,m-1,j);
j2=d2.getDate();
m2=d2.getMonth()+1;
a2=d2.getFullYear();
if (a2<=100) {a2=1900+a2}
if ( (j!=j2)||(m!=m2)||(a!=a2) ) {
ok=0;
}
}
if (ok == 0) {
alert("Date invalide. Entrez une date valide ou supprimez cetta valeur avant de poursuivre.");
d.focus();
}
return ok;
}
}
</script>