How to use google protobuf compiler with maven-compiler-plugin

Viewed 7226

I have a simple java project(No spring) and I have a protobuf file test.proto in src/resources folder and I want to generate sources from it. I read in several places that, to use the plugin I need to install it locally first. But in my previous gradle project I didn't need to do anything like this and just a simple config like below works for gradle :

protobuf {
  protoc {
    artifact = 'com.google.protobuf:protoc:3.8.0'
  }

  generateProtoTasks.generatedFilesBaseDir = generatedProtoPath
}

What is similar thing in Maven, if I want to use google provided protoc compiler and generate code without downloading and installing anything on my production machine.

1 Answers

To answer my own question so that someone finds it helpful :
google protobuf 3.7.0 : Maven changes -- Add this to your pom.xml :

<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.7.0</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>3.7.0</version>
</dependency>
</dependencies>
<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.0</version>
        </extension>
    </extensions>
    <plugins>
    <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <extensions>true</extensions>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <additionalProtoPathElements>
                <additionalProtoPathElement>${project.basedir}/src/main/resources</additionalProtoPathElement>
            </additionalProtoPathElements>
            <protocArtifact>com.google.protobuf:protoc:3.7.0:exe:${os.detected.classifier}</protocArtifact>
        </configuration>
    </plugin>

This is the java class :

public class ProtobufTrial {
  public static void main(String[] args) throws Exception {
    String jsonString = "";
    MyProto.MyEventMsg.Builder builder = MyProto.MyEventMsg.newBuilder();
    JsonFormat.parser().ignoringUnknownFields().merge(jsonString, builder);
    MyProto.MyEventMsg value = builder.build();

    // This is for printing the proto in string format
    System.out.println(JsonFormat.printer().print(value));
  }
}
Related