Java Code Examples for com.google.protobuf.RpcCallback

The following examples show how to use com.google.protobuf.RpcCallback. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gameserver   Source File: RpcTestService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void test(RpcController controller, RpcTestReq request,
		final RpcCallback<RpcTestResp> done) {
	final int sleep = request.getSleep();
	service.execute(new Runnable() {
		public void run() {
			System.out.println("sleep: " + sleep);
			try {
				Thread.sleep(sleep);
			} catch (InterruptedException e) {
			}
			RpcTestResp.Builder respBuilder = RpcTestResp.newBuilder();
			respBuilder.setSleep(sleep);
			done.run(respBuilder.build());
		}
	});
}
 
Example 2
Source Project: protobuf-socket-rpc   Source File: RpcForwarder.java    License: MIT License 6 votes vote down vote up
private void forwardToService(SocketRpcProtos.Request rpcRequest,
    RpcCallback<Message> callback, Service service,
    RpcController socketController) throws RpcException {
  // Get matching method
  MethodDescriptor method = getMethod(rpcRequest,
      service.getDescriptorForType());

  // Create request for method
  Message request = getRequestProto(rpcRequest,
      service.getRequestPrototype(method));

  // Call method
  try {
    service.callMethod(method, socketController, request, callback);
  } catch (RuntimeException e) {
    throw new RpcException(ErrorReason.RPC_ERROR,
        "Error running method " + method.getFullName(), e);
  }
}
 
Example 3
Source Project: phoenix   Source File: MetaDataEndpointImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getVersion(RpcController controller, GetVersionRequest request,
        RpcCallback<GetVersionResponse> done) {

    GetVersionResponse.Builder builder = GetVersionResponse.newBuilder();
    // The first 3 bytes of the long is used to encoding the HBase version as major.minor.patch.
    // The next 4 bytes of the value is used to encode the Phoenix version as major.minor.patch.
    long version = MetaDataUtil.encodeHBaseAndPhoenixVersions(this.env.getHBaseVersion());

    // The last byte is used to communicate whether or not mutable secondary indexing
    // was configured properly.
    version =
            MetaDataUtil.encodeMutableIndexConfiguredProperly(version,
                IndexManagementUtil.isWALEditCodecSet(this.env.getConfiguration()));

    builder.setVersion(version);
    done.run(builder.build());
}
 
Example 4
Source Project: phoenix   Source File: MetaDataEndpointImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void clearTableFromCache(RpcController controller, ClearTableFromCacheRequest request,
        RpcCallback<ClearTableFromCacheResponse> done) {
    byte[] schemaName = request.getSchemaName().toByteArray();
    byte[] tableName = request.getTableName().toByteArray();
    try {
        byte[] tenantId = request.getTenantId().toByteArray();
        byte[] key = SchemaUtil.getTableKey(tenantId, schemaName, tableName);
        ImmutableBytesPtr cacheKey = new ImmutableBytesPtr(key);
        Cache<ImmutableBytesPtr, PTable> metaDataCache =
                GlobalCache.getInstance(this.env).getMetaDataCache();
        metaDataCache.invalidate(cacheKey);
    } catch (Throwable t) {
        logger.error("incrementTableTimeStamp failed", t);
        ProtobufUtil.setControllerException(controller,
            ServerUtil.createIOException(SchemaUtil.getTableName(schemaName, tableName), t));
    }
}
 
Example 5
Source Project: incubator-tajo   Source File: TajoMasterService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getAllWorkerResource(RpcController controller, PrimitiveProtos.NullProto request,
                                 RpcCallback<TajoMasterProtocol.WorkerResourcesRequest> done) {

  TajoMasterProtocol.WorkerResourcesRequest.Builder builder =
      TajoMasterProtocol.WorkerResourcesRequest.newBuilder();
  Collection<Worker> workers = context.getResourceManager().getWorkers().values();

  for(Worker worker: workers) {
    WorkerResource resource = worker.getResource();

    TajoMasterProtocol.WorkerResourceProto.Builder workerResource =
        TajoMasterProtocol.WorkerResourceProto.newBuilder();

    workerResource.setHost(worker.getHostName());
    workerResource.setPeerRpcPort(worker.getPeerRpcPort());
    workerResource.setInfoPort(worker.getHttpPort());
    workerResource.setQueryMasterPort(worker.getQueryMasterPort());
    workerResource.setMemoryMB(resource.getMemoryMB());
    workerResource.setDiskSlots(resource.getDiskSlots());
    workerResource.setQueryMasterPort(worker.getQueryMasterPort());

    builder.addWorkerResources(workerResource);
  }
  done.run(builder.build());
}
 
