com.google.protobuf.RpcCallback Java Examples

The following examples show how to use com.google.protobuf.RpcCallback. 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 File: TajoWorkerManagerService.java    From incubator-tajo with 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 #2
Source File: RangerAuthorizationCoprocessor.java    From ranger with 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 #3
Source File: MetaDataEndpointImpl.java    From phoenix with 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 #4
Source File: MetaDataEndpointImpl.java    From phoenix with 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 #5
Source File: RangerAuthorizationCoprocessor.java    From ranger with 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 #6
Source File: RangerAuthorizationCoprocessor.java    From ranger with 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 #7
Source File: WaveClientRpcImplTest.java    From swellrt with 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 #8
Source File: TajoMasterService.java    From incubator-tajo with 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 #9
Source File: WaveClientRpcImplTest.java    From swellrt with 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 #10
Source File: ServerRpcControllerImpl.java    From swellrt with 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 #11
Source File: ServerRpcControllerImpl.java    From swellrt with 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 #12
Source File: WaveClientRpcImplTest.java    From swellrt with 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 #13
Source File: RpcForwarder.java    From protobuf-socket-rpc with 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 #14
Source File: TajoWorkerManagerService.java    From tajo with 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 #15
Source File: RpcTestService.java    From gameserver with 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 #16
Source File: WaveClientRpcImplTest.java    From swellrt with 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 #17
Source File: WaveClientRpcImplTest.java    From swellrt with 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 #18
Source File: DummyProtocolAsyncImpl.java    From tajo with 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 #19
Source File: TajoWorkerManagerService.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void stopQuery(RpcController controller, TajoIdProtos.QueryIdProto request,
                    RpcCallback<PrimitiveProtos.BoolProto> done) {

  workerContext.getTaskManager().getDispatcher().getEventHandler().handle(new QueryStopEvent(new QueryId(request)));
  done.run(TajoWorker.TRUE_PROTO);
}
 
Example #20
Source File: ServerCachingEndpointImpl.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public void removeServerCache(RpcController controller, RemoveServerCacheRequest request,
    RpcCallback<RemoveServerCacheResponse> done) {
  ImmutableBytesPtr tenantId = null;
  if (request.hasTenantId()) {
    tenantId = new ImmutableBytesPtr(request.getTenantId().toByteArray());
  }
  TenantCache tenantCache = GlobalCache.getTenantCache(this.env, tenantId);
  tenantCache.removeServerCache(new ImmutableBytesPtr(request.getCacheId().toByteArray()));
  RemoveServerCacheResponse.Builder responseBuilder = RemoveServerCacheResponse.newBuilder();
  responseBuilder.setReturn(true);
  RemoveServerCacheResponse result = responseBuilder.build();
  done.run(result);
}
 
Example #21
Source File: QueryMasterManagerService.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void getExecutionBlockContext(RpcController controller,
                                     ExecutionBlockContextRequest request,
                                     RpcCallback<ExecutionBlockContextResponse> done) {

  QueryMasterTask queryMasterTask = queryMaster.getQueryMasterTask(
      new QueryId(request.getExecutionBlockId().getQueryId()));
  if (queryMasterTask != null) {

    Stage stage = queryMasterTask.getQuery().getStage(new ExecutionBlockId(request.getExecutionBlockId()));

    // first request with starting ExecutionBlock
    PlanProto.ShuffleType shuffleType = stage.getDataChannel().getShuffleType();

    ExecutionBlockContextResponse.Builder ebRequestProto = ExecutionBlockContextResponse.newBuilder();
    ebRequestProto.setExecutionBlockId(request.getExecutionBlockId())
        .setQueryContext(stage.getContext().getQueryContext().getProto())
        .setQueryOutputPath(stage.getContext().getStagingDir().toString())
        .setPlanJson(CoreGsonHelper.toJson(stage.getBlock().getPlan(), LogicalNode.class))
        .setShuffleType(shuffleType);

    //Set assigned worker to stage
    if (!stage.getAssignedWorkerMap().containsKey(request.getWorker().getId())) {
      stage.getAssignedWorkerMap().put(request.getWorker().getId(),
          NetUtils.createSocketAddr(request.getWorker().getHost(), request.getWorker().getPeerRpcPort()));
    }
    done.run(ebRequestProto.build());
  } else {
    controller.setFailed("Can't find query. request: " + request);
  }
}
 
Example #22
Source File: TajoWorkerManagerService.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void allocateTasks(RpcController controller,
                          BatchAllocationRequest request,
                          RpcCallback<BatchAllocationResponse> done) {
  workerContext.getNodeResourceManager().getDispatcher().
      getEventHandler().handle(new NodeResourceAllocateEvent(request, done));
}
 
Example #23
Source File: UserRefreshService.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Call the remote rpc server's refresh method
 * @param refreshMode
 * @param userSessionKey
 */
