本文整理汇总了Java中com.google.protobuf.Parser类的典型用法代码示例。如果您正苦于以下问题:Java Parser类的具体用法?Java Parser怎么用?Java Parser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Parser类属于com.google.protobuf包,在下文中一共展示了Parser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: extract
import com.google.protobuf.Parser; //导入依赖的package包/类
/**
* Attempts to extract a protocol buffer from the specified extra.
* @throws MalformedDataException if the intent is null, the extra is missing or not a byte
* array, or the protocol buffer could not be parsed.
*/
@NonNull
public static <T extends MessageLite> T extract(
@NonNull String extraName,
@NonNull Parser<T> protoParser,
@NonNull String failureDescription,
@Nullable Intent intent)
throws MalformedDataException {
if (intent == null) {
throw new MalformedDataException(failureDescription);
}
byte[] protoBytes = intent.getByteArrayExtra(extraName);
if (protoBytes == null) {
throw new MalformedDataException(failureDescription);
}
try {
return protoParser.parseFrom(protoBytes);
} catch (IOException ex) {
throw new MalformedDataException(failureDescription, ex);
}
}
示例2: populateParsersFromClasspath
import com.google.protobuf.Parser; //导入依赖的package包/类
public Map<MessageType, Parser<com.google.protobuf.Message>> populateParsersFromClasspath() {
Map<MessageType, Parser<com.google.protobuf.Message>> parsers = new HashMap<>();
List<Class<? extends com.google.protobuf.GeneratedMessageV3>> foundProtoMessages = new ArrayList<>();
new FastClasspathScanner()
.matchSubclassesOf(com.google.protobuf.GeneratedMessageV3.class, matchingClass ->
foundProtoMessages.add(matchingClass)).scan();
// This algorithm adds parsers for all protobuf messages in the classpath including base types such as com.google.protobuf.DoubleValue.
for (Class<? extends com.google.protobuf.GeneratedMessageV3> clazz : foundProtoMessages) {
try {
java.lang.reflect.Method method = clazz.getMethod("parser"); // static method, no arguments
@SuppressWarnings("unchecked")
Parser<com.google.protobuf.Message> parser = (Parser<com.google.protobuf.Message>) method.invoke(null, (Object[]) null); // static method, no arguments
parsers.put(MessageType.of(clazz), parser);
// too noisy: logger.debug("Added parser for protobuf type {}", clazz.getTypeName());
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {
// too noisy: logger.debug("Ignoring protobuf type {} as we cannot invoke static method parse().", clazz.getTypeName());
}
}
return parsers;
}
示例3: lectura
import com.google.protobuf.Parser; //导入依赖的package包/类
private void lectura() {
final byte[] buf = new byte[65536];
Parser<Protos.Respuesta> parser = Protos.Respuesta.parser();
try {
while (pending-- > 0) {
Protos.Respuesta resp = Utils.read(buf, bin, parser);
if (resp.getRcode() == 0) {
log.debug("OK conf {}", resp.getConfirmacion());
} else {
log.debug("ERR {}", resp.getError());
}
if (timers[resp.getId()] != null) {
timers[resp.getId()].stop();
}
}
} catch (IOException ex) {
log.error("Leyendo de socket", ex);
}
}
示例4: readMessageList
import com.google.protobuf.Parser; //导入依赖的package包/类
/**
* Reads a list of protos, using the provided parser, from the provided input stream.
* @throws IOException if the proto list could not be parsed.
*/
public static <T extends MessageLite> List<T> readMessageList(
InputStream stream,
Parser<T> parser)
throws IOException {
DataInputStream dis = new DataInputStream(stream);
int messageCount = dis.readInt();
ArrayList<T> messages = new ArrayList<>(messageCount);
for (int i = 0; i < messageCount; i++) {
messages.add(parser.parseDelimitedFrom(stream));
}
return messages;
}
示例5: toScanMetrics
import com.google.protobuf.Parser; //导入依赖的package包/类
public static ScanMetrics toScanMetrics(final byte[] bytes) {
Parser<MapReduceProtos.ScanMetrics> parser = MapReduceProtos.ScanMetrics.PARSER;
MapReduceProtos.ScanMetrics pScanMetrics = null;
try {
pScanMetrics = parser.parseFrom(bytes);
} catch (InvalidProtocolBufferException e) {
//Ignored there are just no key values to add.
}
ScanMetrics scanMetrics = new ScanMetrics();
if (pScanMetrics != null) {
for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
if (pair.hasName() && pair.hasValue()) {
scanMetrics.setCounter(pair.getName(), pair.getValue());
}
}
}
return scanMetrics;
}
示例6: subscribeTo
import com.google.protobuf.Parser; //导入依赖的package包/类
/**
* Subscribes to the entity states of the given type.
*
* <p>The method returns a {@link LiveData} of map (string ID -> entity state). The ID is
* the {@linkplain io.spine.Identifier#toString(Object) string representation} of
* the corresponding entity ID.
*
* <p>Currently, the element removal is not supported. If a {@link DocumentChange} of type other
* than {@link DocumentChange.Type#ADDED ADDED} or {@link DocumentChange.Type#MODIFIED MODIFIED}
* is encountered, an {@link UnsupportedOperationException} is thrown.
*
* @param targetType the class of the entity to subscribe to
* @param <T> the type of the entity to subscribe to
* @return an instance of {@link LiveData} for the observers to subscribe to
*/
public <T extends Message> LiveData<Map<String, T>> subscribeTo(Class<T> targetType) {
checkNotNull(targetType);
final CollectionReference targetCollection = collectionFor(targetType);
final MutableLiveData<Map<String, T>> result = new MutableLiveData<>();
targetCollection.addSnapshotListener((documentSnapshots, error) -> {
if (error != null) {
final String errorMsg = format(
"Error encountered while listening for the %s state updates.",
targetType
);
Log.e(TAG, errorMsg, error);
} else {
final Parser<T> parser = getParserFor(targetType);
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
deliverUpdate(change, result, parser);
}
}
});
return result;
}
示例7: deliverUpdate
import com.google.protobuf.Parser; //导入依赖的package包/类
/**
* Delivers the entity state update represented by the given {@link DocumentChange} to
* the observers of the given {@link LiveData}.
*
* @param change the Firestore document change
* @param destination the {@link LiveData} publishing the update
* @param parser the {@link Parser} for the target entity state type
* @param <T> the entity state type
*/
private static <T extends Message>
void deliverUpdate(DocumentChange change,
MutableLiveData<Map<String, T>> destination,
Parser<T> parser) {
final DocumentChange.Type type = change.getType();
final Map<String, T> currentData = destination.getValue();
final Map<String, T> newData = currentData == null
? newHashMap()
: newHashMap(currentData);
final DocumentSnapshot doc = change.getDocument();
final String id = parseMessageId(doc);
final T newMessage = parseMessage(doc, parser);
if (type == ADDED || type == MODIFIED) {
newData.put(id, newMessage);
} else {
throw newIllegalArgumentException("Unexpected document change: %s", type.toString());
}
destination.postValue(newData);
}
示例8: readFirstMatching
import com.google.protobuf.Parser; //导入依赖的package包/类
private static <T> Optional<T> readFirstMatching(Path path, Parser<T> parser, Predicate<T> predicate) {
try (InputStream inputStream = Files.newInputStream(path)) {
while (true) {
T message = parser.parseDelimitedFrom(inputStream);
if (message == null) {
break;
}
if (predicate.test(message)) {
return Optional.of(message);
}
}
} catch (IOException e) {
throw new IllegalStateException("unexpected error while parsing protobuf file: " + path, e);
}
return Optional.empty();
}
示例9: Subscriber
import com.google.protobuf.Parser; //导入依赖的package包/类
public Subscriber() {
Parser<T> parser = null;
try {
Class<?> cl = getClass();
while (!Subscriber.class.equals(cl.getSuperclass())) {
// case of multiple inheritance, we are trying to get the
// first available generic info
if (cl.getGenericSuperclass() instanceof ParameterizedType) {
break;
}
cl = cl.getSuperclass();
}
Class<T> type = ((Class<T>) ((ParameterizedType) cl.getGenericSuperclass())
.getActualTypeArguments()[0]);
parser = (Parser<T>) type.getDeclaredField("PARSER").get(null);
} catch (Exception e) {
System.out.println("Error: callback creation failed");
e.printStackTrace();
}
this.parser = parser;
}
示例10: responseBodyConverter
import com.google.protobuf.Parser; //导入依赖的package包/类
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (!(type instanceof Class<?>)) {
return null;
}
Class<?> c = (Class<?>) type;
if (!MessageLite.class.isAssignableFrom(c)) {
return null;
}
Parser<MessageLite> parser;
try {
Field field = c.getDeclaredField("PARSER");
//noinspection unchecked
parser = (Parser<MessageLite>) field.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Found a protobuf message but " + c.getName() + " had no PARSER field.");
}
return new ProtoResponseBodyConverter<>(parser, registry);
}
示例11: readProtobuf
import com.google.protobuf.Parser; //导入依赖的package包/类
/**
* De-serializes a protobuf from the given buffer.
* <p>
* The protobuf is assumed to be prefixed by a varint indicating its size.
* @param buf The buffer to de-serialize the protobuf from.
* @param parser The protobuf parser to use for this type of protobuf.
* @return An instance of the de-serialized type.
* @throws InvalidResponseException if the buffer contained an invalid
* protobuf that couldn't be de-serialized.
*/
static <T> T readProtobuf(final ChannelBuffer buf, final Parser<T> parser) {
final int length = HBaseRpc.readProtoBufVarint(buf);
HBaseRpc.checkArrayLength(buf, length);
final byte[] payload;
final int offset;
if (buf.hasArray()) { // Zero copy.
payload = buf.array();
offset = buf.arrayOffset() + buf.readerIndex();
buf.readerIndex(buf.readerIndex() + length);
} else { // We have to copy the entire payload out of the buffer :(
payload = new byte[length];
buf.readBytes(payload);
offset = 0;
}
try {
return parser.parseFrom(payload, offset, length);
} catch (InvalidProtocolBufferException e) {
final String msg = "Invalid RPC response: length=" + length
+ ", payload=" + Bytes.pretty(payload);
LOG.error("Invalid RPC from buffer: " + buf);
throw new InvalidResponseException(msg, e);
}
}
示例12: fromResponseBody
import com.google.protobuf.Parser; //导入依赖的package包/类
@Override
public Converter<ResponseData, ?> fromResponseBody(Type type, Annotation[] annotations) {
if (!(type instanceof Class<?>)) {
return null;
}
Class<?> c = (Class<?>) type;
if (!MessageLite.class.isAssignableFrom(c)) {
return null;
}
Parser<MessageLite> parser;
try {
Field field = c.getDeclaredField("PARSER");
//noinspection unchecked
parser = (Parser<MessageLite>) field.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Found a protobuf message but " + c.getName() + " had no PARSER field.");
}
return new ProtoResponseBodyConverter<>(parser);
}
示例13: createBinaryStream
import com.google.protobuf.Parser; //导入依赖的package包/类
public static <T extends GeneratedMessage> MessageInputStream<T> createBinaryStream(final InputStream is, String msgType) throws IOException {
final Registry reg = Registry.getInstance();
final ExtensionRegistry extReg = reg.getExtensionRegistry();
final GeneratedMessage msg = reg.getInstanceForType(msgType);
if (msg == null) {
throw new RuntimeException("Type " + msgType + " not found.");
}
final Parser parser = msg.getParserForType();
return new MessageInputStream<T>() {
{
next = readNext();
}
@Override
protected T readNext() throws IOException {
if (is.available() > 0) {
return (T) parser.parseDelimitedFrom(is, extReg);
}
return null;
}
};
}
示例14: parseDelimitedFrom
import com.google.protobuf.Parser; //导入依赖的package包/类
public static <T extends /*@NonNull*/ AbstractMessage> List<T> parseDelimitedFrom(
@Nullable ByteBuffer byteBuf, Parser<T> parser) throws IOException {
if (byteBuf == null) {
return ImmutableList.of();
}
SizeLimitBypassingParser<T> sizeLimitBypassingParser =
new SizeLimitBypassingParser<>(parser);
List<T> messages = Lists.newArrayList();
try (InputStream input = new ByteBufferInputStream(byteBuf)) {
T message;
while ((message = sizeLimitBypassingParser.parseDelimitedFrom(input)) != null) {
messages.add(message);
}
}
return messages;
}
示例15: fromResponse
import com.google.protobuf.Parser; //导入依赖的package包/类
@Override
public Converter<NetworkResponse, ?> fromResponse(Type type, Annotation[] annotations) {
if (!(type instanceof Class<?>)) {
return null;
}
Class<?> c = (Class<?>) type;
if (!MessageLite.class.isAssignableFrom(c)) {
return null;
}
Parser<MessageLite> parser;
try {
Field field = c.getDeclaredField("PARSER");
//noinspection unchecked
parser = (Parser<MessageLite>) field.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new IllegalArgumentException(
"Found a protobuf message but " + c.getName() + " had no PARSER field.");
}
return new ProtoResponseConverter<>(parser);
}