I have 3 .proto files under same folder, I plan to add LowDataBalanceRequest
and MobileRequest into `EventRequest
Command to generate Java sources:
protoc --java_out=/home/haifzhan/myproject/src/main/java/com/example/util star_event.proto ldb_event.proto generic_event.proto
star_event.proto and ldb_event.proto can generate Java source properly with no error, but generic_event.proto has errors as(my point is to show Errors, so I attache images other than source code):
One error says Descriptor instance might not be initialized
Another one is complaining bracket is expected.
Here's my generic_event.proto
import "star_event.proto";
import "ldb_event.proto";
message EventRequest {
optional LowDataBalanceRequest ldbRequest = 1;
optional MobileRequest mobileRequest = 2;
}
I am using version 2.6.1
Can anyone help?
I have figured it out.
A related issue on GithubJava: Invalid code generated when referencing a file with no package statement
The error is gone after I add option java_package in all .proto files:
option java_package = "com.example.util";
Here's my full .proto files:
option java_package = "com.example.util";
ldb_event.proto
option java_package = "com.example.util";
enum RequestTrigger {
LDB = 1;
OTHER = 2;
}
message LowDataBalanceRequest {
required string probe_id = 1;
required int64 unix_time = 2;
}
generic_event.proto
import "star_event.proto";
import "ldb_event.proto";
option java_package = "com.example.util";
message EventRequest {
optional LowDataBalanceRequest ldbRequest = 1;
optional MobileRequest mobileRequest = 2;
}
Related
Project B is trying to import Project A proto file. Project B pom.xml has dependencies for Project A.
ProjectB has person.proto
syntax = "proto3";
import "projectA/src/main/proto/vehical.proto";
message Person {
string name = 1;
int32 age = 2;
}
Project A has vehical.proto
syntax = "proto3";
message car{
string model= 1;
int32 year= 2;
}
while compilation getting below error
[ERROR] C:\eclipseWorkSpace\TestProto\src\main\proto\person.proto [0:0]: projectA/src/main/proto/vehical.proto: File not found.
person.proto: Import "projectA/src/main/proto/vehical.proto" was not found or had errors.
Any suggestion on how to resolve this experts?
I figured out I just put import "customer.proto"; in person.proto seems to solved my issue.
I want to be able to write a vim snippet that automatically turns into the required package.
E.g. expanding pkg while inside of .../com/theonlygust/project/Main.java would become
package com.theonlygusti.project;
I think the ways to do this are to either: read up the directory tree until seeing a TLD directory name (com, io, net, etc.) and then use the encountered directory names to build the package string, or to look up the directory tree for the pom.xml and find the package from there.
I learned about python interpolation.
I'm now trying this:
snippet pkg "Create package" b
package `!p
import os
from xml.etree import ElementTree
def get_package_name(pom_file_path):
namespaces = {'xmlns' : 'http://maven.apache.org/POM/4.0.0'}
tree = ElementTree.parse(pom_file_path)
root = tree.getroot()
groupId = root.find(".//xmlns:groupId", namespaces=namespaces)
artifactId = root.find(".//xmlns:artifactId", namespaces=namespaces)
return groupId.text + '.' + artifactId.text
def find_nearest_pom():
absolute_path = os.path.abspath(os.path.dirname('__file__')).split("/")
pom_dir_index = -1
# Find index of 'base_dir_name' element
while not os.path.isfile('/'.join(absolute_path[:pom_dir_index]) + '/pom.xml'):
pom_dir_index -= 1
return '/'.join(absolute_path[:pom_dir_index]) + '/pom.xml'
snip.rv = get_package_name(find_nearest_pom())`;
endsnippet
But I get the error
Name __file__ does not exist
And os.getcwd() doesn't work because that returns the directory from which vim was opened, not the directory that contains the current buffer.
I had a look at the snip object because I know it provides snip.fn to get the filename, but I couldn't find out if it provides the current file's directory.
Nevermind, finally learned that UltiSnips sets a global variable "path"
UltiSnips stores Java snippets in java.snippets, which on my machine is ~/.vim/bundle/vim-snippets/UltiSnips/java.snippets (I am usinghonza/vim-snippets` as well).
Snippets for Java are implemented using Python, so I have implemented the snippet below using Python as well (you can do it using multiple languages in UltiSnips).
There is already a snippet for package, which adds simply "package" word followed with a placeholder:
snippet pa "package" b
package $0
endsnippet
Let's create a pad snippet that will automatically insert package name, based on the directory chain, instead of the $0 placeholder:
snippet pad "package" b
package `!p
def get_package_string(base_dir_name):
import os
# Get absolute path of the package (without filename)
absolute_path = os.getcwd().split("/")
src_dir_index = 0
# Find index of 'base_dir_name' element
while absolute_path[src_dir_index] != base_dir_name:
src_dir_index+=1
# Create a 'package ' string, joining with dots
package_string = ".".join(absolute_path[src_dir_index+1:])
return package_string
# snip.rv is UltiSnips' return value we want to paste between ``
snip.rv = get_package_string("java")`
endsnippet
Note that this solution is based on the fact that in many Java projects, there is an src directory with main/java and test/java directories in it and you are editing one of the files in java directory (e.g. for src/main/com/google/common it will return com.google.common). You may need to modify this to be more flexible.
You can find more information about creating snippets in screencasts linked in its README.
I use a combination of the file path and the groupId and the artifactId from the nearest pom.xml (upwards)
global !p
import os
from xml.etree import ElementTree
def get_package_name(pom_file_path):
namespaces = {'xmlns' : 'http://maven.apache.org/POM/4.0.0'}
tree = ElementTree.parse(pom_file_path)
root = tree.getroot()
groupId = root.find(".//xmlns:groupId", namespaces=namespaces)
artifactId = root.find(".//xmlns:artifactId", namespaces=namespaces)
return groupId.text + '.' + artifactId.text
def find_nearest_pom():
current_file_dir = '/'.join((os.getcwd() + ('/' if os.getcwd()[-1] != '/' else '') + path).split('/')[:-1])
absolute_path = current_file_dir.split("/")
pom_dir_index = -1
if os.path.isfile('/'.join(absolute_path) + '/pom.xml'):
return '/'.join(absolute_path) + '/pom.xml'
# Find index of 'base_dir_name' element
while not os.path.isfile('/'.join(absolute_path[:pom_dir_index]) + '/pom.xml'):
pom_dir_index -= 1
return '/'.join(absolute_path[:pom_dir_index]) + '/pom.xml'
def get_file_package():
current_file_location = '.'.join((os.getcwd() + ('/' if os.getcwd()[-1] != '/' else '') + path).split('/')[:-1])
package = get_package_name(find_nearest_pom())
return package + current_file_location.split(package)[1]
endglobal
snippet pkg "package" b
package `!p snip.rv = get_file_package()`;
endsnippet
The code below doesn't work. Is it the best way to use Any? I'm trying to read from/write to Any and identify the type stored by Any.
My .proto:
syntax = "proto3";
import "google/protobuf/any.proto";
message CommandListPrinters {
}
message Commands {
int32 id = 1;
repeated google.protobuf.Any command = 2;
}
my.java:
CommandListPrinters commandListPrinters = CommandListPrinters.newBuilder().build();
Any any = Any.newBuilder()
.setValue(commandListPrinters.toByteString()).build();
Commands.Builder commandsBuilder = Commands.newBuilder().setId(0);
commandsBuilder.addCommand(any);
Commands commands = commandsBuilder.build();
//
byte [] ba = commands.toByteArray();
Commands cmds2 = Commands.parseFrom(ba);
for (Any any2 : cmds2.getCommandList()) {
Descriptor fe = any2.getDescriptorForType();
// This IF is FALSE;
if (fe.equals(CommandListPrinters.getDescriptor()) ) {
CommandListPrinters cmdLR = CommandListPrinters.parseFrom(any2.getValue());
}
}
I'm new to stackoverflow, so I can't comment, but I was wondering:
why does your CommandListPrinters message has no fields?
Calling
CommandListPrinters.getDescriptor()
makes me think CommandListPrinters should have a field descriptor. Also the Any proto doesn't have a field named descriptor_for_type either. See https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto
So
Descriptor fe = any2.getDescriptorForType();
doesn't makes much sense either.
So when an error occurred during runtime, the log always show a link to the specific error and you can click on it to be taken there directly.
I'm looking to exploit this function for my own use (since finding where the log is generated across multiple files can be a pain). Of course you can just put the source in the log key but if I'm able to link it just the way Android Studio / Intellij IDEAS does it with the error output, that would be MASSIVELY helpful. Thanks.
The following code will be a work-around to print the logged function name and line number (in Java):
private static String _FUNC_() {
int STACK_LEVEL = 2;
StackTraceElement traceElement = ((new Exception()).getStackTrace())[STACK_LEVEL];
StringBuilder sb = new StringBuilder();
sb.append("<");
String className = traceElement.getClassName();
className = className.substring(className.lastIndexOf(".") + 1);
sb.append(className);
sb.append(":");
sb.append(traceElement.getMethodName());
sb.append(":");
sb.append(traceElement.getLineNumber());
sb.append("> ");
return sb.toString();
}
I am developing a Client-Server-application which uses Google Protocol Buffers.
Unfortunatelly when I am building the protocol buffer response on the server side using the builder pattern I get a IndexOutOfBoundsException:
This is the line where I build the protobuf file:
Builder getVGResonseBuilder = App_getVGResponse.GetVGResponse.newBuilder().getVGBuilder(0);
[some more code that uses the builder patterns]
getVGResponseBuilder.set...
getVGResponseBuilder.set...
the error occures in the first line of code.
here is the protobuf definition (ofc I have compiled it! The compiled calss is App_getVGResponse):
message GetVGResponse {
message VG {
optional string id = 1;
optional string g_id = 2;
optional int64 f_id = 3;
optional string g_name = 4;
}
repeated VG v_gp = 1;
}
Here is a excerpt of my stacktrace
Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: **Protocol message tag had invalid wire type.**
at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:78)
at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:498)
at com.google.protobuf.GeneratedMessage$Builder.parseUnknownField(GeneratedMessage.java:439)
and the debugger at runtime shows ma the variable:
e
-> cause: IndexOutOfBoundsException (id=12291)
-> detaiMessage: Index: 0, Size: 0 (id=12324)
-> stackTrace null
personally I create the "child builder" then add it to the parent builder. i.e.
App_GetVGResponse.GetVGResponse.Builder bldr = App_GetVGResponse.GetVGResponse.newBuilder();
App_GetVGResponse.GetVGResponse.VG.Builder childBldr = App_GetVGResponse.GetVGResponse.VG.newBuilder();
childBldr.setId(value);
...........
bldr.addVGp(childBldr);
I think the error is because you get the "child" builder before adding one