public void remoteRefresh(int refreshMode, SessionKey userSessionKey) {
	if ( userSessionKey == null ) return;
	
	RefreshReq.Builder reqBuilder = RefreshReq.newBuilder();
	reqBuilder.setUserSessionKey(ByteString.copyFrom(userSessionKey.getRawKey()));
	reqBuilder.setRefreshmode(refreshMode);
	
	String rpcServerId = GameContext.getInstance().getSessionManager().findUserRpcId(userSessionKey);
	MinaRpcPoolChannel channel = GameContext.getInstance().findRpcChannel(rpcServerId);
	
	RpcUserRefresh.UserRefresh.Stub stub = RpcUserRefresh.UserRefresh.newStub(channel);

	final boolean[] result = new boolean[]{true};
	
	stub.refresh(null, reqBuilder.build(), new RpcCallback<BoolResponse>() {

		@Override
		public void run(BoolResponse parameter) {
			try {
				result[0] = parameter.getResult();
			} catch (Throwable e) {
				logger.warn("Failed to call remote rpc method: refresh.", e.getMessage());
				result[0] = false;
			}
		}
	});
	
	logger.debug("#remoteRefresh to rpcServer:{} succeed!", rpcServerId);
}
 
Example #24
Source File: WaveClientRpcImpl.java    From swellrt with 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??
        }
      });
}
 
Example #25
Source File: RpcTestService.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Override
public void test(RpcController controller, RpcTestReq request,
		final RpcCallback<RpcTestResp> done) {
	int sleep = request.getSleep();
	//do nothing.
	RpcTestResp.Builder respBuilder = RpcTestResp.newBuilder();
	respBuilder.setSleep(sleep);
	done.run(respBuilder.build());
}
 
Example #26
Source File: QueryMasterManagerService.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void statusUpdate(RpcController controller, TajoWorkerProtocol.TaskStatusProto request,
                         RpcCallback<PrimitiveProtos.BoolProto> done) {
  try {
    QueryId queryId = new QueryId(request.getId().getQueryUnitId().getExecutionBlockId().getQueryId());
    QueryUnitAttemptId attemptId = new QueryUnitAttemptId(request.getId());
    QueryMasterTask queryMasterTask = queryMaster.getQueryMasterTask(queryId);
    if (queryMasterTask == null) {
      queryMasterTask = queryMaster.getQueryMasterTask(queryId, true);
    }
    SubQuery sq = queryMasterTask.getQuery().getSubQuery(attemptId.getQueryUnitId().getExecutionBlockId());
    QueryUnit task = sq.getQueryUnit(attemptId.getQueryUnitId());
    QueryUnitAttempt attempt = task.getAttempt(attemptId.getId());

    if(LOG.isDebugEnabled()){
      LOG.debug(String.format("Task State: %s, Attempt State: %s", task.getState().name(), attempt.getState().name()));
    }

    if (request.getState() == TajoProtos.TaskAttemptState.TA_KILLED) {
      LOG.warn(attemptId + " Killed");
      attempt.handle(
          new TaskAttemptEvent(new QueryUnitAttemptId(request.getId()), TaskAttemptEventType.TA_LOCAL_KILLED));
    } else {
      queryMasterTask.getEventHandler().handle(
          new TaskAttemptStatusUpdateEvent(new QueryUnitAttemptId(request.getId()), request));
    }
    done.run(TajoWorker.TRUE_PROTO);
  } catch (Exception e) {
    LOG.error(e.getMessage(), e);
    done.run(TajoWorker.FALSE_PROTO);
  }
}
 
Example #27
Source File: TajoMasterService.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void releaseWorkerResource(RpcController controller,
                                       TajoMasterProtocol.WorkerResourceReleaseRequest request,
                                       RpcCallback<PrimitiveProtos.BoolProto> done) {
  List<YarnProtos.ContainerIdProto> containerIds = request.getContainerIdsList();

  for(YarnProtos.ContainerIdProto eachContainer: containerIds) {
    context.getResourceManager().releaseWorkerResource(eachContainer);
  }
  done.run(BOOL_TRUE);
}
 
Example #28
Source File: CubeVisitServiceTest.java    From kylin-on-parquet-v2 with 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 #29
Source File: UserRefreshService.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
  * 1: refresh user data
  * 2: refresh user bag data
  * 4: refresh user relation
  */
@Override
public void refresh(RpcController controller, final RefreshReq request,
		final RpcCallback<BoolResponse> done) {
	service.execute(new Runnable() {
		public void run() {
			int mode = request.getRefreshmode();
			ByteString pbSessionKey = request.getUserSessionKey();
			SessionKey sessionKey = SessionKey.createSessionKey(pbSessionKey.toByteArray());
			User user = GameContext.getInstance().findLocalUserBySessionKey(sessionKey);
			boolean result = false;
			if ( user != null ) {
				if ( (mode & 0x1) == 0x1 ) {
					logger.debug("refresh user {} basic data.", user.getRoleName());
					UserManager.getInstance().queryUser(user.get_id());
					result = true;
				}
				if ( (mode & 0x2) == 0x2 ) {
					logger.debug("refresh user {} bag data.", user.getRoleName());
					UserManager.getInstance().queryUserBag(user);
					result = true;
				}
				if ( (mode & 0x4) == 0x4 ) {
					logger.debug("refresh user {} relation data.", user.getRoleName());
					UserManager.getInstance().queryUserRelation(user);
					result = true;
				}
			} else {
				logger.info("#UserRefreshService: cannot find user in this server for sessionkye {}", sessionKey);
			}
			BoolResponse.Builder respBuilder = BoolResponse.newBuilder();
			respBuilder.setResult(result);
			done.run(respBuilder.build());
		}
	});
}
 
Example #30
Source File: DummyProtocolAsyncImpl.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void sum(RpcController controller, SumRequest request,
                RpcCallback<SumResponse> done) {

  SumResponse response = SumResponse.newBuilder().setResult(
      request.getX1()+request.getX2()+request.getX3()+request.getX4()
  ).build();
  done.run(response);
}