天道酬勤,学无止境

Dependencies for Protoc Java plugin?

I'm trying to make working example at How to write a custom Protobuf CodeGenerator in Java . When I try to compile a file with

import com.google.protobuf.compiler.PluginProtos;

import java.io.IOException;

public class MyPlugin {
    public static void main(String[] args) throws IOException {
        CodeGenerator gen = new CodeGenerator();
        PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);
        codeGeneratorRequest.getProtoFileList().forEach(gen::handleFile);
        // get the response and do something with it
        //PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.newBuilder().build();
        //response.writeTo(System.out);
    }
}

I get compile error because CodeGenerator is unknown. I have in my pom.xml Maven file the following inside "dependencies" tag -

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

What else do I need to add to dependencies make my plugin working? I plan to use Java API from https://developers.google.com/protocol-buffers/docs/reference/java/ .

评论

Yeah, that was a bit stupid - CodeGenerator is a custom class, we need to write it, it's the name which confuses by implying it's from the Google library.

So after writing it could look like this - approximate analogy of Python code at https://www.expobrain.net/2015/09/13/create-a-plugin-for-google-protocol-buffer/ , but without packaging into JSON and cleaning subfields:

import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.compiler.PluginProtos;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ProtocPlugin {
    private static List _traverse(String strPackage, List items) {
        List<List> res = new ArrayList<>();
        for(Object item : items) {
            res.add(Arrays.asList(item, strPackage));
            if(item instanceof DescriptorProtos.DescriptorProto) {
                DescriptorProtos.DescriptorProto dp = (DescriptorProtos.DescriptorProto) item;
                for(DescriptorProtos.EnumDescriptorProto e : dp.getEnumTypeList()) {
                    res.add(Arrays.asList(e, strPackage));
                }
                for(DescriptorProtos.DescriptorProto nested : dp.getNestedTypeList()) {
                    String strNestedPackage = strPackage + nested.getName();
                    for(Object nestedItem : _traverse(strNestedPackage, nested.getNestedTypeList())) {
                        res.add(Arrays.asList(((List)nestedItem).get(0), strNestedPackage));
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) throws IOException {
        StringBuilder data = new StringBuilder();
        PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(System.in);
        codeGeneratorRequest.getProtoFileList().forEach((DescriptorProtos.FileDescriptorProto fileDescriptorProto) -> {
            String strPackage = fileDescriptorProto.getPackage();
            if(strPackage == null || strPackage.isEmpty()) {
                strPackage = "&lt;root&gt;";
            }
            data.append("package: ").append(strPackage).append("\n");
            data.append("filename: ").append(fileDescriptorProto.getName()).append("\n");

            List<DescriptorProtos.EnumDescriptorProto> enums = fileDescriptorProto.getEnumTypeList();
            for(Object pair : _traverse(strPackage, enums)) {
                data.append("type: enum").append("\n");
                data.append(((List)pair).get(0)).append(((List)pair).get(1)).append(" ");
            }

            List<DescriptorProtos.DescriptorProto> messageTypes = fileDescriptorProto.getMessageTypeList();
            for(Object pair : _traverse(strPackage, messageTypes)) {
                data.append("type: message").append("\n");
                data.append(((List)pair).get(0)).append(((List)pair).get(1)).append(" ");
            }
        });

        PluginProtos.CodeGeneratorResponse.Builder builder = PluginProtos.CodeGeneratorResponse.newBuilder();
        builder.addFileBuilder().setContent(data.toString()).setName("mytest.txt");
        PluginProtos.CodeGeneratorResponse response = builder.build();
        response.writeTo(System.out);
    }
}

The launch of protoc could be with

protoc --plugin=protoc-gen-custom=my-plugin.bat --custom_out=. hello.proto

where my-plugin.bat contains something like

@echo off
java -cp target/classes;c:/users/bover/.m2/repository/com/google/protobuf/protobuf-java/3.6.1/protobuf-java-3.6.1.jar ProtocPlugin

here we assume that our Java plugin compiles ProtocPlugin.class into target/classes directory. The output will be in mytest.txt file. hello.proto is a simple proto file from the Python example above.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 使用 gradle 进行简单的 protobuf 编译(simple protobuf compilation with gradle)
    问题 如果您正在寻找示例 gradle protobuf 项目,请看这里。 我在使用 gradle 和 protobuf 时遇到困难,我想创建一个简单的 gradle 项目,该项目将从默认的src/main/proto 、 src/test/proto获取任何 proto 文件并将它们编译为src/main/java 、 src/test/java相应地,然后将其打包到一个 jar 中并发布到本地存储库。 不幸的是,我是 gradle 的新手,无法弄清楚原始项目是如何组成的。 这是我未完成的 build.gradle 文件 apply plugin: 'java' apply plugin: "com.google.protobuf" buildscript { repositories { mavenCentral() } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.7.0' } } repositories { mavenCentral() } dependencies { compile 'com.google.protobuf:protobuf-java:3.0.0-beta-1' } sourceSets { main { proto { srcDir 'src/main
  • Android中的ProtoBuf应用-基础篇
    项目中经常用到Gson,xml等数据格式,今天接触到一个新的(对我来说是新的)格式,决定尝试一下其在Android中的用法,折腾了半天,终于搞完了,在此总结一下基本用法。 ProtoBuf的优势: 跨平台,跨语言。你可以在Android,Linux,Windows多个平台使用它并且不受Java,Python还是C++的限制数据量小。由于其独特的序列化方式,使得其比其他数据格式更小,传输效率更高。扩展性好,兼容性好。在更新数据结构后,基于其特有的Builder方式,可以不对原有的代码产生影响。 搭建环境 在Android Studio中搭建环境并没有想象中的轻松,历经了多种方式,辗转多个教程才最终运行成功,主要有以下几个步骤: 1.在项目的build.gradle中添加依赖 dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.10' } 2.在app的build.gradle中添加插件 apply plugin: 'com.google.protobuf' 3.在app的build.gradle的android目录下添加sourceSets sourceSets { main { java {
  • Gradle not able to detect osdetector plugin
    I am using OpenSSL for my Java GRPC project which uses gradle. I read the documetation which mentions that we should make security settings as mentioned in this link. I have included the osdetector plugin in the build.gradle file. But when I build the project, gradle is not able to resolve the osdetector plugin and throwing error > Failed to apply plugin [id 'com.google.protobuf'] > Plugin with id 'osdetector' not found. My gradle file is as follows: def neo4jVersion = "2.3.3" apply plugin: 'application' apply plugin: 'java' apply plugin: 'com.google.protobuf' apply plugin: 'idea' apply plugin
  • Gradle 无法检测 osdetector 插件(Gradle not able to detect osdetector plugin)
    问题 我在使用 gradle 的 Java GRPC 项目中使用 OpenSSL。 我阅读了文档,其中提到我们应该按照此链接中的说明进行安全设置。 我在 build.gradle 文件中包含了 osdetector 插件。 但是当我构建项目时,gradle 无法解析 osdetector 插件并抛出错误 > Failed to apply plugin [id 'com.google.protobuf'] > Plugin with id 'osdetector' not found. 我的gradle文件如下: def neo4jVersion = "2.3.3" apply plugin: 'application' apply plugin: 'java' apply plugin: 'com.google.protobuf' apply plugin: 'idea' apply plugin: 'com.google.osdetector' buildscript { repositories { mavenCentral() } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.7.3' classpath 'com.google.gradle:osdetector-gradle
  • How to implement com.google.protobuf.BlockingRpcChannel for gRPC generated Java code?
    I recently took a proto file representing a gRPC service and generated Java code from it. However, all the interfaces expect a com.google.protobuf.BlockingRpcChannel and I don't have any idea on how to create it. When I look at example, I see people using io.grpc.ManagedChannel but that is because the generated Java code used that type instead. I'm not sure if it's because i'm using a specific version of protobuf or what? public static BlockingInterface newBlockingStub(com.google.protobuf.BlockingRpcChannel channel) { return new BlockingStub(channel); } Here are examples of what i've seen
  • 在 Eclipse IDE 中使用 maven/m2e 从 .proto 自动生成 Java(Automatically generate Java from .proto with maven/m2e in Eclipse IDE)
    问题 对于我的团队,我想将 maven/eclipse build 配置为从*.proto文件(在使用 gRPC 的项目中)自动生成 Java 代码。 目前需要运行mvn generate-source或mvn protobuf:compile (如插件使用页面)。 或者相同的 add Run 配置来调用 maven 目标compile 。 每当刷新 Eclipse Maven 项目( Alt + F5 )或重新启动 IDE 时,都会重建项目,但不会出现在target/generated ,从而将项目变成红色。 所以需要生成和刷新项目( F5 )。 更新 Eclipse 需要在.clathpath文件中配置源文件夹。 据我所知,这应该是 m2e 连接器,但我只能找到一个 https://github.com/masterzen/m2e-protoc-connector 用于最古老的 Google s plugin com.google.protobuf.tools:maven-protoc-plugin ,目前在 https://github.com/grpc/grpc-java 中甚至没有提到 我们使用完全引用/推荐的 <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin<
  • 将协议缓冲区集成到 Maven2 构建中(Integrate Protocol Buffers into Maven2 build)
    问题 我正在一个现有的、相当普通的 Maven 2 项目中试验协议缓冲区。 目前,我每次需要更新生成的源时都会调用一个 shell 脚本。 这显然很麻烦,因为我希望在每次构建之前自动生成源代码。 希望不要诉诸可耻的hackery。 所以,我的问题有两个方面: 远景:是否有 Maven 2 的“协议缓冲区插件”可以以自动方式实现上述目标? 谷歌代码上有一个分支,其作者似乎已经尝试实现这样的插件。 不幸的是,它没有通过代码审查或被合并到 protobuf 主干中。 因此,该插件的状态未知。 可能更现实:缺少实际的插件,我还能如何从我的 Maven 2 构建中调用protoc ? 我想我可以将我现有的 shell 脚本连接到antrun调用或类似的东西中。 个人经验最受赞赏。 回答1 您将在 Protocol Buffers 讨论组的 Protocol Buffers Compiler Maven Plug-In 线程中的 Protocol Buffers 存储库中找到有关该插件的一些信息。 我的理解是它可用但缺乏测试。 我想试一试。 或者你可以只使用antrun插件(从上面提到的线程粘贴的antrun ): <build> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions>
  • Maven & Protobuf 编译错误:在包 com.google.protobuf 中找不到符号(Maven & Protobuf compile error: Cannot find symbol in package com.google.protobuf)
    问题 我是 Linux 和 Protobuf 的新手。我需要帮助。 我正在尝试“mvn package”一个包含许多“.proto”文件的项目,当然还有一个 pom.xml 文件...... 我在 Ubuntu 上工作 ======================================== 错误 当我运行“mvn package”时,我收到此错误: 后 ... Compiling 11 source files to .../target/classes ... 我收到一堆这些错误: [ERROR] .../target/generated-sources/...java:[16457,30] cannot find symbol [ERROR] symbol : class Parser [ERROR] location: package com.google.protobuf [ERROR] [ERROR] .../target/generated-sources/...java:[17154,37] cannot find symbol [ERROR] symbol : class Parser [ERROR] location: package com.google.protobuf [ERROR] [ERROR] .../target/generated
  • simple protobuf compilation with gradle
    If you're looking for sample gradle protobuf project look here. I'm having hard time with gradle and protobuf, i want to create a simple gradle project that will take any proto files from default src/main/proto, src/test/proto and compile them to src/main/java, src/test/java accordingly, then pack that into a jar and publish to local repo. Unfortunately i'm new to gradle and cant figure out how the original project is composed. Here is my unfinished build.gradle file apply plugin: 'java' apply plugin: "com.google.protobuf" buildscript { repositories { mavenCentral() } dependencies { classpath
  • Import Protobuf generated classes using Gradle in IntelliJ
    I am having trouble importing Protobuf generated classes using Gradle. This is how my project tree looks like: I've tried marking the packages as Source, I have tried all possible combinations of imports: import generated.main.grpc.GreeterGrpc; import main.java.HelloRequest; import java.*; import HelloRequest; None of them works. Here is my build.gradle: group 'andu' version '1.0-SNAPSHOT' apply plugin: 'java' apply plugin: 'com.google.protobuf' sourceCompatibility = 1.5 repositories { mavenCentral() maven { url "https://plugins.gradle.org/m2/" } } buildscript { repositories { mavenCentral() }
  • IDEA中protobuf 各版本编译java文件和js文件
    1、protobuf文件: syntax = "proto2"; message MsgProto { required int32 version = 1; optional LineProto line = 2; } message LineProto { required int32 number = 1; repeated Line list = 3; } message Line { required int32 interNr = 1; optional int32 dirStatus = 2; } proto文件放在maven框架main文件夹下的与java文件夹平级下: 在这里插入图片描述 2、pom.xml文件: <properties> <!--grpc版本号--> <grpc.version>1.7.0</grpc.version> <!--protobuf 版本号--> <protobuf.version>3.4.0</protobuf.version> </properties> protobuf的依赖库: <dependencies> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf
  • Maven & Protobuf compile error: Cannot find symbol in package com.google.protobuf
    I'm new to Linux and Protobuf.. I need help. I'm trying to "mvn package" a project that contains many ".proto" files, and a pom.xml file of course... I'm working on Ubuntu ======================================= ERROR When I run "mvn package", I receive this error: after ... Compiling 11 source files to .../target/classes ... I get a bunch of these errors: [ERROR] .../target/generated-sources/...java:[16457,30] cannot find symbol [ERROR] symbol : class Parser [ERROR] location: package com.google.protobuf [ERROR] [ERROR] .../target/generated-sources/...java:[17154,37] cannot find symbol [ERROR]
  • Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
    I have been trying to build a code using maven. But I am stuck with an error. The code is available on this github repo. google-play-crawler My system configurations as shown by maven is followning: Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:28+0530) Maven home: /Users/tushar/Downloads/apache-maven-3.0.5 Java version: 1.6.0_65, vendor: Apple Inc. Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home Default locale: en_US, platform encoding: MacRoman OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac" Following is the
  • Cannot import com.google.cloud.speech.v1.SpeechGrpc in Android
    I'm trying to use Google's Speech API in Android project. The example project works. I'm having trouble to use it in my own android app. build.gradle(Module:app) : apply plugin: 'com.android.application' apply plugin: 'com.google.protobuf' ext { supportLibraryVersion = '25.4.0' grpcVersion = '1.4.0' } android { compileSdkVersion 25 buildToolsVersion "25.0.3" defaultConfig { applicationId "ApplicationID" minSdkVersion 16 targetSdkVersion 24 // compileOptions { // sourceCompatibility JavaVersion.VERSION_1_5 // targetCompatibility JavaVersion.VERSION_1_5 // } } signingConfigs { release {
  • How to build Google protocol buffers and Kotlin using Gradle?
    I'm trying to build a project that uses both Google protocol buffers and Kotlin using Gradle. I want the proto files to compile into Java source, which is then called from my Kotlin code. My source files are arranged like this: src/main/proto/*.proto src/main/kotlin/*.kt src/test/kotlin/*.kt Here's my build.gradle file: version '1.0-SNAPSHOT' apply plugin: 'kotlin' apply plugin: 'java' apply plugin: 'com.google.protobuf' repositories { mavenCentral() maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" } } buildscript { ext.kotlin_version = '1.1-M02' repositories { mavenCentral() maven {
  • Grpc 实战Java 调用python
    文章目录 背景服务端客户端测试 背景 主要是为了解决在java代码中调用python服务的问题,考虑到性能的要求,还是决定采用RPC协议调用 服务端 接口定义文件,注意java和python定义文件相同 syntax = "proto3"; option java_multiple_files = true; option java_package = "com.xx"; option java_outer_classname = "HelloWorldProto"; option objc_class_prefix = "HLW"; package grpc_demo; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1
  • 无法使用MAVEN进行编译并出现错误-无法执行目标org.apache.maven.plugins:maven-compiler-plugin:3.1:compile(Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile)
    问题 我一直在尝试使用Maven构建代码。 但是我陷入了一个错误。 该代码可在此github存储库上找到。 谷歌播放爬虫 我的系统配置如下所示: Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 19:21:28+0530) Maven home: /Users/tushar/Downloads/apache-maven-3.0.5 Java version: 1.6.0_65, vendor: Apple Inc. Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home Default locale: en_US, platform encoding: MacRoman OS name: "mac os x", version: "10.9", arch: "x86_64", family: "mac" 以下是该错误的Maven跟踪: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project
  • SpringBoot + GoogleProtobuf
    SpringBoot + GoogleProtobuf 项目地址: protobuf-simple :https://github.com/Cyanss/protobuf-simple 一、环境配置   protobuf-java版本的选择需要对应到C++等其他端的版本以及Maven中protobuf-java版本。这里选择3.4.0版本进行演示及测试。 电脑系统: Windows 10 x64 bit protobuf GitHub: https://github.com/protocolbuffers/protobuf protobuf 源码下载: protobuf-java-3.4.0.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.4.0/protobuf-java-3.4.0.zip protoc 编译器下载: protoc-3.4.0-win32.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.4.0/protoc-3.4.0-win32.zip 注:protoc编译器3.4.0版本只有32位安装包。 protobuf-java 依赖: <dependency> <groupId>com
  • idea下使用gradle多项目构建生成proto协议并使用
    idea下使用gradle多项目构建生成proto协议并使用 注意事项1.本文要达到的效果2. 建立目录结构根目录下setting.gradle配置根目录下build.gradleprotocol子项目的build.gradle中的配置: 3.写proto协议4.产生java代码5. 解决之前的警告6.使用proto协议写代码7.后记 注意事项 项目的路径不能有中文!不能有中文!不能有中文! 1.本文要达到的效果 我们的目的是在protocol子项目中写xx.proto的协议文件,然后产生java代码在shared项目中,其他项目依赖shared项目,从而让其他项目可以使用到proto协议。 2. 建立目录结构 根目录下setting.gradle配置 rootProject.name = 'multiProject' include 'project1' include 'project2' include 'protocol' include 'shared' 根目录下build.gradle 由于我需要java和kotlin混编,所以这里也有支持kotlin编译的配置,如果只是java项目,可以去掉对应导入。 buildscript { ext { kotlin_version = '1.3.72' } repositories { mavenCentral() }
  • 如何使用 Gradle 构建 Google 协议缓冲区和 Kotlin?(How to build Google protocol buffers and Kotlin using Gradle?)
    问题 我正在尝试使用 Gradle 构建一个同时使用 Google 协议缓冲区和 Kotlin 的项目。 我希望 proto 文件编译成 Java 源代码,然后从我的 Kotlin 代码中调用它。 我的源文件是这样排列的: src/main/proto/*.proto src/main/kotlin/*.kt src/test/kotlin/*.kt 这是我的build.gradle文件: version '1.0-SNAPSHOT' apply plugin: 'kotlin' apply plugin: 'java' apply plugin: 'com.google.protobuf' repositories { mavenCentral() maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" } } buildscript { ext.kotlin_version = '1.1-M02' repositories { mavenCentral() maven { url "http://dl.bintray.com/kotlin/kotlin-eap-1.1" } } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0