Example 6
Source Project: swellrt   Source File: ServerRpcControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setFailed(String reason) {
  RpcCallback<Object> runCallback = null;
  synchronized (statusLock) {
    if (complete) {
      throw new IllegalStateException("Can't fail this RPC, as it is already complete.");
    } else {
      complete = true;
      callback.run(Rpc.RpcFinished.newBuilder().setFailed(true).setErrorText(reason).build());
      if (cancelCallback != null && !cancelled) {
        runCallback = cancelCallback;
      }
    }
  }
  if (runCallback != null) {
    runCallback.run(null);
  }
}
 
Example 7
Source Project: swellrt   Source File: ServerRpcControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void cancel() {
  RpcCallback<Object> runCallback = null;
  synchronized (statusLock) {
    if (cancelled) {
      throw new IllegalStateException("Can't cancel RPC, already cancelled.");
    }
    cancelled = true;
    if (cancelCallback != null && !complete) {
      runCallback = cancelCallback;
    }
  }
  if (runCallback != null) {
    runCallback.run(null);
  }
}
 
Example 8
Source Project: swellrt   Source File: WaveClientRpcImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that an open results in a proper wavelet commit update.
 */
public void testOpenCommit() {
  ProtocolOpenRequest request = ProtocolOpenRequest.newBuilder()
      .setParticipantId(USER)
      .setWaveId(ModernIdSerialiser.INSTANCE.serialiseWaveId(WAVE_ID)).build();
  counter = 0;
  rpcImpl.open(controller, request, new RpcCallback<ProtocolWaveletUpdate>() {
    @Override
    public void run(ProtocolWaveletUpdate update) {
      ++counter;
      assertEquals(WAVELET_NAME, getWaveletName(update.getWaveletName()));
      assertTrue(update.hasCommitNotice());
      assertEquals(BEGIN_VERSION,
          CoreWaveletOperationSerializer.deserialize(update.getCommitNotice()));
    }
  });
  frontend.waveletCommitted(WAVELET_NAME, BEGIN_VERSION);
  assertEquals(1, counter);
  assertFalse(controller.failed());
}
 
Example 9
Source Project: swellrt   Source File: WaveClientRpcImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that an open failure results in a proper wavelet failure update.
 */
public void testOpenFailure() {
  ProtocolOpenRequest request = ProtocolOpenRequest.newBuilder()
      .setParticipantId(USER)
      .setWaveId(ModernIdSerialiser.INSTANCE.serialiseWaveId(WAVE_ID)).build();
  counter = 0;
  rpcImpl.open(controller, request, new RpcCallback<ProtocolWaveletUpdate>() {
    @Override
    public void run(ProtocolWaveletUpdate update) {
      ++counter;
    }
  });
  frontend.doUpdateFailure(WAVE_ID, FAIL_MESSAGE);
  assertEquals(0, counter);
  assertTrue(controller.failed());
  assertEquals(new ChannelException(ResponseCode.INTERNAL_ERROR, FAIL_MESSAGE, null, Recoverable.NOT_RECOVERABLE, WAVE_ID, null).serialize(), controller.errorText());
}
 
Example 10
Source Project: swellrt   Source File: WaveClientRpcImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a failed submit results in the proper submit failure response.
 */
public void testSubmitFailed() {
  ProtocolSubmitRequest request = ProtocolSubmitRequest.newBuilder()
    .setDelta(DELTA)
    .setWaveletName(getWaveletUri(WAVELET_NAME)).build();
  counter = 0;
  rpcImpl.submit(controller, request, new RpcCallback<ProtocolSubmitResponse>() {
    @Override
    public void run(ProtocolSubmitResponse response) {
      ++counter;
      assertEquals(0, response.getOperationsApplied());
      assertEquals(FAIL_MESSAGE, response.getErrorMessage());
    }
  });
  frontend.doSubmitFailed(WAVELET_NAME, FAIL_MESSAGE);
  assertEquals(1, counter);
  assertFalse(controller.failed());
}
 
Example 11
Source Project: swellrt   Source File: WaveClientRpcImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a bad wave id request is gracefully handled.
 */
