public static void sendCall(GeneratedMessage call, Protocol protocol, String streamId, String url) throws IOException { log.debug("[call] " + call); Restty restty = Restty.create(url) .addAccept(protocol.mediaType()) .addMediaType(protocol.mediaType()) .requestBody(protocol.getSendBytes(call)); if (StringUtils.isNotBlank(streamId)) { restty.addHeader("Mesos-Stream-Id", streamId); } try { restty.postNoResponse(); } catch (IOException e) { log.warn("send call to mesos master failed, due to : " + e); throw e; } }
@Test public void testHostIdentification() { final GeneratedMessage protobufMessage = Messages.HostIdentification.getDefaultInstance(); final AggregationMessage message = AggregationMessage.create(protobufMessage); Assert.assertNotNull(message); Assert.assertSame(protobufMessage, message.getMessage()); final Buffer vertxBuffer = message.serialize(); final byte[] messageBuffer = vertxBuffer.getBytes(); final byte[] protobufBuffer = protobufMessage.toByteArray(); ByteString.fromArray(vertxBuffer.getBytes()); // Assert length Assert.assertEquals(protobufBuffer.length + 5, messageBuffer.length); Assert.assertEquals(protobufBuffer.length + 5, vertxBuffer.getInt(0)); Assert.assertEquals(protobufBuffer.length + 5, message.getLength()); // Assert payload type Assert.assertEquals(1, messageBuffer[4]); // Assert the payload was not corrupted for (int i = 0; i < protobufBuffer.length; ++i) { Assert.assertEquals(protobufBuffer[i], messageBuffer[i + 5]); } }
@Override public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException { try { if (data == null || data.length == 0) { return null; } Method m = PROTOBUF_METHOD_CACHE.getComputeResult(clazz.getName() + METHOD_NAME_PARSEFROM, new Callable<Method>() { @Override public Method call() throws Exception { return clazz.getMethod(METHOD_NAME_PARSEFROM, byte[].class); } }); GeneratedMessage msg = (GeneratedMessage) m.invoke(clazz, data); return (T) msg; } catch (Exception e) { throw new CodecException("Decode failed due to " + e.getMessage(), e); } }
@Override public Task proto0(GeneratedMessage message) { org.apache.mesos.Protos.TaskInfo task = (org.apache.mesos.Protos.TaskInfo) message; name = task.getName(); id = task.getTaskId().getValue(); slaveId = task.getSlaveId().getValue(); resources.clear(); for (org.apache.mesos.Protos.Resource resource : task.getResourcesList()) resources.add(new Resource().proto0(resource)); if (task.hasExecutor()) executor = new Executor().proto0(task.getExecutor()); if (task.hasCommand()) command = new Command().proto0(task.getCommand()); if (task.hasData()) data = task.getData().toByteArray(); return this; }
@Override public Task proto1(GeneratedMessage message) { org.apache.mesos.v1.Protos.TaskInfo task = (org.apache.mesos.v1.Protos.TaskInfo) message; name = task.getName(); id = task.getTaskId().getValue(); slaveId = task.getAgentId().getValue(); resources.clear(); for (org.apache.mesos.v1.Protos.Resource resource : task.getResourcesList()) resources.add(new Resource().proto1(resource)); if (task.hasExecutor()) executor = new Executor().proto1(task.getExecutor()); if (task.hasCommand()) command = new Command().proto1(task.getCommand()); if (task.hasData()) data = task.getData().toByteArray(); return this; }
@Override public Offer proto0(GeneratedMessage message) { org.apache.mesos.Protos.Offer offer = (org.apache.mesos.Protos.Offer) message; id = offer.getId().getValue(); frameworkId = offer.getFrameworkId().getValue(); slaveId = offer.getSlaveId().getValue(); hostname = offer.getHostname(); resources.clear(); for (org.apache.mesos.Protos.Resource resource : offer.getResourcesList()) resources.add(new Resource().proto0(resource)); attributes.clear(); for (org.apache.mesos.Protos.Attribute attribute : offer.getAttributesList()) attributes.add(new Attribute().proto0(attribute)); return this; }
@Override public Offer proto1(GeneratedMessage message) { org.apache.mesos.v1.Protos.Offer offer = (org.apache.mesos.v1.Protos.Offer) message; id = offer.getId().getValue(); frameworkId = offer.getFrameworkId().getValue(); slaveId = offer.getAgentId().getValue(); hostname = offer.getHostname(); resources.clear(); for (org.apache.mesos.v1.Protos.Resource resource : offer.getResourcesList()) resources.add(new Resource().proto1(resource)); attributes.clear(); for (org.apache.mesos.v1.Protos.Attribute attribute : offer.getAttributesList()) attributes.add(new Attribute().proto1(attribute)); return this; }
private Call newCall(GeneratedMessage.Builder builder) { Message obj = builder.build(); Call.Builder call = newBuilder(); call.setExecutorId(org.apache.mesos.v1.Protos.ExecutorID.newBuilder().setValue(System.getenv("MESOS_EXECUTOR_ID"))); call.setFrameworkId(org.apache.mesos.v1.Protos.FrameworkID.newBuilder().setValue(System.getenv("MESOS_FRAMEWORK_ID"))); if (obj instanceof Subscribe) { call.setSubscribe((Subscribe) obj); call.setType(Call.Type.SUBSCRIBE); } else if (obj instanceof Call.Message) { call.setMessage((Call.Message) obj); call.setType(Call.Type.MESSAGE); } else if (obj instanceof Update) { call.setUpdate((Update) obj); call.setType(Call.Type.UPDATE); } else throw new UnsupportedOperationException("Unsupported object " + obj); return call.build(); }
protected void sendCall(GeneratedMessage call) { try { StringWriter body = new StringWriter(); new JsonFormat().print(call, body); logger.debug("[call] " + body); Request request = new Request(url) .method(Request.Method.POST) .contentType("application/json") .accept("application/json") .body(("" + body).getBytes("utf-8")); if (streamId != null) // Mesos 0.25 has no streamId request.header("Mesos-Stream-Id", streamId); Request.Response response = request.send(); logger.debug("[response] " + response.code() + " - " + response.message() + (response.body() != null ? ": " + new String(response.body()) : "")); if (response.code() != 202) throw new DriverException("Response: " + response.code() + " - " + response.message() + (response.body() != null ? ": " + new String(response.body()) : "")); } catch (IOException e) { throw new DriverException(e); } }
@Override public Command proto0(GeneratedMessage message) { org.apache.mesos.Protos.CommandInfo command = (org.apache.mesos.Protos.CommandInfo) message; value = command.getValue(); uris.clear(); for (org.apache.mesos.Protos.CommandInfo.URI uri : command.getUrisList()) uris.add(new URI().proto0(uri)); if (command.hasEnvironment()) { env.clear(); for (org.apache.mesos.Protos.Environment.Variable var : command.getEnvironment().getVariablesList()) env.put(var.getName(), var.getValue()); } return this; }
@Override public Command proto1(GeneratedMessage message) { org.apache.mesos.v1.Protos.CommandInfo command = (org.apache.mesos.v1.Protos.CommandInfo) message; value = command.getValue(); uris = new ArrayList<>(); for (org.apache.mesos.v1.Protos.CommandInfo.URI uri : command.getUrisList()) uris.add(new URI().proto1(uri)); if (command.hasEnvironment()) { env = new LinkedHashMap<>(); for (org.apache.mesos.v1.Protos.Environment.Variable var : command.getEnvironment().getVariablesList()) env.put(var.getName(), var.getValue()); } return this; }
@Override public Framework proto0(GeneratedMessage message) { org.apache.mesos.Protos.FrameworkInfo framework = (org.apache.mesos.Protos.FrameworkInfo) message; if (framework.hasId()) id = framework.getId().getValue(); if (framework.hasName()) name = framework.getName(); if (framework.hasUser()) user = framework.getUser(); if (framework.hasFailoverTimeout()) timeout = new Period((long)framework.getFailoverTimeout() + "s"); checkpoint = framework.getCheckpoint(); role = framework.getRole(); if (framework.hasPrincipal()) principal = framework.getPrincipal(); return this; }
@Override public Framework proto1(GeneratedMessage message) { org.apache.mesos.v1.Protos.FrameworkInfo framework = (org.apache.mesos.v1.Protos.FrameworkInfo) message; if (framework.hasId()) id = framework.getId().getValue(); if (framework.hasName()) name = framework.getName(); if (framework.hasUser()) user = framework.getUser(); if (framework.hasFailoverTimeout()) timeout = new Period((long)framework.getFailoverTimeout() + "s"); checkpoint = framework.getCheckpoint(); role = framework.getRole(); if (framework.hasPrincipal()) principal = framework.getPrincipal(); return this; }
/** * @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#asyncTransport(java.lang.Class, * com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg) */ @Override public <T extends GeneratedMessage> CallFuture<T> asyncTransport(Class<T> responseClazz, PbrpcMsg pbrpcMsg) { PbrpcClientChannel channel = channelPool.getResource(); try { CallFuture<T> res = channel.asyncTransport(responseClazz, pbrpcMsg, this.readTimeout); return res; } catch (Exception e) { LOG.error("asyncTransport failed, " + e.getMessage(), e); channelPool.returnBrokenResource(channel); throw new PbrpcException("Pbrpc invocation failed on " + getInfo() + ", " + e.getMessage(), e); } finally { channelPool.returnResource(channel); } }
/** * @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#asyncTransport(java.lang.Class, * com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg) */ public <T extends GeneratedMessage> CallFuture<T> asyncTransport(Class<T> responseClazz, PbrpcMsg pbrpcMsg) { try { if (isShortAliveConn) { ChannelFuture channelFuture = connect().sync(); Channel ch = channelFuture.channel(); return doAsyncTransport(ch, responseClazz, pbrpcMsg); } else { return doAsyncTransport(this.channel, responseClazz, pbrpcMsg); } } catch (Exception e) { LOG.error("Failed to transport to " + getInfo() + " due to " + e.getMessage(), e); throw new PbrpcException(e); } }
/** * 使用channel进行数据发送 * * @param ch * @param responseClazz * @param pbrpcMsg * @return */ protected <T extends GeneratedMessage> CallFuture<T> doAsyncTransport(Channel ch, Class<T> responseClazz, PbrpcMsg pbrpcMsg) { if (ch != null) { int uuid = IdGenerator.genUUID(); pbrpcMsg.setLogId(uuid); CallFuture<T> future = CallFuture.newInstance(); CallbackPool.put(uuid, this.readTimeout, this.isShortAliveConn, ch, responseClazz, future); ch.writeAndFlush(pbrpcMsg); LOG.debug("Send message " + pbrpcMsg + " done"); return future; } else { LOG.error("Socket channel is not well established, so failed to transport on " + getInfo()); throw new PbrpcConnectionException( "Socket channel is not well established,so failed to transport on " + getInfo()); } }
/** * 异步调用 * * @param responseClazz * @param pbrpcMsg * @param readTimeout * 客户端调用超时时间 * @return * @throws Exception */ public <T extends GeneratedMessage> CallFuture<T> asyncTransport(Class<T> responseClazz, PbrpcMsg pbrpcMsg, int readTimeout) throws Exception { if (channelFuture != null) { try { int uuid = IdGenerator.genUUID(); pbrpcMsg.setLogId(uuid); CallFuture<T> future = CallFuture.newInstance(); CallbackPool.put(uuid, readTimeout, false, null, responseClazz, future); // long start = System.currentTimeMillis(); channelFuture.channel().writeAndFlush(pbrpcMsg); // LOG.info("Send message " + pbrpcMsg + " done using " + (System.currentTimeMillis() - start) + "ms"); return future; } catch (Exception e) { LOG.error( "Failed to transport to " + channelFuture.channel() + " due to " + e.getMessage(), e); throw new PbrpcException(e); } } else { LOG.error("Socket channel is not well established, so failed to transport"); throw new PbrpcException( "ChannelFuture is null! Socket channel is not well established, so failed to transport"); } }
/** * @see com.baidu.beidou.navi.pbrpc.client.PbrpcClient#syncTransport(java.lang.Class, * com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg) */ @Override public <T extends GeneratedMessage> T syncTransport(Class<T> responseClazz, PbrpcMsg pbrpcMsg) { BlockingIOPbrpcClient client = socketPool.getResource(); try { T res = client.syncTransport(responseClazz, pbrpcMsg); return res; } catch (Exception e) { LOG.error("asyncTransport failed, " + e.getMessage(), e); socketPool.returnBrokenResource(client); throw new PbrpcException("Pbrpc invocation failed on " + getInfo() + ", " + e.getMessage(), e); } finally { socketPool.returnResource(client); } }
/** * 判断某个方法是否可以暴露为服务,这里的判断条件是满足以下 * <ul> * <li>1)参数只有一个</li> * <li>2)参数必须是protoc自动生成的GeneratedMessage类型的子类</li> * <li>3)返回不能为void</li> * <li>4)返回必须是protoc自动生成的GeneratedMessage类型的子类</li> * </ul> * * @see com.baidu.beidou.navi.pbrpc.server.core.MethodResolver#isSupport(java.lang.reflect.Method) */ @Override public boolean isSupport(Method m) { Class<?>[] paramTypes = m.getParameterTypes(); Class<?> returnType = m.getReturnType(); if (paramTypes.length != 1) { LOG.warn("Pbrpc only supports one parameter, skip " + m.getName()); return false; } if (paramTypes[0].isAssignableFrom(GeneratedMessage.class)) { LOG.warn("Method argument type is not GeneratedMessage, skip " + m.getName()); return false; } if (ReflectionUtil.isVoid(returnType)) { LOG.warn("Method return type should not be void, skip " + m.getName()); return false; } if (returnType.isAssignableFrom(GeneratedMessage.class)) { LOG.warn("Method return type is not GeneratedMessage, skip " + m.getName()); return false; } return true; }
/** * @see com.baidu.beidou.navi.pbrpc.codec.Codec#decode(java.lang.Class, byte[]) */ @Override public Object decode(final Class<?> clazz, byte[] data) throws CodecException { try { if (data == null || data.length == 0) { return null; } Method m = PROTOBUF_METHOD_CACHE.get(clazz.getName() + METHOD_NAME_PARSEFROM, new Callable<Method>() { @Override public Method call() throws Exception { return clazz.getMethod(METHOD_NAME_PARSEFROM, byte[].class); } }); GeneratedMessage msg = (GeneratedMessage) m.invoke(clazz, data); return msg; } catch (Exception e) { throw new CodecException("Decode failed due to " + e.getMessage(), e); } }
/** Register a new {@link StorageFormat}. * @param protobufExtension the extension field that keys use of this format * @param sqlIdentifier the <code>STORAGE_FORMAT</code> identifier that keys use of this format or <code>null</code> * @param descriptionClass that specific class used to hold this format * @param storageFormat the mapping handler */ public <T extends StorageDescription> void registerStorageFormat(GeneratedMessage.GeneratedExtension<Storage,?> protobufExtension, String sqlIdentifier, Class<T> descriptionClass, StorageFormat<T> storageFormat) { int fieldNumber = protobufExtension.getDescriptor().getNumber(); if (formatsByField.containsKey(fieldNumber)) throw new IllegalArgumentException("there is already a StorageFormat registered for field " + fieldNumber); if ((sqlIdentifier != null) && formatsByIdentifier.containsKey(sqlIdentifier)) throw new IllegalArgumentException("there is already a StorageFormat registered for STORAGE_FORMAT " + sqlIdentifier); if (!isDescriptionClassAllowed(descriptionClass)) { throw new IllegalArgumentException("description " + descriptionClass + " not allowed for " + getClass().getSimpleName()); } extensionRegistry.add(protobufExtension); Format<T> format = new Format<T>(protobufExtension, sqlIdentifier, descriptionClass, storageFormat); formatsInOrder.add(format); formatsByField.put(fieldNumber, format); if (sqlIdentifier != null) { formatsByIdentifier.put(sqlIdentifier, format); } }
/** * 发送消息 * * @param session * 会话对象 * @param module * 消息对象 * @return 发送是否成功 */ public static boolean write(GameSession session, GeneratedMessage module) { if (TransportV2.ENABLE) { TransportV2.fireOut(session, module); return true; } int hash = module.getClass().hashCode(); if (_commandValueCaches.containsKey(hash)) { write(session, _commandValueCaches.get(hash), module); return true; } else { log.error(String.format( "BackendServer -> Transport[write]: Try Send Module But Unregister Module Command. Module:[%s].", module.getClass().toString())); } return false; }
ListenableFuture<? extends GeneratedMessage> issueRequest(Row row) { if (row instanceof Put) { return issuePutRequest((Put) row); } else if (row instanceof Delete) { return issueDeleteRequest((Delete) row); } else if (row instanceof Append) { return issueAppendRequest((Append) row); } else if (row instanceof Increment) { return issueIncrementRequest((Increment) row); } else if (row instanceof Get) { return issueGetRequest((Get) row); } else if (row instanceof RowMutations) { return issueRowMutationsRequest((RowMutations) row); } LOG.error("Encountered unknown action type %s", row.getClass()); return Futures.immediateFailedFuture( new IllegalArgumentException("Encountered unknown action type: " + row.getClass())); }
void sendResponse(GeneratedMessage message) { ServerResponse.Builder builder = ServerResponse.newBuilder(); builder.setRequestId(requestId); if (message instanceof SubmitTaskResponse) builder.setSubmitResponse((SubmitTaskResponse) message); if (message instanceof SubscribeResponse) builder.setSubscribeResponse((SubscribeResponse) message); if (message instanceof ListTasksResponse) builder.setListResponse((ListTasksResponse) message); ServerResponse response = builder.build(); // Отправляет на сокет сообщение response try { OutputStream out = socket.getOutputStream(); System.out.println("Size = " + response.getSerializedSize()); out.write(response.getSerializedSize()); response.writeTo(out); } catch (IOException e) { e.printStackTrace(); } }
void sendResponse(GeneratedMessage message) { Protocol.ServerResponse.Builder response = Protocol.ServerResponse.newBuilder(); response.setRequestId(requestId); if(message instanceof Protocol.ListTasksResponse) { response.setListResponse((Protocol.ListTasksResponse) message); } if(message instanceof Protocol.SubmitTaskResponse) { response.setSubmitResponse((Protocol.SubmitTaskResponse) message); } if(message instanceof Protocol.SubscribeResponse) { response.setSubscribeResponse((Protocol.SubscribeResponse) message); } Protocol.ServerResponse answer = response.build(); try { OutputStream outputStream = socket.getOutputStream(); outputStream.write(answer.getSerializedSize()); answer.writeTo(outputStream); } catch (IOException e) { e.printStackTrace(); } }
/** * Adds a UnitRemote to the list of this button's units. If it is the first unit after construction, * the correct icon is added to this button. * * @param unit UnitRemote that is supposed to be controlled by this grouped button. * @throws InterruptedException * @throws CouldNotPerformException */ public void addUnit(final UnitRemote<? extends GeneratedMessage> unit) throws InterruptedException, CouldNotPerformException { try { AbstractUnitPane content; content = UnitPaneFactoryImpl.getInstance().newInitializedInstance(unit.getConfig()); content.setDisplayMode(DisplayMode.ICON_ONLY); if (groupingPane.getChildren().isEmpty()) { SVGIcon icon = content.getIconSymbol(); iconPane.getChildren().add(icon); this.locationId = unit.getConfig().getPlacementConfig().getLocationId(); } content.setVisible(false); content.getStyleClass().add("units-button"); content.setStyle("-fx-background-color: rgb(64.0, 64.0, 64.0)"); this.groupingPane.getChildren().add(content); } catch (CouldNotPerformException ex) { throw new CouldNotPerformException("Could not create grouped unit button for config " + this, ex); } }
public ProtobufExtensionLookup add(Class<?> parent) { // find all the generated service extensions for the class specified for (Field field : parent.getFields()) { // skip anything that isn't a generated extension. should be fine as long as we dont start // mucking around with class loaders if (field.getType() != GeneratedMessage.GeneratedExtension.class) { continue; } try { GeneratedMessage.GeneratedExtension extension = (GeneratedMessage.GeneratedExtension) field.get(parent); Message defaultMessageInst = extension.getMessageDefaultInstance(); this.fields.put(defaultMessageInst.getClass(), extension); } catch (IllegalAccessException e) { LOG.warn("Could not not access " + field + " for " + parent); } } return this; }
public static Printer createPrinter(final MessageOutputStream mos, Expression expr) { if (expr.getType() != OBJECT_REFERENCE) { throw new IllegalStateException("Expression of type " + expr.getType() + " cannot be printed to MessageOutputStream"); } final ObjectExpression objExpr = ObjectExpression.class.cast(expr); return new Printer() { @Override public void print() { try { mos.write(GeneratedMessage.class.cast(objExpr.eval())); } catch (Exception ex) { ex.printStackTrace(); } } }; }
public static <T extends GeneratedMessage> MessageInputStream<T> createMemoryStream(final Queue<T> queue) { return new MessageInputStream<T>() { @Override public boolean hasMoreMessages() { return !queue.isEmpty(); } @Override public T peek() { return queue.peek(); } @Override public T read() throws IOException { return queue.remove(); } @Override protected T readNext() throws IOException { return null; // should never called } }; }
@Override public GeneratedMessage getDto(Settings settings) { ClientMessageDtos.WriteEvents.Builder web = ClientMessageDtos.WriteEvents.newBuilder(); web.setEventStreamId(streamId); web.setExpectedVersion(expectedVersion); web.setRequireMaster(settings.isRequireMaster()); List<ClientMessageDtos.NewEvent> newEvents = new ArrayList<>(); for (Event e : events) { newEvents.add(e.getMessageEvent()); } web.addAllEvents(newEvents); return web.build(); }
@SuppressWarnings("unchecked") public static final IRepeatedFieldMessageBuilder getBuilderForRepeatedChild( final Message.Builder builder, final FieldDescriptor field) { if (!field.isRepeated()) { throw new IllegalArgumentException("the field must be repeated"); } else if (field.getJavaType() != JavaType.MESSAGE) { throw new IllegalArgumentException("the field must be of Message type"); } else if (builder.getDescriptorForType() != field.getContainingType()) { throw new IllegalArgumentException("the field doen't belong to this type"); } if (builder instanceof GeneratedMessage.Builder) { final GeneratedMessage.Builder<?> generatedBuilder = (GeneratedMessage.Builder<?>) builder; return getGeneratedRepeatedFieldBuilder(generatedBuilder, field, generatedBuilder.getClass()); } else if (builder instanceof IBuilder2) { return new DynamicRepeatedFieldMessageBuilder((IBuilder2) builder, field); } else { throw new IllegalArgumentException("builder is not of a supported Builder type"); } }
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { summary = (Math.SummaryStatisticsDto)in.readObject(); GeneratedMessage ext = (GeneratedMessage)in.readObject(); if (ext == null) return; Math.SummaryStatisticsDto.Builder builder = summary.toBuilder(); if(ext instanceof Math.CategoricalSummaryDto) builder.setExtension(Math.CategoricalSummaryDto.categorical, (Math.CategoricalSummaryDto) ext); else if(ext instanceof Math.ContinuousSummaryDto) builder.setExtension(Math.ContinuousSummaryDto.continuous, (Math.ContinuousSummaryDto) ext); else if(ext instanceof Math.DefaultSummaryDto) builder.setExtension(Math.DefaultSummaryDto.defaultSummary, (Math.DefaultSummaryDto) ext); else if(ext instanceof Math.TextSummaryDto) builder.setExtension(Math.TextSummaryDto.textSummary, (Math.TextSummaryDto) ext); else if(ext instanceof Math.GeoSummaryDto) builder.setExtension(Math.GeoSummaryDto.geoSummary, (Math.GeoSummaryDto) ext); else if(ext instanceof Math.BinarySummaryDto) builder.setExtension(Math.BinarySummaryDto.binarySummary, (Math.BinarySummaryDto) ext); summary = builder.build(); }
private void writeObject(java.io.ObjectOutputStream stream) throws IOException { stream.writeObject(summary); GeneratedMessage ext = null; if(summary.hasExtension(Math.CategoricalSummaryDto.categorical)) ext = summary.getExtension(Math.CategoricalSummaryDto.categorical); else if(summary.hasExtension(Math.ContinuousSummaryDto.continuous)) ext = summary.getExtension(Math.ContinuousSummaryDto.continuous); else if(summary.hasExtension(Math.DefaultSummaryDto.defaultSummary)) ext = summary.getExtension(Math.DefaultSummaryDto.defaultSummary); else if(summary.hasExtension(Math.TextSummaryDto.textSummary)) ext = summary.getExtension(Math.TextSummaryDto.textSummary); else if(summary.hasExtension(Math.GeoSummaryDto.geoSummary)) ext = summary.getExtension(Math.GeoSummaryDto.geoSummary); else if(summary.hasExtension(Math.BinarySummaryDto.binarySummary)) ext = summary.getExtension(Math.BinarySummaryDto.binarySummary); stream.writeObject(ext); }
public GeneratedMessage copyTo() { ChatMsgProto.Builder builder = ChatMsgProto.newBuilder(); builder.setMainType(type.mainType); builder.setSubType(type.subType); builder.setChannelId(channelId); builder.setTargetUserId(targetUserId+""); if(userName != null){ builder.setUserName(userName); } if(targetUserName != null){ builder.setTargetUserName(targetUserName); } builder.setUserId(userId+""); builder.setUnionId(unionId); builder.setMsg(msg); return builder.build(); }
@Override public byte[] encode(final GeneratedMessage msg) { final REEFProtocol.REEFMessage.Builder message = REEFProtocol.REEFMessage.newBuilder(); if (msg instanceof ClientRuntimeProtocol.JobControlProto) { message.setJobControl((ClientRuntimeProtocol.JobControlProto) msg); } else if (msg instanceof ReefServiceProtos.RuntimeErrorProto) { message.setRuntimeError((ReefServiceProtos.RuntimeErrorProto) msg); } else if (msg instanceof ReefServiceProtos.JobStatusProto) { message.setJobStatus((ReefServiceProtos.JobStatusProto) msg); } else if (msg instanceof EvaluatorRuntimeProtocol.EvaluatorControlProto) { message.setEvaluatorControl((EvaluatorRuntimeProtocol.EvaluatorControlProto) msg); } else if (msg instanceof EvaluatorRuntimeProtocol.EvaluatorHeartbeatProto) { message.setEvaluatorHeartBeat((EvaluatorRuntimeProtocol.EvaluatorHeartbeatProto) msg); } else { throw new RuntimeException("Unable to serialize: " + msg); } return message.build().toByteArray(); }
public List<String> getGeneratedProtoClasses(String serviceName) { FastClasspathScanner cpScanner = new FastClasspathScanner(); ScanResult scanResult = cpScanner.scan(); List<String> oldProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessage.class); List<String> newProtobuf = scanResult.getNamesOfSubclassesOf(GeneratedMessageV3.class); List<String> retval = Stream.concat(oldProtobuf.stream(), newProtobuf.stream()).collect(Collectors.toList()); String[] packageTokens = serviceName.split("\\."); return retval.stream().filter(s -> protoFilePackageMatches(s, packageTokens)).collect(Collectors.toList()); }
/** * Writes a GeneratedMessage to a temp file, synchronizes it to disk * and then renames the file over file. * * @param msg GeneratedMessage to write to the file * @param file destination file * @throws IOException if a write error occurs or the File.renameTo * method returns false meaning the file could not be overwritten. */ public static void writeDelimitedTo(GeneratedMessage msg, File file) throws IOException { File tmp = Serialization.getMetaDataTempFile(file); FileOutputStream outputStream = new FileOutputStream(tmp); boolean closed = false; try { msg.writeDelimitedTo(outputStream); outputStream.getChannel().force(true); outputStream.close(); closed = true; if (!tmp.renameTo(file)) { //Some platforms don't support moving over an existing file. //So: //log.meta -> log.meta.old //log.meta.tmp -> log.meta //delete log.meta.old File oldFile = Serialization.getOldMetaDataFile(file); if (!file.renameTo(oldFile)) { throw new IOException("Unable to rename " + file + " to " + oldFile); } if (!tmp.renameTo(file)) { throw new IOException("Unable to rename " + tmp + " over " + file); } oldFile.delete(); } } finally { if (!closed) { try { outputStream.close(); } catch (IOException e) { LOGGER.warn("Unable to close " + tmp, e); } } } }
@Nullable public static < MessageType extends GeneratedMessage.ExtendableMessage<MessageType>, Type extends GeneratedMessage> Type getExtensionObject( GeneratedMessage.ExtendableMessageOrBuilder<MessageType> mob, ExtensionLite<MessageType, Type> extension) { if (mob.hasExtension(extension)) { return mob.getExtension(extension); } return null; }
@Nullable public static < MessageType extends GeneratedMessage.ExtendableMessage<MessageType>, Type extends GeneratedMessage> List<Type> getRepeatedExtensionObjects( GeneratedMessage.ExtendableMessageOrBuilder<MessageType> mob, ExtensionLite<MessageType, List<Type>> extension) { ImmutableList.Builder extensionList = ImmutableList.builder(); int extensionCount = mob.getExtensionCount(extension); for (int extensionIndex = 0; extensionIndex < extensionCount; ++extensionIndex) { extensionList.add(mob.getExtension(extension, extensionIndex)); } return extensionList.build(); }
/** * Given a GeneratedMessage object, get a Map of the state. Why? More Clojure-friendly * * @param status the GeneratedMessage * @return a key/value set of the fields */ public static Map<String, Object> statusToMap(GeneratedMessage status) { return status.getAllFields().entrySet(). stream(). collect(Collectors.toMap(e -> e.getKey().getName(), Map.Entry::getValue)); }