avr

23

Posted by : admin | On : 23 avril 2012

Source

http://www.careerride.com/Spring-bean-lifecycle-in-spring-framework.aspx

Question/response  JAVA

Spring

What is Spring?

Spring is a framework that resolves common problems in JEE architecture. (JDBC ,integration later, presentation layer …)
Spring is managing business objects and encouraging practices POJO model (vs programming model)
It’s highly recommended to use a architectural tiers  (presentation,business,dao Layer) ; the inejection of the different beans is realized by utilizing IoC.
Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation. Spring is also an ideal framework for test driven projects.

  • The most common modules are :
  1. Most use module : Spring core, Spring test, Spring jdbc
  2. Advanced module :  Spring AOP ,Spring integration , Spring batch

Bean lifecycle in Spring framework.

The bean’s definition is found by the spring container from the XML file and instantiates the bean.

All the properties specified in the bean definition are populated by spring using dependency injection.

 

The bean’s Id is passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase the bean implements the BeanFactoryAware interface.

The init() method is invoked if specified. If any BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.

Thread in JAVA

http://www.careerride.com/Interview-Questions-Java-Threading.aspx

2 type of process are being execute in a PC

les multitache  par processus + long pour le CPU de réaliser le swap entre les différents applicatif .

Le multitache par thread

class MonThread implements Runnable {
	Thread t ;
	MonThread("Mon thread "){
		t = new Thread("Mon thread");
		t.start();
	}
	public void run(){
		System.out.println("Thread enfant démarré");
	}

	public static void main(String args[]){
		new MonThread();
		System.out.println("Thread principale démarré ");
		System.out.println("Thread principale terminé ");
	}
}

l’instruction join() permet d’attendre le thread enfant se termine et qu’il rejoinne le thread principale . (exemple le thread du main)

permettre à deux thread de ne pas accéder à la même ressource en même temps on utilise pour cela le mot clé synchronized dans le prototype de la méthode.Souvent cela arrive lorsque 1 thread => appel 1 methode d’une autre classe Exemple :

class  MonThread implements Runnable (){
	String s1 ;
	Parenthese p1;
	Thread t ;
	public MonThread(Parenthese p2 , String s2){
		p1 = p2 ;
		s1 = s2 ;
		t = new Thread(this);
		t.start();
	}
	public void run(){
		p1.afficher(); // La méthode affficher doit être nécessairement en synchronized
	}
}

Une méthode peut etre appellé à l’intérieur d’un bloc synchronizé ( les objets et les methodes sont synchronisés ) Les appels aux méthodes contenues dans le bloc synchronisé n’ont lieu qu’après que le threade a activé le moniteur sur objet L’instruction synchronized

 

public void run(){
	synchronized(p1){
		p1.afficher();
	}
}

 

Communication entre les threads wait() demande à un thread de libérer un moniteur et de se placer en suspens .notify() demande au thread suspendu de se remettre en marche et de reprendre le contrôle du moniteur

 

class MonThread implements Runnable {
	Thread t;

	MonThread(String threadName) {
		// t = new Thread(threadName);
		// t.start();
	}

	public void run() {
		System.out.println("RUN Child thread :" + Thread.currentThread());
	}

	public static void main(String args[]) throws InterruptedException {
		Thread thread1 = new Thread(new MonThread("thread1"), "thread1");
		Thread thread2 = new Thread(new MonThread("thread2"), "thread2");
		thread1.start();
		thread2.start();

		thread1.join();
		if (!thread1.isAlive()) {
			System.out.println("Thread T1 is not alive.");
		}
		thread2.join();
		if (!thread2.isAlive())
			System.out.println("Thread T2 is not alive.");

		Thread.currentThread().sleep(2000);
		System.out.println(Thread.currentThread());

	}
}

RUN Child thread :Thread[thread1,5,main]

RUN Child thread :Thread[thread2,5,main]

Thread T1 is not alive.Thread T2 is not alive.

Thread[main,5,main]

package coordination;

public class AutoBus extends Thread {
	int total = 0;

