java类com.google.protobuf.GeneratedMessage的实例源码

SendUtils.java 文件源码 项目:Juice 阅读 25 收藏 0 点赞 0 评论 0
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;
        }

    }
AggregationMessageTest.java 文件源码 项目:metrics-aggregator-daemon 阅读 38 收藏 0 点赞 0 评论 0
@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]);
    }
}
ProtobufCodec.java 文件源码 项目:multi-engine 阅读 34 收藏 0 点赞 0 评论 0
@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);
    }
}
Task.java 文件源码 项目:java-mesos-util 阅读 38 收藏 0 点赞 0 评论 0
@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;
}
Task.java 文件源码 项目:java-mesos-util 阅读 42 收藏 0 点赞 0 评论 0
@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;
}
Offer.java 文件源码 项目:java-mesos-util 阅读 41 收藏 0 点赞 0 评论 0
@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;
}
Offer.java 文件源码 项目:java-mesos-util 阅读 32 收藏 0 点赞 0 评论 0
@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;
}
ExecutorDriverV1.java 文件源码 项目:java-mesos-util 阅读 35 收藏 0 点赞 0 评论 0
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();
}
AbstractDriverV1.java 文件源码 项目:java-mesos-util 阅读 33 收藏 0 点赞 0 评论 0
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);
    }
}
Command.java 文件源码 项目:java-mesos-util 阅读 41 收藏 0 点赞 0 评论 0
@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;
}
Command.java 文件源码 项目:java-mesos-util 阅读 46 收藏 0 点赞 0 评论 0
@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;
}
Framework.java 文件源码 项目:java-mesos-util 阅读 59 收藏 0 点赞 0 评论 0
@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;
}
Framework.java 文件源码 项目:java-mesos-util 阅读 38 收藏 0 点赞 0 评论 0
@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;
}
PooledPbrpcClient.java 文件源码 项目:navi-pbrpc 阅读 29 收藏 0 点赞 0 评论 0
/**
 * @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);
    }
}
SimplePbrpcClient.java 文件源码 项目:navi-pbrpc 阅读 34 收藏 0 点赞 0 评论 0
/**
 * @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);
    }
}
SimplePbrpcClient.java 文件源码 项目:navi-pbrpc 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 使用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());
    }
}
PbrpcClientChannel.java 文件源码 项目:navi-pbrpc 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 异步调用
 * 
 * @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");
    }

}
BlockingIOPooledPbrpcClient.java 文件源码 项目:navi-pbrpc 阅读 30 收藏 0 点赞 0 评论 0
/**
 * @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);
    }
}
SimpleMethodResolver.java 文件源码 项目:navi-pbrpc 阅读 28 收藏 0 点赞 0 评论 0
/**
 * 判断某个方法是否可以暴露为服务,这里的判断条件是满足以下
 * <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;
}
ProtobufCodec.java 文件源码 项目:navi-pbrpc 阅读 26 收藏 0 点赞 0 评论 0
/**
 * @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);
    }
}
StorageFormatRegistry.java 文件源码 项目:sql-layer 阅读 78 收藏 0 点赞 0 评论 0
/** 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);
    }
}
Transport.java 文件源码 项目:GameServerFramework 阅读 46 收藏 0 点赞 0 评论 0
/**
 * 发送消息
 *
 * @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;
}
BatchExecutor.java 文件源码 项目:cloud-bigtable-client 阅读 29 收藏 0 点赞 0 评论 0
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()));
}
Server.java 文件源码 项目:hpcourse 阅读 41 收藏 0 点赞 0 评论 0
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();
            }
        }
BaseTask.java 文件源码 项目:hpcourse 阅读 41 收藏 0 点赞 0 评论 0
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();
    }
}
UnitButtonGrouped.java 文件源码 项目:bco.bcozy 阅读 27 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
ProtobufExtensionLookup.java 文件源码 项目:coyote 阅读 32 收藏 0 点赞 0 评论 0
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;
}
Printer.java 文件源码 项目:protobuf-utils 阅读 44 收藏 0 点赞 0 评论 0
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();
            }
        }
    };
}
MessageInputStream.java 文件源码 项目:protobuf-utils 阅读 37 收藏 0 点赞 0 评论 0
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
        }
    };
}
WriteEvents.java 文件源码 项目:esj 阅读 25 收藏 0 点赞 0 评论 0
@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();
}


问题


面经


文章

微信
公众号

扫码关注公众号