nov

02

Posted by : admin | On : 2 novembre 2011

 

Rendre un Jar executable en Spring

  • Nous allons voir dans cet article comment packager un executable jar avec Maven 2 .
  • Ayant rencontrer quelque problème dans le chargement des Beans Spring . Pour cela il faut inclure dans le packaging du jar les fichiers spring.handlers  et spring.schemas.
  • Nous utiliserons ici le plugin shade plutot que le plugin Assembly . (Le plugin assembly étant plus adapté à la création Archive tar.gz , zip …)

NB : Pour les applicatifs web sous formats War ou ear vous ne rencontrer pas ce type de problème.

Origine du problème :

4.3.2. ClassPathResource

This class represents a resource which should be obtained from the classpath. This uses either the thread context class loader, a given class loader, or a given class for loading resources.

This Resource implementation supports resolution as java.io.File if the class path resource resides in the file system, but not for classpath resources which reside in a jar and have not been expanded (by the servlet engine, or whatever the environment is) to the filesystem. To address this the various Resource implementations always support resolution as a java.net.URL.

A ClassPathResource is created by Java code explicitly using the ClassPathResource constructor, but will often be created implicitly when you call an API method which takes a String argument which is meant to represent a path. For the latter case, a JavaBeans PropertyEditor will recognize the special prefix classpathn the string path, and create a ClassPathResource in that case.

 

    package test;  

    import org.springframework.beans.factory.xml.XmlBeanFactory;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;  

    public class TestSpring {  

        public static void main(String[] args) {
            ApplicationContext contexte = new ClassPathXmlApplicationContext("config.xml");
            Test test = contexte.getBean("test", Test.class);
            System.out.println(test);
        }
    }

 

  • code Main de test :
    package test;  

    import java.io.IOException;
    import java.io.File;  

    import org.springframework.context.ResourceLoaderAware;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.ResourceLoader;  

    public class Test implements ResourceLoaderAware {  

        private ResourceLoader resourceLoader;
        private String fichier;
        private Resource resource;  

        public void init() throws IOException {
            System.out.println("#init");
            if(resource.exists()){
                new File(resource.getURL().getFile());
            }
            new File(resourceLoader.getResource(fichier).getURL().getFile());
        }  

        public void setFichier(String fichier) {
            System.out.println("#setFichier");
            this.fichier = fichier;
        }  

        public void setResource(Resource resource) {
            System.out.println("#setResource");
            this.resource = resource;
        }  

        public void setResourceLoader(ResourceLoader arg0) {
            System.out.println("#setResourceLoader");
            this.resourceLoader = arg0;
        }
    }

 

Configuration Maven2

	<dependencies>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-core</artifactId>
			<version>2.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-file</artifactId>
			<version>2.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-sftp</artifactId>
			<version>2.0.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>
	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.handlers</include>
					<include>**/*.schemas</include>
					<include>**/*.properties</include>
					<include>**/*.txt</include>
				</includes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>test.TestSpring</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>test.TestSpring</mainClass>
								</transformer>

								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/properties/system.properties</resource>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.handlers</resource>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/spring.schemas</resource>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>system.properties</resource>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>test.TestSpring</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>

		</plugins>

		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>some-group-id</groupId>
										<artifactId>some-artifact-id</artifactId>
										<versionRange>[1.0.0,)</versionRange>
										<goals>
											<goal>some-goal</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<execute>
											<runOnIncremental>false</runOnIncremental>
										</execute>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>

	</build>
	<repositories>
		<repository>
			<id>com.springsource.repository.bundles.release</id>
			<name>EBR Spring Release Repository</name>
			<url>http://repository.springsource.com/maven/bundles/release</url>
		</repository>
		<repository>
			<id>com.springsource.repository.bundles.external</id>
			<name>EBR External Release Repository</name>
			<url>http://repository.springsource.com/maven/bundles/external</url>
		</repository>
	</repositories>

 

 

Annexe :

http://static.springsource.org/spring/docs/2.0.3/reference/resources.html


					

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