	public void run() {
		synchronized (this) {
			System.out.println("wait ...");
			for (int i = 0; i < 100; i++)
				total = +i;
			System.out.println("passenger is given notification call ");
			notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		AutoBus bus = new AutoBus();
		bus.start();
		synchronized (bus) {
			System.out.println(" passenger is waiting for the bus");
			bus.wait();
			System.out.println("passenger go notification");
		}
		System.out.println(" total=" + bus.total);
	}
}

passenger is waiting for the buswait …

passenger is given notification call passenger go notification total=99

Example questions :

how to create a thread and start it running
Example 1 : Extending Thread Class

Example 2 : implentation Runnable

Explain how do we allow one thread to wait while other to finish.

When a thread is created and started, what is its initial state?
Ready for execution (Create + started )
A thread is in “Ready” state after it has been created and started.
This state signifies that the thread is ready for execution. From here, it can be in the running state.

explain monitor in java

mot clé synchronization

What is serializable Interface?

If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs to be serialized.

 

 

EJB

EJB is a standard for developing server side in JAVA. It specifies agreement between components and application servers that allows components to run on server. They are mainly for complex serer side operations like executing complex algorithm or high volume business. EJB provides the application layer logic, also called as middle tier. It provides a standard specifications-based way to develop and deploy enterprise-class system.

What are the kinds of EJB’s?

There are 3 kinds of EJB’s -

  1. Session beans,
  2. Entity Beans
  3. Message-driven beans

 

  • Session beans

Sessions beans represent business logic of an application. Session beans can be of 2 types namely stateless and stateful beans

  • Entity Beans

Entity beans represent persistent data in an EJB application.

  • Message-driven beans

This type of beans is used implement asynchronous communication in the system.

Stateful

The state of the conversation can be maintained using a stateful session bean.
It implements ‘javax.ejb.SessionBean’ interface and is deployed with the declarative attribute ‘stateful’.
The instance variables contain a state only during the invocation by a client method.
The bean can use the conversational states as its business process methods.

Main cons: Resources that is needed to be substain to maintain connection between server and client
Other discussion pro/cons :

http://blog.xebia.fr/2007/07/24/service-stateful-vs-service-stateless/

Stateless

We dont maintain conversational state specific to client session.
It is an EJB component that implements ‘javax.ejb.SessionBean’ interface.
The stateless session bens carry equal value for all the instances due to which a container can assign a bean to any client making it very scalable.
There is no instance state. The business methods on a stateless session bean are like procedural applications or static methods, so all the data needed to execute the method is provided by the method arguments.
Stateless session beans are very lightweight and fast.Typically an application requires less number of stateless beans compared to stateful beans.

What is lazy loading?

Heavy weight application consume a lot of time while loading the plug-ins. In lazy loading approach, the plug-ins that are needed at that particular time are loaded and instantiated. This boosts up the performance as only the plug-ins that are used are loaded. This also ensures the efficiency and speeds up the initial load time of the applications. Applications like Eclipse use this approach. In other words, the goal of lazy loading is to dedicate memory only when it is absolutely necessary.

Difference between a Server, a Container, and a Connector?

-A server is an application that responds to the requests made by client(s) and manages system resources like network connections, threads, processes, memory, database connections, etc
E.g.: Websphere,Jonas,BEA WebLogic …
-A server can contain N number of containers. An EJB container runs inside an EJB server. The Container shields the EJB server through an API between the bean and its container.
-A connector is used to resolve the issue with the legacy systems. A connector is an architecture defined by Sun. Since the applications running on the legacy systems cannot be discarded due to the business logic and other reasons, the connectors were used to serve the purpose.
(exemple connector : Oracle, Mysql,Postgre …)

 

Packaging :

What is the difference between EAR, JAR and WAR file?

Modules are packaged based on their functionality as EAR, JAR and WAR files.

• JAR files (.jar):Modules which contain EJB class files and EJB deployment descriptor are packed as JAR files.
WAR Files (.war):Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as JAR file.
EAR Files (.ear):‘.jar’ & ‘.war’ files are packaged as JAR files. ‘Ear’ stands for enterprise archive. These files are deployed in the application server.

 

Révision Java

Variables en Java

