Integrate Protocol Buffers into Maven2 build

Max A. picture Max A. · Oct 16, 2009 · Viewed 31.5k times · Source

I'm experimenting with Protocol Buffers in an existing, fairly vanilla Maven 2 project. Currently, I invoke a shell script every time I need to update my generated sources. This is obviously a hassle, as I would like the sources to be generated automatically before each build. Hopefully without resorting to shameful hackery.

So, my question is two-fold:

  1. Long shot: is there a "Protocol Buffers plugin" for Maven 2 that can achieve the above in an automagic way? There's a branch on Google Code whose author appears to have taken a shot at implementing such a plugin. Unfortunately, it hasn't passed code review or been merged into protobuf trunk. The status of that plugin is thus unknown.

  2. Probably more realistic: lacking an actual plugin, how else might I go about invoking protoc from my Maven 2 build? I suppose I may be able to wire up my existing shell script into an antrun invocation or something similar.

Personal experiences are most appreciated.

Answer

Pascal Thivent picture Pascal Thivent · Oct 16, 2009

You'll find some information about the plugin available in the Protocol Buffers repository in the Protocol Buffers Compiler Maven Plug-In thread on the Protocol Buffers discussion group. My understanding is that it's usable but lacking tests. I'd give it a try.

Or you could just use the antrun plugin (snipet pasted from the thread mentioned above):

 <build>
   <plugins>
     <plugin>
       <artifactId>maven-antrun-plugin</artifactId>
       <executions>
         <execution>
           <id>generate-sources</id>
           <phase>generate-sources</phase>
           <configuration>
             <tasks>
               <mkdir dir="target/generated-sources"/>
               <exec executable="protoc">
                 <arg value="--java_out=target/generated-sources"/>
                 <arg value="src/main/protobuf/test.proto"/>
               </exec>
             </tasks>
             <sourceRoot>target/generated-sources</sourceRoot>
           </configuration>
           <goals>
             <goal>run</goal>
           </goals>
         </execution>
       </executions>
     </plugin>
   </plugins>
 </build>

 <dependencies>
   <dependency>
     <groupId>com.google.protobuf</groupId>
     <artifactId>protobuf-java</artifactId>
     <version>2.0.3</version>
   </dependency>
 </dependencies>