Search posterous

Search all posts and users. Type a name, type a favorite song title, whatever! See what comes up.
  

More posterous blogs











More recommended blogs »

Here are posterous posts filed under maven...

ildella says...

Fortunately there is the Maven handbook [1]. Unfortunately you had to
know that it exists, or you risk to deal with the complete but huge
Nexus documentation. What you need to run a Nexus server is what
follows, giving that you already have JRE and a servlet container
installed (I use Jetty here)

 
cd $JETTY_HOME/webapps 
wget http://nexus.sonatype.org/downloads/nexus-webapp-1.4.0.war 
cd .. 
./bin/jetty.sh restart 

Point browser to http://localhost:8080/nexus-webapp-1.4.0/
Login as admin/admin123

Click on the link "repositories" on the left and choose the "Release"
repository. There is a local path configured as attribute "Default
Local Storage Location".

If you already have a local repositories (in ~/.m2/repository), you
should copy all artifacts to that folder. Like:

 
cp ~/.m2/repository/* ~/sonatype-work/nexus/storage/releases/ 

Then the artifacts will become available to the URL of the Release
repository. Now adding that repository in your pom.xml will make Maven
use those artifacts during build.

That's all.

[1] http://www.sonatype.com/books/mhandbook/reference/

Filed under: maven

ildella says...

In this two parts article, I will explain how to configure a web application built with Maven to support "branding", or skinning. That is, support different distribution skinned with particular images, logo, background, text. In the end we just want to keep separated the static contents and choose the right set when we package our application so that the result is a war with just the content for a single company. I call this a branded distribution using brand as a similar word for skinning. Brand looks more enterprise and general than skinning, anyway :)

In the second part of the article I will also cover the Wicket side of the story. The Maven side works by himself, anyway.

Some thoughts, before to start.

Fundamentals stuff, but important to remember: files that are in the war root are accessible from an HTML file with a relative path, so if we can have an image under myapp.war/images/pic.png we can acess it with src="images/pic.png".
Instead, when we need to load an image or a text file from Java code, it must be in the Classpath, so it had to be under myapp.war/WEB-INF/
Fundamentals, I told.

Another thing: we want to develop in comfort under our IDE, spcifically Eclipse, not being doomed to perform a Maven compile every time to filter some property. Test should run with their own resources, build path in Eclipse should be consistent and not be affected by multi brand configuration so that Eclipse copy modified resources on the fly and we have latest version in place without going to ask Maven again.

Last thing: as always, use what already exists. Wicket has a built-in support for skinning (called styling) and Maven provides "profiles". Let's use everything we can. Ready, go!

Maven Side - Profiles

Let's first introduce the concept that we are running our application in a particular mode, a brand mode, whatever. Comes natural to define a maven property in pom.xml

 <properties>
             .....
            <brand>stage</brand>
</properties>

Where "brand" is the name of the property and "stage" is the value. For those not familiar with Maven properties, let's say just this: in every file that will be processed by maven during a build session, maven will "filter" all the variables and they will be substituted by the value defined in pom. In a few words:

${brand}  --> stage

in every file filtered by Maven. Included pom.xml itself.

So we will have different brands: stage is my word for "demonstration application". We can have companyA, companyB, and so on. To implement different brands, in maven, we use maven profiles. While stage is a top level POM property, we now define:

   <profiles>
      <profile>
         <id>companyA</id>
         <properties>
            <brand>companyA</brand>
         </properties>
       </profile>
   </profiles>

As we all know, to activate a profile we add "-P companyA" in the maven command line and all the profile configuration will override the default ones. So now we have a default brand, stage, and a companyA specific profile.

Maven Side - Resources

In my stage brand I have to use free images, a personal disclaimer and avoid all contents owned by my customer. So I create a folder "brands"  with a sub folder for each "brand" [1]. So in "src/main/brands/stage" I put my free to use contents.

To let maven choose the folder accordingly to the chosen brand, we configure the new resource this way:

<resources>
         <resource>
            <filtering>false</filtering>
             <directory>src/main/brands/${brand}/</directory>
            <includes>
               <include>**/*.txt</include>
            </includes>
         </resource>
     ...
</resources>

In my particular situation, I am interested in having just *.txt files under my Classpath. Please note that I have also put every file in the brand folder under a sub folder I call "contents", so I do not  have a mess of files in the root of my war. Here is how I load resources from java:

getClass().getClassLoader().getResourceAsStream("contents/" + "myResource.txt")

Now let's deal with static images, typically some logo, background and so on. Target is to access images from HTML file simply with an img tag and a src="contents/header.jpg"