  • Variable instance ont pour durée de vie celle de l’objet
  • Variable de classe sont mis en place quand les classes sont dites chargées .
  • Variable locales celle d’une fonction

 

Flux

Java.io

Flux entrée System.in .

Remarque : Depuis Java 5 la classe Scanner permet de lire les entrées clavier facilement

Scanner scanner = new Scanner(System.in);

String choix = scanner.next();

Flux de sortie : System.out

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

nom = br.readLine();

 

mot clé static

on peut appeler la méthode d’un objet sans avoir à instancier celui ci

On l’utilise le plus souvent lorsque l’objet n’a pas de rapport à proprement dit avec la classe

disposer d’information collectives (exemple : comptage instance de classe )

ou bien disposer de fonction indépendante

 

bloc static

n’ont accès qu’au champs static de la classe

utilise surtout pour initialiser des champs static

=> Conseil mieux vaut avoir un private static methode pour avoir la main sur nos variables facilement

 

Clonage

recopie les références de l’objet mais ne provoquue pas la recopie des valeur des objets .

 

compare

== et !=

ne compare les objets que sur les reférences , peut être utilisé pour comparer des références null , 2 énum values …

a.compareTo(b) compare les values des champs a et b et retourne un int issu de la comparaison

=> penser aussi au pattern Iterator et à la classe Comparator<T>

 

La rammasse miette en java

Lors un objet ne possède plus de référence sur cet objet on dit qu’il est candidat au gargage collector

finalize() est appellé par le garbage collector quand la condition précédente est vérifié

 

Classe anonymes

permet de définir une classe sans lui donner de nom

pas de référence possible

classe anonyme peut dériver d’une autre classe (exemple de la classe JpaTemplate )

classe anonyme implémentant une interface

 

Héritage

le constructeur dérivée (fille) doit prendre en charge l’intégralité de la contruction du père.

ou bien utiliser le mot clé super() pour ne pas avoir à redéfinir les fonctionnalités et disposé de celle défini dans la classe mère.

 

Polymorphisme

complète l’héritage , peut prendre plusieurs formes ou comportement suivant les situations .

différentes formes de polymorphisme

méthode

classe

polymorphisme via heritage (on spécialise un comportement )

String … elements <=> String [] elements

 

final

interdit la modification de la valeur (variable )

méthode final ne peuvent être redéfini par une classe dérivée

classe final idem

 

classe abstraites

pas instancation objet possible

contient les méthodes et champs dont héritera toutes les classes dérivées

 

Exception

des erreur peuvent se produire on les gère… gestion des exceptions

Java.lang.Throwable

|

exception                                  java.lang.error

Runtime      SQLException/IOException

NPE

SeccurityException

 

Manipulation des chaines de caractères

StringBuffer

StringTokenizer

matcher

Java 5

  • prommation générique
  • annotation
  • autoboxing /unboxing (conversion auto des types )
  • énumération
  • nouvelles classes (scanner , formatter …)
  • Java concurrency

 

 

Collection en Java