public void testOpenEncodingError() {
  ProtocolOpenRequest request = ProtocolOpenRequest.newBuilder()
      .setParticipantId(USER)
      .setWaveId("badwaveid").build();
  counter = 0;
  try {
    rpcImpl.open(controller, request, new RpcCallback<ProtocolWaveletUpdate>() {
      @Override
      public void run(ProtocolWaveletUpdate update) {
        ++counter;
        fail("Unexpected callback");
      }
    });
  } catch (IllegalArgumentException e) {
    controller.setFailed(FAIL_MESSAGE);
  }
  assertEquals(0, counter);
  assertTrue(controller.failed());
  assertFalse(controller.errorText().isEmpty());
}
 
Example 12
Source Project: swellrt   Source File: WaveClientRpcImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a bad wavelet name submit is gracefully handled.
 */
public void testSubmitEncodingError() {
  ProtocolSubmitRequest request = ProtocolSubmitRequest.newBuilder()
    .setDelta(DELTA)
    .setWaveletName("badwaveletname").build();
  counter = 0;
  try {
    rpcImpl.submit(controller, request, new RpcCallback<ProtocolSubmitResponse>() {
      @Override
      public void run(ProtocolSubmitResponse response) {
        ++counter;
        fail("Unexpected callback");
      }
    });
  } catch (IllegalArgumentException e) {
    controller.setFailed(FAIL_MESSAGE);
  }
  assertEquals(0, counter);
  assertTrue(controller.failed());
  assertFalse(controller.errorText().isEmpty());
}
 
Example 13
Source Project: ranger   Source File: RangerAuthorizationCoprocessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void grant(RpcController controller, GrantRequest request, RpcCallback<GrantResponse> done) {

	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerAuthorizationCoprocessor.grant()");
	}

	try {
		activatePluginClassLoader();
		implAccessControlService.grant(controller, request, done);
	} finally {
		deactivatePluginClassLoader();
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerAuthorizationCoprocessor.grant()");
	}
}
 
Example 14
Source Project: ranger   Source File: RangerAuthorizationCoprocessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void checkPermissions(RpcController controller, CheckPermissionsRequest request, RpcCallback<CheckPermissionsResponse> done) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerAuthorizationCoprocessor.checkPermissions()");
	}

	try {
		activatePluginClassLoader();
		implAccessControlService.checkPermissions(controller, request, done);
	} finally {
		deactivatePluginClassLoader();
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerAuthorizationCoprocessor.checkPermissions()");
	}
}
 
Example 15
Source Project: ranger   Source File: RangerAuthorizationCoprocessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getUserPermissions(RpcController controller, GetUserPermissionsRequest request,	RpcCallback<GetUserPermissionsResponse> done) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerAuthorizationCoprocessor.getUserPermissions()");
	}

	try {
		activatePluginClassLoader();
		implAccessControlService.getUserPermissions(controller, request, done);
	} finally {
		deactivatePluginClassLoader();
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerAuthorizationCoprocessor.getUserPermissions()");
	}
}
 
Example 16
Source Project: incubator-tajo   Source File: TajoWorkerManagerService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void executeExecutionBlock(RpcController controller,
                                  TajoWorkerProtocol.RunExecutionBlockRequestProto request,
                                  RpcCallback<PrimitiveProtos.BoolProto> done) {
  workerContext.getWorkerSystemMetrics().counter("query", "executedExecutionBlocksNum").inc();
  try {
    String[] params = new String[7];
    params[0] = "standby";  //mode(never used)
    params[1] = request.getExecutionBlockId();
    // NodeId has a form of hostname:port.
    params[2] = request.getNodeId();
    params[3] = request.getContainerId();

    // QueryMaster's address
    params[4] = request.getQueryMasterHost();
    params[5] = String.valueOf(request.getQueryMasterPort());
    params[6] = request.getQueryOutputPath();
    workerContext.getTaskRunnerManager().startTask(params);
    done.run(TajoWorker.TRUE_PROTO);
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    done.run(TajoWorker.FALSE_PROTO);
  }
}
 
Example 17
Source Project: tajo   Source File: TajoWorkerManagerService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void stopExecutionBlock(RpcController controller,
                               StopExecutionBlockRequest requestProto,
                               RpcCallback<PrimitiveProtos.BoolProto> done) {
  try {

    workerContext.getTaskManager().getDispatcher().getEventHandler().handle(
        new ExecutionBlockStopEvent(requestProto.getExecutionBlockId(), requestProto.getCleanupList()));

    done.run(TajoWorker.TRUE_PROTO);
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    controller.setFailed(e.getMessage());
    done.run(TajoWorker.FALSE_PROTO);
  }
}
 
