home.


Tagged: maven


Gradle: Generate POM file etc with the maven plugin

The maven plugin lets us install a maven package, the pom file etc, to a repository. The default repository is our local file system.

Let’s say we’re building a Java project, here’s the build script. It’s as normal, except for the archivesBaseName, group and version.

apply plugin: 'java'
apply plugin: 'maven'

repositories {
    mavenCentral()
}

dependencies {
  ...
}

archivesBaseName = 'jersey-json-wadl'
group = 'com.newfivefour'
version = '0.0.1'

Now if we do ./gradew install (I’m assuming you’re using the gradle wrapper), it will install this to ~/.m2/repository/com/newfivefour/jersey-json-wadl/0.0.1/.

Within that directory you’ll have your POM file and the generated JAR. In the directory above that, there’s a maven-metadata-local.xml file that documents the versions and last updated time amoung other things.

If you run ./gradlew install again with a new version attribute, you’ll get a new directory above, this time named 0.0.2 for example.

gradle maven pom

Maven p23: Build profiles

Development and production version of a project often exist with different properties, SQL server params for example.

Maven allows us to use build profiles. In such a profile we can override pretty much anything in the POM. In this case we’re going to override the resource filter in a ‘prod’ profile.

    ...

    <build>
       <resources>
           <resource>
             <directory>src/main/resources/</directory>
             <filtering>true</filtering>
           </resource>
       </resources>                    
         <filters>
           <filter>src/main/filters/development.properties</filter>
         </filters>               
    </build>

    <profiles>

       <profile>
         <id>prod</id>
         <build>
             <filters>
         <filter>src/main/filters/production.properties</filter>
             </filters>    
         </build>
       </profile>    

    </profile>

    ...

We have a normal build section that specifies the resource directory and a filter. Then in a profile section we give it a name, and override the filters tag in the build section. Note we keep the other build properties previously defined.

So when we run mvn package we’ll use the development.properties. If we run mvn package -P prod we’ll get production.properties.

It’s also possible to active a profile on certain conditions, such as the JDK version. See the activition tag. You can have a activeByDefault tag in a profile to get that used by default. You can also have a profile defined in your own settings.xml file under the settings tag. That way you can give a property to the build system, your db password for example.

maven maven-build-profile

Maven p22: Run a task at a build lifecycle phase

To execute a plugin, or an Ant task in this case, at a certain time in the build, you can specify a plugin in the build tag, and then an executions tag to specify the phase it should execute:

      ...
      <build>
        <plugins>
          <plugin>
       <artifactId>maven-antrun-plugin</artifactId>
       <executions>
         <execution>
           <id>hellothere</id>
           <phase>pre-clean</phase>
           <goals>
             <goal>run</goal>
           </goals>
           <configuration>
             <tasks name="hallo">
         <echo>Hello, World</echo>
             </tasks>
           </configuration>
         </execution>
       </executions>
          </plugin>
        </plugins>
      </build>
      ...

This says that the ant plugin should be ran in the ‘pre-clean’ stage, that the goal in the ant plugin should be run, and the tasks in the configuration says what to do.

maven ant maven-build-lifecycle

Maven p21: Multi module projects

Multimodules projects are for when you’ve partitioned your project into sub projects, and you want to automate changing one, compiling it, and then going into the other project to compile it again to pull up the changes from the other sub-project.

You’d have two projects, for example, with prj two being depedent on prj one. So when you mvn install it from the parent project, it will compile and install prj one, then compile and install prj two.

First create a parent project, of the type pom, defining the two sub-modules (the order is unimportant, mvn will find out what to compile first):

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <artifactId>java0</artifactId>
      <packaging>pom</packaging>
      <version>1-SNAPSHOT</version>
      <groupId>your.pkg</groupId>

      <modules>
        <module>java2</module>
        <module>java1</module>
      </modules>

    </project>

Now you’ll a java1 directory within that project, with its own pom, defining its parent, and source code:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <parent>
        <groupId>your.pkg</groupId>
        <artifactId>java0</artifactId>
        <version>1-SNAPSHOT</version>
      </parent>
      <artifactId>java1</artifactId>
      <packaging>jar</packaging>

    </project>