  • Vecteur : ensemble objet pouvant être retrouvé par leur référence
  • Liste : ensemble objet classé par leur position
  • Ensembles : ensemble objet classé par leur type
  • Table de hashage :  ensemble objet classé à l’aide d’une clé
  • Pile : ensemble objet classé pouvant être simplement posé ou retiré

List

doublon autorisé

récupération via index

LinkedList (liste doublement chainée )

ArrayList (tableau redimensionnable)

Vector ( la différence avec ArrayList est qu’elle est synchronisé durant l’appel de la méthode de cette classe par un thread autre et ne peut être modifier )

 

Map

clé /valeur

unicité de la clé

HashTable va recherche ses éléments avec hashCode

HashTable est ThreadSafe et n’accepte pas null

 

HashMap n’est poas ThreadSafe

 

Set

n’accepte pas les doublons

HahsSet permet de stocker des objets sans doublons , n’accepte pas d’objet null (sinon NPE) => Iterator

 

TreeSet utilise un arbre de recherche

SortedSet

 

Pile

pop/push

 

Iterator

List<String> maListe = new ArrayList<String>();

maListe.add(« Bonkour »);

Iterator<String> it= maListe.iterator();

while(it.hasNext()){

sysout(it.next());

}

parcours HashMap

for(Key key : map.keySet()){}

 

SQL

inner join

relation 1-1 entre 2 tables

exemple :

Select * from Employee inner join departement on employee.DepartementID=departement.DepartementID

natural join : jointure faites sur les tables de même nom

Left / right join (favoriser une ou autre des tables)

Toutes les valeur de  A et les valeurs de B qui matche avec A

cela se traduit en clair quelquesoit ….. who is in

 

jan

10

Posted by : admin | On : 10 janvier 2012

Rss Reader

Bellow a Simple code about how to make a simple Rss Reader handle by SAX handler.



package mapping.rss;

public class Item {
	private String title ;
	private String description;
	private String link;
	private String pubDate;
	private String source;
	private String mediaContent;
	private String mediaText;
	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}
	/**
	 * @param title the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}
	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}
	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * @return the link
	 */
	public String getLink() {
		return link;
	}
	/**
	 * @param link the link to set
	 */
	public void setLink(String link) {
		this.link = link;
	}
	/**
	 * @return the pubDate
	 */
	public String getPubDate() {
		return pubDate;
	}
	/**
	 * @param pubDate the pubDate to set
	 */
	public void setPubDate(String pubDate) {
		this.pubDate = pubDate;
	}
	/**
	 * @return the source
	 */
	public String getSource() {
		return source;
	}
	/**
	 * @param source the source to set
	 */
	public void setSource(String source) {
		this.source = source;
	}
	/**
	 * @return the mediaContent
	 */
	public String getMediaContent() {
		return mediaContent;
	}
	/**
	 * @param mediaContent the mediaContent to set
	 */
	public void setMediaContent(String mediaContent) {
		this.mediaContent = mediaContent;
	}
	/**
	 * @return the mediaText
	 */
	public String getMediaText() {
		return mediaText;
	}
	/**
	 * @param mediaText the mediaText to set
	 */
	public void setMediaText(String mediaText) {
		this.mediaText = mediaText;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Item [title=");
		builder.append(title);
		builder.append(", description=");
		builder.append(description);
		builder.append(", link=");
		builder.append(link);
		builder.append(", pubDate=");
		builder.append(pubDate);
		builder.append(", source=");
		builder.append(source);
		builder.append(", mediaContent=");
		builder.append(mediaContent);
		builder.append(", mediaText=");
		builder.append(mediaText);
		builder.append("]");
		return builder.toString();
	}

}

package xml;

import java.util.ArrayList;
import java.util.List;

import mapping.rss.Item;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SearchItemRssHandler extends DefaultHandler {
	private final static String CHANNEL="channel";
	private final static String ITEM="item";
	private final static String TITLE="title";
	private final static String LINK="link";
	private final static String DESCRIPTION="description";
	private final static String SOURCE="source";
	private final static String PUBDATE="PUBDATE";

	private boolean bfChannel = false;
	private boolean bfItem = false;
	private boolean bfTitle = false;
	private boolean bflink = false ;
	private boolean bfDescription = false ;
	private boolean bfSource = false ;
	private boolean bfPubdate = false; 

	private Item item ;
	private List<Item> items ;
	public void startElement(String uri, String localName,String qName,
			Attributes attributes) throws SAXException {
		if(qName.equalsIgnoreCase(CHANNEL)){
			items = new ArrayList<Item>();
			bfChannel = true;
		}
		if(qName.equalsIgnoreCase(ITEM)){
			item = new Item();
			bfItem = true ;
		}
		if(qName.equalsIgnoreCase(TITLE)){
			bfTitle = true ;
		}
		if(qName.equalsIgnoreCase(LINK)){
			bflink = true ;
		}
		if(qName.equalsIgnoreCase(PUBDATE)){
			bfPubdate = true ;
		}
		if(qName.equalsIgnoreCase(SOURCE)){
			bfSource = true ;
		}
		if(qName.equalsIgnoreCase(DESCRIPTION)){
			bfDescription = true ;
		}

	}
	public void endElement(String uri, String localName,
			String qName) throws SAXException {
		if(qName.equalsIgnoreCase(ITEM)){
			items.add(item);
			bfItem = false;
		}
		if(qName.equalsIgnoreCase(CHANNEL)){
			setItems(items);
			bfChannel = false ;
		}
	}
	public void characters(char ch[], int start, int length) throws SAXException {
		String resu= new String(ch, start, length);
		if(bfItem){
			bfItem = false;
		}
		if(bfDescription){
			if(item!=null)
			item.setDescription(resu);
			bfDescription = false;
		}
		if(bfTitle){
			if(item!=null)
			item.setTitle(resu);
			bfTitle = false;
		}
		if(bflink){
			if(item!=null)
			item.setLink(resu);
			bflink = false ;
		}
		if(bfPubdate){
			if(item!=null)
			item.setPubDate(resu);
			bfPubdate = false;
		}
		if(bfSource){
			if(item!=null)
			item.setSource(resu);
		}
	}
	/**
	 * @return the items
	 */
	public List<Item> getItems() {
		return items;
	}
	/**
	 * @param items the items to set
	 */
	public void setItems(List<Item> items) {
		this.items = items;
	}
}

///TEST Main 

package xml.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mapping.rss.Item;

import org.xml.sax.InputSource;

import xml.SearchItemRssHandler;

public class ReadRssXmlFile {
	public static void main(String argv[]) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();