Example 18
Source Project: kylin-on-parquet-v2   Source File: CubeVisitServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testVisitCube() throws Exception {
    RawScan rawScan = mockFullScan(gtInfo, getTestConfig());

    CoprocessorEnvironment env = PowerMockito.mock(RegionCoprocessorEnvironment.class);
    PowerMockito.when(env, "getRegion").thenReturn(region);

    final CubeVisitService service = new CubeVisitService();
    service.start(env);

    CubeVisitProtos.CubeVisitRequest request = mockFullScanRequest(gtInfo, Lists.newArrayList(rawScan));

    RpcCallback<CubeVisitProtos.CubeVisitResponse> done = new RpcCallback<CubeVisitProtos.CubeVisitResponse>() {
        @Override
        public void run(CubeVisitProtos.CubeVisitResponse result) {
            CubeVisitProtos.CubeVisitResponse.Stats stats = result.getStats();
            Assert.assertEquals(0L, stats.getAggregatedRowCount());
            Assert.assertEquals(0L, stats.getFilteredRowCount());
            Assert.assertEquals(dateList.size() * userList.size(), stats.getScannedRowCount());

            try {
                byte[] rawData = CompressionUtils
                        .decompress(HBaseZeroCopyByteString.zeroCopyGetBytes(result.getCompressedRows()));
                PartitionResultIterator iterator = new PartitionResultIterator(rawData, gtInfo, setOf(0, 1, 2, 3));
                int nReturn = 0;
                while (iterator.hasNext()) {
                    iterator.next();
                    nReturn++;
                }
                Assert.assertEquals(dateList.size() * userList.size(), nReturn);
            } catch (Exception e) {
                Assert.fail("Fail due to " + e);
            }
        }
    };
    service.visitCube(null, request, done);
}
 
Example 19
Source Project: BigData-In-Practice   Source File: TestRowCountEndPoint.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void getRowCount(RpcController controller,
                        getRowCountRequest request,
                        RpcCallback<getRowCountResponse> done) {
    // 单个region上的计算结果值
    int result = 0;

    // 定义返回response
    getRowCountResponse.Builder responseBuilder = getRowCountResponse.newBuilder();
    // 进行行数统计
    InternalScanner scanner = null;
    try {
        Scan scan = new Scan();
        scanner = this.envi.getRegion().getScanner(scan);
        List<Cell> results = new ArrayList<Cell>();
        boolean hasMore = false;

        do {
            hasMore = scanner.next(results);
            result++;
        } while (hasMore);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (scanner != null) {
            try {
                scanner.close();
            } catch (IOException ignored) {
                // nothing to do
            }
        }
    }

    responseBuilder.setRowCount(result);
    done.run(responseBuilder.build());
    return;

}
 
Example 20
Source Project: tajo   Source File: DummyProtocolAsyncImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void delay(RpcController controller, EchoMessage request,
                  RpcCallback<EchoMessage> done) {
  try {
    Thread.sleep(3000);
  } catch (InterruptedException e) {
    LOG.error(e.getMessage());
  }

  done.run(request);
}
 
Example 21
Source Project: incubator-tajo   Source File: QueryMasterManagerService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void killQuery(RpcController controller, TajoIdProtos.QueryIdProto request,
                      RpcCallback<PrimitiveProtos.BoolProto> done) {
  QueryId queryId = new QueryId(request);
  QueryMasterTask queryMasterTask = queryMaster.getQueryMasterTask(queryId);
  queryMasterTask.getQuery().handle(new QueryEvent(queryId, QueryEventType.KILL));
}
 
Example 22
Source Project: opendsp   Source File: BiddingService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void bidding(RpcController controller, BiddingReq request, RpcCallback<BiddingRsp> done) {
	try {
		done.run(bidding(controller, request));
	} catch (ServiceException ex) {
	}
}
 
Example 23
public QueryUnitAttemptScheduleContext(ContainerId containerId,
                                       String host,
                                       RpcCallback<QueryUnitRequestProto> callback) {
  this.containerId = containerId;
  this.host = host;
  this.callback = callback;
}
 
Example 24
Source Project: gameserver   Source File: MinaRpcPoolChannel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Call the actual RPC logic.
 * @return
 */