We need to configure what in maven are called "web resources", and deal with the maven-war-plugin:

       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                  <resource>
                     <directory>src/main/brands/${brand}/</directory>
                     <includes>
                        <include>**/*.jpg</include>
                         <include>**/*.gif</include>
                        <include>**/*.png</include>
                     </includes>
                  </resource>
               </webResources>
             </configuration>
         </plugin>

In the end, the "src/main/brands/${brand}" folder is just a new folder threated as maven normally threat "src/main/webapp" where we normally found the css folder and other folders with static content. This is the reason I normally keep files under "src/main/brands/${brand}/contents", to keep war root clean.

To summer up, here is the folder layout:



src/main/


  - brands


    - stage


      - contents/disclaimer.txt


    - companyA


        - contents/disclaimer.txt


  - webapp


    -css



This completes the maven side of the problem. In the next article we will attack the "web" side, with Wicket, and finish with fixing the development environment.

[1] Thanks to Simone Bordet for the final tip on this on the JUG Milano mailing list! :) http://bordet.blogspot.comt.

Filed under: maven

trapo says...

How cool is dropbox? I just created an account and now the site generated by maven is available at:

https://dl.getdropbox.com/u/2812119/trapo/index.html

I promisse that I will try to maintain it updated with the code in github.

cya

Filed under: maven

trapo says...

I want to keep Trapo environment as simple as possible. I want that people just fire a command and all tests can run immediately: no setups, no database creation, no sql to run. Just one single command and trapo should do everything for you. Because of that, I start to isolate the test environment from the production one in order to use a different database instance (or even a different database vendor). To integrate the combo, I just call HSQLDB to the party. To avoid describe exactly what is HSQLDB, here is a quote from its homepage:

HSQLDB (HyperSQL DataBase) is the leading SQL relational database engine written in Java. It has a JDBC driver and supports a rich subset of ANSI-92 SQL (BNF tree format) plus many SQL:2008 enhancements. It offers a small, fast database engine which offers both in-memory and disk-based tables and supports embedded and server modes. Additionally, it includes tools such as a minimal web server, in-memory query and management tools (can be run as applets) and a number of demonstration examples.


FIRST, CONFIGURE MAVEN...

The simplest part: just add hsqldb as a maven dependency:

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>1.8.0.10</version>
    <scope>test</scope>
</dependency>

I decide to scope it as test because I'm not intent to use it in production, but you can use a different scope.

SECOND, ADD TEST RESOURCES...

Then, I just create two files inside src/test/resources directory. You can create files here to replace src/main/resources while running tests. But I want to reduce the amount of work to maintain both test and production enviroment, so, I'm replacing just what need to be replace: the database configuration. The two files are:

src/test/resources/hibernate.tests.properties

hibernate.connection.driver_class = org.hsqldb.jdbcDriver
hibernate.connection.url = jdbc:hsqldb:mem:trapo
hibernate.connection.username = sa
hibernate.connection.password =
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.HSQLDialect

hibernate.show_sql=true
hibernate.format_sql=true
hibernate.default_batch_fetch_size=5
hibernate.generate_statistics=true
hibernate.use_sql_comments=true
hibernate.jdbc.batch_size=10

hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider
hibernate.cache.use_structured_entries=true

hibernate.hbm2ddl.auto=create-drop

Note the url property, it is pointing to an in memory database. Moreover, this files contains cache and some other optional configurations to mimic the production configurations. The other file is the Spring context to configure the SessionFactory for tests:

src/test/resources/applicationContextTest.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util-2.5.xsd">
  <bean id="testSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
        p:annotatedClasses-ref="annotatedClasses"
        p:annotatedPackages="com.google.code.trapo.domain"
        p:hibernateProperties-ref="hibernateProperties" />
  <util:list id="annotatedClasses">
    <value>com.google.code.trapo.domain.Forum</value>
    <value>com.google.code.trapo.domain.Topic</value>
  </util:list>
  <util:properties id="hibernateProperties" location="classpath:hibernate.test.properties" />
</beans>

I'm not fully confortable with that because I need to copy and past mapped classes here. But, this is a start, so I prefer to have sub-optimal solution over don't have any solution at all.

THIRD, REFACTOR YOUR TESTS...

Your tests should use SpringJUnit4Runner instead of the default one. So you have to put the following annotation in the test class:

@RunWith(SpringJUnit4ClassRunner.class)
public class MyRepositoryTests {
    ...
}

You also need to say to Spring where it should find the configuration files using @ContextConfiguration annotation:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:/trapo-servlet.xml",
    "classpath:/applicationContextTest.xml"
})
public class MyRepositoryTests {
    ...
}

And, because your tests are using the database, is a good call configure them to be transactional. In order to do that, you need both @Transactional and @TransactionConfiguration annotations:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:/trapo-servlet.xml",
    "classpath:/applicationContextTest.xml"
})
@Transactional
@TransactionConfiguration(transactionManager = "txManager")
public class MyRepositoryTests {
    ...
}

And then inject the testSessionFactory configure in applicationContextTests.xml in your tests:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:/trapo-servlet.xml",
    "classpath:/applicationContextTest.xml"
})
@Transactional
@TransactionConfiguration(transactionManager = "txManager")
public class MyRepositoryTests {

    @Autowired private SessionFactory testSessionFactory;

}

FINALLY, JUST RUN YOUR TESTS...

And now the grand finale, just open a command prompt, go to trapo directory and type:

mvn clean test

If you want to see cobertura report, type:

mvn clean cobertura:cobertura

Hope that helps.

Filed under: maven

Quân says...

- netbeans > new maven web app
- run index.jsp to see 'Hello World!' message

- Add spring web fw to project

  add to pom.xml

  add to springapp2/web/WEB-INF/web.xml
 + autoload Dispatcher at startup
 + URL with an '.htm' extension be routed to the 'springapp' servlet (the DispatcherServlet)

- Add new file springapp2/web/WEB-INF/springapp-servlet.xml


- Create the Controller
com.mycompany.springapp2.web.HelloController
- Test Controller
HelloControllerTests.java

- Create the View
'springapp2/web/hello.jsp':
- Compile, deploy & run the application: http://localhost:8084/springapp2/hello.htm

Click here to download:
springapp2.rar (4 KB)

Filed under: Maven

trapo says...

Fast tip: you can use tomcat maven plugin to run Trapo in development mode. Just open a prompt, go to trapo directory and run the following command:
 
>> mvn clean tomcat:run 
Voilá! Besides the fact that Trapo runs ok in Tomcat, I'm just trying compatibilities issues here. Tomcat is more heavy than Jetty for restarts, something that I need to change-save-and-see developement.

Filed under: maven

trapo says...

So, do you want to run Trapo and see how it looks like?

CURRENT STATE

For now, you can just run it in development mode. You will need:
  1. You need Java, because Trapo is developed using Java. You need version 1.5 or newer
  2. PostgreSQL (8.2 or newer) with a database named trapo and with an user "trapo" with password "trapo"
  3. And you need maven.
Once you have all this stuff installed and configured in your box, you can run Trapo using one of the these two ways:

RUN TRAPO THROUGH MAVEN

Piece of cake, just travel to Trapo directory and type:

> mvn clean jetty:run

Probably, maven will try to download the whole internet and so the command may take a while to run. But this will occur just first time you run the command. Open your browser and go to http://localhost:8080/trapo/index.html

CREATING AND DEPLOYING A WAR

If you choose this option, you will need a servlet container (Tomcat, Jetty, Glassfish, etc). Just follow the steps below:
  1. Travel to Trapo directory and run: > mvn war
  2. Maven will generate a war file, rename it to trapo.war
  3. Deploy the trapo.war (usually you just need to copy the file to a directory inside your container)
Open your browser and go to http://localhost:8080/trapo/index.html

Filed under: maven

ildella says...

As many that are using maven 2 since years, I have many mavenized projects and the most of them have similar structure: are web projects, uses jetty and other plugins, many shares a lot of dependencies. So I decided to create an archetype to quickly generate new projects. I also wanted to use the mvn archetype generate command, so I prepared a archetypes catalog in my repository to allow me to use my personal archetypes with automatic generation.


As a start, I took an existing mvn archetype source code. Yes, maybe there are a good tutorial but what is better than an existing simple projects to modify? I am the lazy dev after all. I choose wicketrad-archetype, for the only reason I already had the code on my computer.

There are just two things to do:

  1. Change group and artifact id in the archetype pom (the one in the root folder) with what you like i called mines net.ildella.archetypes.base and net.ildella.archetypes.pheadra.
  2. Modify the pom.xml in src/main/resources/archetype-resources. This will be the one that will be used as basis for generated projects. Put in there whatever you like: plugins with configurations, dependencies, some comment as tip or reminder should also be useful.

Then a simple "mvn install" will install archetype artifact in local repository.

Let's now go for the Catalogue: create a file called archetype-catalog.xml with a content like this one:


<?xml version="1.0" encoding="UTF-8"?>
<archetype-catalog>
   <archetypes>
<archetype>
           <groupId>net.ildella.archetypes</groupId>
           <artifactId>base</artifactId>
           <version>1.0</version>
           <repository>http://www.mvnsearch.org/maven2</repository>
           <description>Basic maven projects with useful stuff configured</description>
       </archetype>
<archetype>
           <groupId>net.ildella.archetypes</groupId>
           <artifactId>phaedra</artifactId>
           <version>1.0</version>
           <repository>http://www.mvnsearch.org/maven2</repository>
           <description>Basic + pheadra dependencies and stuff</description>
       </archetype>
   </archetypes>
</archetype-catalog>

and put it in your ~/.m2/repository folder, or wherever you keep your repository.
That's all. Now we can do:

mvn archetype:generate -DarchetypeCatalog=file:///home/ildella/.m2/repository/

to get the following result:

We choose a number and we got our skeleton project.

If like me you started from wicketrad-archetype, have a look at file src/main/resources/META-INF/maven/archetype.xml to see how to include resources to your skeleton project, for example to add some demonstration classes.

 

Filed under: maven

Quân says...

For example, “kaptcha” is a third party library which can generate captcha image easily, but it did not support or provide pom.xml for Maven project. Here i demonstrate how to install “kaptcha” jar into my Maven’s local reposiroty.

1) Download the “kaptcha” jar file and put it into c drive, and issue following command

mvn install:install-file -Dfile=c:\kaptcha-2.3.jar -DgroupId=com.google.code -DartifactId=kaptcha -Dversion=2.3 -Dpackaging=jar

2) Create or modify the Pom.xml file, add the following code

<dependency>
      <groupId>com.google.code</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3</version>
</dependency>

3) Done, “kaptcha” is installed in my Maven local repository

Filed under: Maven

riduidel says...

A chaque fois que je vois un développeur Java passer son temps à regarder Maven tourner, j’y vois une perte de productivité.
D’autant plus que je vois très régulièrement cette tendance dans les projets, au sein d’OCTO et même dans ma propre utilisation.
Attention, je pense que Maven est très efficace pour améliorer la productivité des développements, mais le plus gros piège reste de « passer son temps dans la console ».

Pourquoi c’est mal ?
Quand on s’occupe de faire marcher Maven en bidouillant le POM et en regardant le build tourner dans la console : on ne développe pas.
Lorsqu’on développe, on doit passer son temps dans son IDE (eclipse, InteliJ, netbean, notepad ou vi selon les gouts) et coder du code, des tests.

maven is building

Cette image est un détournement, voici l’image originale : http://xkcd.com/303/

Alors pourquoi on passe son temps dans la console ?
En cherchant bien, j’en viens à la conclusion que la principale raison pour laquelle je passe mon temps dans la console est que mon IDE n’est pas bien configuré : un build dans mon IDE produit un résultat différent d’un build Maven, je ne fais plus confiance à mon IDE et la seule façon d’être sûr que mon code marche c’est de lancer la commande « mvn install » et d’attendre le message « Build Successfull ». Un cas typique est l’utilisation du filtering des ressources par Maven qui n’est pas géré nativement par Eclipse (le plugin m2eclipse résout ce problème).

Oui, mais ça ne marche pas : les tests dans mon IDE ont un comportement différents que dans Maven
Dans ce cas, je n’ai qu’un seul conseil : faites le marcher !
Votre configuration doit être assez bonne pour que quand vos tests passent dans l’IDE, vous devez être assez confiants pour pousser votre code dans votre gestionnaire de source.
Si vraiment il y a un problème, l’intégration continue va vous prévenir.

Lancer un build Maven sur votre poste et bidouiller vos configurations (Maven ou IDE) doit être rare :

  • quand l’UDD a retourné une erreur et que vous avez diagnostiqué que le problème vient d’une configuration
  • quand justement vous avez modifié votre POM (pour rajouter un plugin, ajouter un module, etc.)

Ces 2 cas doivent rester marginaux :

  • si votre UDD vous retourne constamment des erreurs de configuration, prenez le temps de les corriger durablement
  • si vous modifiez trop souvent vos POM, il est surement temps de prendre un peu de recul et de stabiliser la configuration des projets.

En résumé : Ne passez pas votre temps dans la console Maven, passez-le à coder dans votre IDE

C'est marrant, ça, mais chez IT-Finance, on a passé pas mal de temps (trop, peut-être ?) à jouer avec le script maven qui permettait de générer l'application. Et bien des fois, j'ai suggéré à mes collègues de réfléchir à notre usage de maven. Est-ce qu'on n'essayait pas d'en faire trop avec maven ? Est-ce qu'on faisait les choses dans le bon sens avec cet outil qui, définitivement, n'est pas une silver-bullet ? Est-ce qu'on n'aurait pas dû rester avec ant (et éventuellement, utiliser un outil séparé de gestion des dépendances comme ivy) ?Je n'aurais sans doute jamais la réponse à cette question. Ce que je sais, en revanche, c'est que c'est encore un domaine où, peut-être sans même sans rendre compte, on réinventait beaucoup de choses.

Filed under: maven