			File file = new File("C:\\workspace\src\\rss-test-fr.xml");
			InputStream inputStream= new FileInputStream(file);
			Reader reader = new InputStreamReader(inputStream,"UTF-8");

			InputSource is = new InputSource(reader);
			is.setEncoding("UTF-8");

			SearchItemRssHandler handler = new SearchItemRssHandler();
			saxParser.parse(is, handler);
			List<Item> items  = handler.getItems();
			for (Item item : items) {
				System.out.println(item);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

oct

24

Posted by : admin | On : 24 octobre 2011

  1. Dans cette section nous allons nous attacher  d’installer la JDK et la JRE sur une environnement Linux (testé sur ubuntu)
  2. Dans la section suivante j’explique comment installer Maven 2 et son plugin sur Eclipse
  3. Enfin j’expose dans la dernière section le couplage de Maven 2 et de Ant . Nous pouvons imaginer par exemple que nous souhaitons « builder » notre projet et les déployer automatiquement sur la plateforme distante avec le moins d’effort possible . Nous allons donc voir dans cette section comment le couplage de ces deux technologies concorde dans la réponse à ce besoin .

 

 

Install JDK /JRE

 

  • Download JRE 6 :

http://java.com/fr/download/manual.jsp

mv jre-6u18* jre-6u18-linux-i586.bin
sudo mv ./jre-6u18-linux-i586.bin /opt/
cd /opt/
chmod +x jre-6u18-linux-i586.bin
sudo ./jre-6u18-linux-i586.bin</pre>
ln -sf /opt/java/jdkX.X.X_u/ /opt/java/jdk
ln -sf /opt/java/jreX.X.X_u/ /opt/java/jre
ln -sf /opt/java/jdkX.X.X_u/ /opt/java/default
echo "" >> /etc/profile
echo "#JAVA" >> /etc/profile
echo "JRE_HOME=/opt/java/jre" >> /etc/profile
echo "JDK_HOME=/opt/java/jdk" >> /etc/profile
echo "JAVA_HOME=/opt/java/default" >> /etc/profile
echo "export JRE_HOME JDK_HOME JAVA_HOME" >> /etc/profile
  1. Reconfigurer le java de votre machine si nécessaire:
sudo update-alternatives --config java
cd ~
ls -al

editer le bashrc

export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun-1.5.0.06 export PATH=$PATH:$JAVA_HOME/bin

# set PATH so it includes user's private bin if it exists

if [ -d ~/bin ] ; then

PATH=~/bin:"${PATH}"

fi

export JAVA_HOME=”/usr/lib/jvm/java-6-openjdk/″

export JDK_HOME=”${JAVA_HOME}”

export PATH=”${JAVA_HOME}/bin:${PATH}”

fi
export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1

export M2=$M2_HOME/bin

export MAVEN_OPTS="-Xms512m -Xmx1024m"

export PATH=$M2:$PATH

Install Maven2

  • lancer le script suivant
#!/bin/sh

mavenVersion="apache-maven-2.2.1"
wget http://apache.cict.fr/maven/binaries/apache-maven-2.2.1-bin.tar.gz

echo "== Telechargement de Apache Maven2 == "

tar -xvf apache-maven-2.2.*.tar.gz

if [ -d "/usr/local/apache-maven" ]
then
 echo "le repertoire /apache-maven existe deja"
 cp -r $mavenVersion /usr/local/apache-maven
 echo "== Copie du repertoire effectue == "
 rm -rf ./$mavenVersion
else
 cd /usr/local/
 mkdir apache-maven
 cd -
 cp -r $mavenVersion /usr/local/
 rm -rf ./$mavenVersion
fi

export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xms512m -Xmx1024m"
export PATH=$M2:$PATH

echo "==== MAVEN  ==="
mvn --version

Install Maven2 plugin Eclipse

  • Download Maven 2 Plugin for Eclipse Help=> Software Update => Click Add enter the following adress. Accept the conditions and restart your Eclipse.

 

 


 

 

 

 

Spring Tool suite and Maven 2

Nb :  Commonly  STS Tool suite is being used as far as it come with Spring IDE integrate plus some other spring visualization such as spring batch and spring integration , namespace support …

  • Since version 2.8 there is some notable changes that must be taken in consideration (eg: Maven connector ) , I invite you guys to have a look at
  • I had encounter some difficulties a straightforward migration from version 2.7 to 2.8 so be diligent during the manipulation. check out the procedure in the link bellow

Procedure

http://blog.springsource.com/2011/10/18/upgrading-maven-integration-for-springsource-tool-suite-2-8-0/

Forum and FAQ

http://forum.springsource.org/showthread.php?116189-STS-2.8.0-and-m2e-FAQ

 

 

 

Ant et Maven

Dans cette section nous allons ajouter le plugin antrun plugin nous permettant d’utiliser les fonctionnalités de Ant via Maven 2

Pour cela il suffit d’inclure dans le fichier Pom.xml  le code ci dessous. Il ne reste plus qu’à ajouter vos appel de target ant relatif que vous souhaitez exécuter à chacune des phases du cycle de vie Maven à savoir :

 

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

 

à la racine du projet nous allons donc créer un fichier build.xml (ant)  où nous allons répertorier les différentes taches Ant que notre projet va utiliser .

 

  • pom.xml
<build>
 <!-- Tips : To define the plugin version in your parent POM -->
 <pluginManagement>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-antrun-plugin</artifactId>
 <version>1.3</version>
 </plugin>
 </plugins>
 </pluginManagement>
 <!-- Tips: To use the plugin goals in your POM or parent POM -->
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-antrun-plugin</artifactId>
 <version>1.6</version>
 <executions>
 <execution>
 <id>Information</id>
 <phase>compile</phase>
 <goals>
 <goal>run</goal>
 </goals>
 <configuration>
 <tasks>
 <ant antfile="${basedir}/build.xml" inheritAll="true"
 inheritRefs="true">
<!--Pass the required properties to ant File-->
 <property name="version" value="${version}" />
 <property name="artifactId" value="${artifactId}" />
 <!--Call ant Target here -->
 <target name="deploymentInformation" />
 </ant>
 </tasks>
 </configuration>
 </execution>
 <execution>
 <id>Deploiement</id>
 <phase>install</phase>
 <goals>
 <goal>run</goal>
 </goals>
 <configuration>
 <tasks>
 <ant antfile="${basedir}/build.xml" inheritAll="true"
 inheritRefs="true">
<!--Pass the required properties to Ant file -->
 <property name="version" value="${version}" />
 <property name="artifactId" value="${artifactId}" />

<!--Call the ant target you want to execute here ... -->
 <target name="XXXX" />

 </ant>
 </tasks>
 </configuration>
 </execution>
 </executions>

 <dependencies>
 <dependency>
 <groupId>ant</groupId>
 <artifactId>ant-jsch</artifactId>
 <version>1.6.5</version>
 </dependency>
 <dependency>
 <groupId>com.jcraft</groupId>
 <artifactId>jsch</artifactId>
 <version>0.1.44-1</version>
 </dependency>
 </dependencies>
 </plugin>
 </plugins>
 </build>
  • build.xml
 

<project name="MyProjectNAME" basedir=".">

 <description>FICHIER ANT DE RUN </description>

 <target name="deploymentInformation">
 <echo message=" Ant File : ${ant.file}"/>
 <echo message ="Ant version  :  ${ant.version}" />
 <echo message="Version :    ${version}" />
 <echo message="ArtifactId :    ${artifactId}" />

 </target>
  • Le transfert SCP
 <target name="copyArchive">
 <scp
 todir=${usr}:${password}@${hostduserveur}:${DestinationFolder}/${artifactId}"
 port="22" trust="true" verbose="true" failonerror="true"
 file="${basedir}/target/${artifactId}-${project.version}-.tar.gz">
 </scp>
 </target>
  • Le remote Sheel via SSH(port 22 par défault )

 

<target name="deploymentCreate">
<sshexec host="${host}" username="${user}" keyfile="${privateRSAKEY}" trust="yes"  command="${NameScript} ${ARG1/2/3...}" verbose="true" >
</sshexec>
</target>
  • A noter que j’ai rencontré des problèmes lors de multiples invocations de remote shell le programme Maven2 /ant s’arrête apparaement il s’agirait d’un bug répertorié sur bugzilla qui serait en cours de correction .

 

 

Ressources et références

http://www.avajava.com/tutorials/lessons/what-are-the-phases-of-the-maven-default-lifecycle.html

http://www.developpez.net/forums/d700132/java/edi-outils-java/build/maven/maven-ant-acces-aux-properties-maven-fichier-build-xml-dant/

http://maven.apache.org/plugins/maven-antrun-plugin/usage.html

http://ant.apache.org/manual/Tasks/scp.html

http://ant.apache.org/manual/Tasks/sshexec.html

  • maven helper :
http://stackoverflow.com/questions/2244344/deploying-assembly-package-with-maven-release-plugin

					

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

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