private final Callback doCallMethod(MethodDescriptor method, RpcController controller,
		Message request, Message responsePrototype, RpcCallback<Message> done) {
	
	RpcMessage.Builder rpcReqBuilder = RpcMessage.newBuilder();
	rpcReqBuilder.setId(rpcIdCounter.getAndIncrement());
	String serviceName = method.getService().getFullName();
	String methodName = method.getName();
	String className = void.class.getName();
	byte[] content = Constant.EMPTY_BYTES;
	if ( request != null ) {
		className = request.getClass().getName();
		content = request.toByteArray();
	}
	logger.debug("callMethod className: {}, methodName: {}", className, methodName);
	rpcReqBuilder.setClassName(className);
	rpcReqBuilder.setType(Type.REQUEST);
	rpcReqBuilder.setService(serviceName);
	rpcReqBuilder.setMethod(methodName);
	rpcReqBuilder.setPayload(ByteString.copyFrom(content));
	RpcMessage req = rpcReqBuilder.build();
	
	//Save the callback
	Callback callback = new Callback(done, responsePrototype);
	resultMap.put(req.getId(), callback);
	
	//Send this RpcRequest method to server.
	clientPool.sendMessageToServer(req);
	
	return callback;
}
 
Example 25
Source Project: protobuf-socket-rpc   Source File: FakeServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void testMethod(RpcController controller, Request request,
    final RpcCallback<Response> done) {
  Assert.assertEquals(expectedRequest, request);
  if (error != null) {
    controller.setFailed(error);
  }
  if (rex != null) {
    throw rex;
  }
  if (!invokeCallback) {
    return;
  }
  done.run(response);
}
 
Example 26
Source Project: geowave   Source File: VersionEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void version(
    final RpcController controller,
    final VersionRequest request,
    final RpcCallback<VersionResponse> done) {
  done.run(VersionResponse.newBuilder().addAllVersionInfo(VersionUtils.getVersionInfo()).build());
}
 
Example 27
Source Project: incubator-tajo   Source File: DummyProtocolAsyncImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void getError(RpcController controller, EchoMessage request,
                     RpcCallback<EchoMessage> done) {
  LOG.info("noCallback is called");
  getErrorCalled = true;
  controller.setFailed(request.getMessage());
  done.run(request);
}
 
Example 28
Source Project: incubator-tajo   Source File: TajoMasterService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void allocateWorkerResources(
    RpcController controller,
    TajoMasterProtocol.WorkerResourceAllocationRequest request,
    RpcCallback<TajoMasterProtocol.WorkerResourceAllocationResponse> done) {
  context.getResourceManager().allocateWorkerResources(request, done);
}
 
Example 29
Source Project: swellrt   Source File: ClientRpcController.java    License: Apache License 2.0 5 votes vote down vote up
RpcState(ClientRpcChannel creator, boolean isStreamingRpc, RpcCallback<Message> callback,
    Runnable cancelRpc) {
  this.creator = creator;
  this.isStreamingRpc = isStreamingRpc;
  this.callback = callback;
  this.cancelRpc = cancelRpc;
}
 
Example 30
Source Project: swellrt   Source File: WaveClientRpcImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void submit(RpcController controller, ProtocolSubmitRequest request,
    final RpcCallback<ProtocolSubmitResponse> done) {
  WaveletName waveletName = null;
  try {
    waveletName = ModernIdSerialiser.INSTANCE.deserialiseWaveletName(request.getWaveletName());
  } catch (InvalidIdException e) {
    LOG.warning("Invalid id in submit", e);
    controller.setFailed(new ChannelException(ResponseCode.INVALID_ID, null, e, Recoverable.NOT_RECOVERABLE, null, null).serialize());          
    return;
  }
  String channelId;
  if (request.hasChannelId()) {
    channelId = request.getChannelId();
  } else {
    channelId = null;
  }
  ParticipantId loggedInUser = asBoxController(controller).getLoggedInUser();
  frontend.submitRequest(loggedInUser, waveletName, request.getDelta(), channelId,
      new SubmitRequestListener() {
        @Override
        public void onFailure(String error) {
          done.run(ProtocolSubmitResponse.newBuilder()
              .setOperationsApplied(0).setErrorMessage(error).build());
        }

        @Override
        public void onSuccess(int operationsApplied,
            HashedVersion hashedVersionAfterApplication, long applicationTimestamp) {
          done.run(ProtocolSubmitResponse.newBuilder()
              .setOperationsApplied(operationsApplied)
              .setHashedVersionAfterApplication(
                  CoreWaveletOperationSerializer.serialize(hashedVersionAfterApplication))
              .build());
          // TODO(arb): applicationTimestamp??
        }
      });
}