java1/src/main/java/your/pkg/TextOutput.java:

    package your.pkg;


    public class TextOutput {
       public String getText() {               
         return "Some sample text";
       }
    }

Now for java2. It’s very similar to the pom in java1, except its defining its dependency on java1.

(Note we’re only telling it to make a java-with-dependencies to easy run the new jar file later; it’s not a part of multimodule projects per se)

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
         <modelVersion>4.0.0</modelVersion>
         <parent>
           <groupId>your.pkg</groupId>
           <artifactId>java0</artifactId>
           <version>1-SNAPSHOT</version>
         </parent>

         <artifactId>java2</artifactId>
         <packaging>jar</packaging>

         <dependencies>
         <dependency>
             <groupId>your.pkg</groupId>
             <artifactId>java1</artifactId>
             <version>1-SNAPSHOT</version>
         </dependency>
         </dependencies>

         <build>
            <plugins>
         <plugin>
             <artifactId>maven-assembly-plugin</artifactId>
             <executions>
          <execution>
              <id>itsname</id>
              <phase>package</phase>
              <goals>
              <goal>single</goal>
              </goals>
              <configuration>
              <descriptorRefs>
                  <descriptorRef>
                 jar-with-dependencies
                  </descriptorRef>
              </descriptorRefs>
              </configuration>
          </execution>
             </executions>
         </plugin>
            </plugins>
       </build>
    </project> 

java2/src/main/java/your/pkg/DisplayText.java:

    package your.pkg;

    import your.pkg.TextOutput;

    public class DisplayText {
       public static void main(String[] strings) {
         TextOutput ta = new TextOutput();
         System.out.println(ta.getText());
       }
    }

Now if you go into the parent project, you can run mvn install. Then finally a java -cp java2/target/java2-1-SNAPSHOT-jar-with-dependencies.jar your.pkg.DisplayText will output the result of DisplayText.

(Note we used the jar-with-dependencies thing so java2’s output would contain the java1 depedency)

maven maven-multimodule

Maven p20: Java servlets

To actually use Servlets in your webapp, we need a depedency which gives us all the J2EE goodness, the OSS Apache Geronimo project. The mvn depedency can be found here: http://mvnrepository.com/artifact/org.apache.geronimo.specs/geronimo-servlet_2.5_spec/1.2 Let’s put that in the dependencies section of your pom.xml:

    ...
    <dependency>
       <groupId>org.apache.geronimo.specs</groupId>
       <artifactId>geronimo-servlet_2.5_spec</artifactId>
       <version>1.2</version>
    </dependency>
    ...

Now we need to tell web.xml that we’re going to create a servlet, and give it a mapping also:

    <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <servlet>
       <servlet-name>simple</servlet-name>
       <servlet-class>your.pkg.simpleservlet.SimpleServlet</servlet-class>
      </servlet>
      <servlet-mapping>
       <servlet-name>simple</servlet-name>
       <url-pattern>/simple</url-pattern>
      </servlet-mapping>
    </web-app>

We’re saying they’ll be a servlet, called simple, and we give its to-be-created class. Then we map its name to a url pattern. Let’s now create that class in src/main/java/your.pky.simpleservlet

    package your.pkg.simpleservlet;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Date;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class SimpleServlet extends HttpServlet {
       public void doGet(HttpServletRequest request, 
          HttpServletResponse response)
         throws ServletException, IOException {

         PrintWriter out = response.getWriter();

         HttpSession lSess = request.getSession(true);
         int lInactive = lSess.getMaxInactiveInterval();
         long lTime = lSess.getLastAccessedTime();
         lSess.setAttribute("bar", "Hello, session attribute!");
         String att = (String) lSess.getAttribute("bar");

         out.println(att);
         out.flush();
         out.close();
       }

       @Override
       public void init() throws ServletException {
         super.init();
         System.out.println("init'd");
       }

       @Override
       public void destroy() {
         super.destroy();
         System.out.println("destroy'd");
       }
    }

Notice we’re importing lots of servlet classes. These are given to use by the Geronimo project. The class extends a HttpServlet. init() and destory() are called at moments that you can imagine well enough yourself. The doGet() is called during a GET request. Whatever’s written to the HttpServletResponse is outputted. And we can get session information, even getting session variables.

maven java j2ee

Page 1 of 5
Next