Java Code Examples for com.google.common.annotations.VisibleForTesting

The following examples show how to use com.google.common.annotations.VisibleForTesting. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: grpc-nebula-java   Source File: ProtocolNegotiators.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
HostPort parseAuthority(String authority) {
  URI uri = GrpcUtil.authorityToUri(Preconditions.checkNotNull(authority, "authority"));
  String host;
  int port;
  if (uri.getHost() != null) {
    host = uri.getHost();
    port = uri.getPort();
  } else {
    /*
     * Implementation note: We pick -1 as the port here rather than deriving it from the
     * original socket address.  The SSL engine doens't use this port number when contacting the
     * remote server, but rather it is used for other things like SSL Session caching.  When an
     * invalid authority is provided (like "bad_cert"), picking the original port and passing it
     * in would mean that the port might used under the assumption that it was correct.   By
     * using -1 here, it forces the SSL implementation to treat it as invalid.
     */
    host = authority;
    port = -1;
  }
  return new HostPort(host, port);
}
 
Example 2
Source Project: presto   Source File: SimplifyExpressions.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Expression rewrite(Expression expression, Session session, SymbolAllocator symbolAllocator, Metadata metadata, LiteralEncoder literalEncoder, TypeAnalyzer typeAnalyzer)
{
    requireNonNull(metadata, "metadata is null");
    requireNonNull(typeAnalyzer, "typeAnalyzer is null");
    if (expression instanceof SymbolReference) {
        return expression;
    }
    Map<NodeRef<Expression>, Type> expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression);
    expression = pushDownNegations(metadata, expression, expressionTypes);
    expression = extractCommonPredicates(metadata, expression);
    expressionTypes = typeAnalyzer.getTypes(session, symbolAllocator.getTypes(), expression);
    ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes);
    Object optimized = interpreter.optimize(NoOpSymbolResolver.INSTANCE);
    return literalEncoder.toExpression(optimized, expressionTypes.get(NodeRef.of(expression)));
}
 
Example 3
Source Project: presto   Source File: ElasticsearchClient.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static Optional<String> extractAddress(String address)
{
    Matcher matcher = ADDRESS_PATTERN.matcher(address);

    if (!matcher.matches()) {
        return Optional.empty();
    }

    String cname = matcher.group("cname");
    String ip = matcher.group("ip");
    String port = matcher.group("port");

    if (cname != null) {
        return Optional.of(cname + ":" + port);
    }

    return Optional.of(ip + ":" + port);
}
 
Example 4
Source Project: presto   Source File: RecordingHiveMetastore.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void loadRecording()
        throws IOException
{
    Recording recording = RECORDING_CODEC.fromJson(readAllBytes(recordingPath));

    allDatabases = recording.getAllDatabases();
    allRoles = recording.getAllRoles();
    databaseCache.putAll(toMap(recording.getDatabases()));
    tableCache.putAll(toMap(recording.getTables()));
    supportedColumnStatisticsCache.putAll(toMap(recording.getSupportedColumnStatistics()));
    tableStatisticsCache.putAll(toMap(recording.getTableStatistics()));
    partitionStatisticsCache.putAll(toMap(recording.getPartitionStatistics()));
    allTablesCache.putAll(toMap(recording.getAllTables()));
    tablesWithParameterCache.putAll(toMap(recording.getTablesWithParameter()));
    allViewsCache.putAll(toMap(recording.getAllViews()));
    partitionCache.putAll(toMap(recording.getPartitions()));
    partitionNamesCache.putAll(toMap(recording.getPartitionNames()));
    partitionNamesByPartsCache.putAll(toMap(recording.getPartitionNamesByParts()));
    partitionsByNamesCache.putAll(toMap(recording.getPartitionsByNames()));
    tablePrivilegesCache.putAll(toMap(recording.getTablePrivileges()));
    roleGrantsCache.putAll(toMap(recording.getRoleGrants()));
    grantedPrincipalsCache.putAll(toMap(recording.getGrantedPrincipals()));
}
 
Example 5
/**
 * Picks a load balancer based on given criteria.  In order of preference:
 *
 * <ol>
 *   <li>User provided lb on the channel.  This is a degenerate case and not handled here.</li>
 *   <li>"grpclb" if any gRPC LB balancer addresses are present</li>
 *   <li>The policy picked by the service config</li>
 *   <li>"pick_first" if the service config choice does not specify</li>
 * </ol>
 *
 * @param servers The list of servers reported
 * @param config the service config object
 * @return the new load balancer factory, never null
 */
@VisibleForTesting
static LoadBalancerProvider decideLoadBalancerProvider(
    List<EquivalentAddressGroup> servers, @Nullable Map<String, Object> config)
    throws PolicyNotFoundException {
  // Check for balancer addresses
  boolean haveBalancerAddress = false;
  for (EquivalentAddressGroup s : servers) {
    if (s.getAttributes().get(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY) != null) {
      haveBalancerAddress = true;
      break;
    }
  }

  if (haveBalancerAddress) {
    return getProviderOrThrow("grpclb", "NameResolver has returned balancer addresses");
  }

  String serviceConfigChoiceBalancingPolicy = null;
  if (config != null) {
    serviceConfigChoiceBalancingPolicy =
        ServiceConfigUtil.getLoadBalancingPolicyFromServiceConfig(config);
    if (serviceConfigChoiceBalancingPolicy != null) {
      // Handle ASCII specifically rather than relying on the implicit default locale of the str
      return getProviderOrThrow(
          Ascii.toLowerCase(serviceConfigChoiceBalancingPolicy),
          "service-config specifies load-balancing policy");
    }
  }
  return getProviderOrThrow(DEFAULT_POLICY, "Using default policy");
}
 
Example 6
Source Project: hadoop-ozone   Source File: ReplicationManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process all the containers immediately.
 */
@VisibleForTesting
@SuppressFBWarnings(value="NN_NAKED_NOTIFY",
    justification="Used only for testing")
public synchronized void processContainersNow() {
  notifyAll();
}
 
Example 7
Source Project: kylin-on-parquet-v2   Source File: HFileOutputFormat3.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs inside the task to deserialize column family to compression algorithm
 * map from the configuration.
 *
 * @param conf to read the serialized values from
 * @return a map from column family to the configured compression algorithm
 */
@VisibleForTesting
static Map<byte[], Algorithm> createFamilyCompressionMap(Configuration conf) {
    Map<byte[], String> stringMap = createFamilyConfValueMap(conf, COMPRESSION_FAMILIES_CONF_KEY);
    Map<byte[], Algorithm> compressionMap = new TreeMap<byte[], Algorithm>(Bytes.BYTES_COMPARATOR);
    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
        Algorithm algorithm = AbstractHFileWriter.compressionByName(e.getValue());
        compressionMap.put(e.getKey(), algorithm);
    }
    return compressionMap;
}
 
Example 8
Source Project: cloud-spanner-r2dbc   Source File: GrpcClient.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
GrpcClient(SpannerStub spanner, DatabaseAdminStub databaseAdmin, OperationsStub operations) {
  this.spanner = spanner;
  this.databaseAdmin = databaseAdmin;
  this.operations = operations;
  this.channel = null;
}
 
Example 9
Source Project: plugins   Source File: AttackStylesPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
@VisibleForTesting
void onConfigChanged(ConfigChanged event)
{
	if (event.getGroup().equals("attackIndicator"))
	{
		boolean enabled = Boolean.TRUE.toString().equals(event.getNewValue());
		switch (event.getKey())
		{
			case "warnForDefensive":
				updateWarnedSkills(enabled, Skill.DEFENCE);
				break;
			case "warnForAttack":
				updateWarnedSkills(enabled, Skill.ATTACK);
				break;
			case "warnForStrength":
				updateWarnedSkills(enabled, Skill.STRENGTH);
				break;
			case "warnForRanged":
				updateWarnedSkills(enabled, Skill.RANGED);
				break;
			case "warnForMagic":
				updateWarnedSkills(enabled, Skill.MAGIC);
				break;
			case "removeWarnedStyles":
				hideWarnedStyles(enabled);
				break;
		}
		processWidgets();
	}
}
 
Example 10
Source Project: kylin-on-parquet-v2   Source File: HFileOutputFormat3.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs inside the task to deserialize column family to bloom filter type
 * map from the configuration.
 *
 * @param conf to read the serialized values from
 * @return a map from column family to the the configured bloom filter type
 */
@VisibleForTesting
static Map<byte[], BloomType> createFamilyBloomTypeMap(Configuration conf) {
    Map<byte[], String> stringMap = createFamilyConfValueMap(conf, BLOOM_TYPE_FAMILIES_CONF_KEY);
    Map<byte[], BloomType> bloomTypeMap = new TreeMap<byte[], BloomType>(Bytes.BYTES_COMPARATOR);
    for (Map.Entry<byte[], String> e : stringMap.entrySet()) {
        BloomType bloomType = BloomType.valueOf(e.getValue());
        bloomTypeMap.put(e.getKey(), bloomType);
    }
    return bloomTypeMap;
}
 
Example 11
Source Project: presto   Source File: TableFinishOperator.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
TableFinishInfo getInfo()
{
    return new TableFinishInfo(
            outputMetadata,
            new Duration(statisticsTiming.getWallNanos(), NANOSECONDS).convertToMostSuccinctTimeUnit(),
            new Duration(statisticsTiming.getCpuNanos(), NANOSECONDS).convertToMostSuccinctTimeUnit());
}
 
Example 12
Source Project: presto   Source File: Driver.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Driver createDriver(DriverContext driverContext, Operator firstOperator, Operator... otherOperators)
{
    requireNonNull(driverContext, "driverContext is null");
    requireNonNull(firstOperator, "firstOperator is null");
    requireNonNull(otherOperators, "otherOperators is null");
    ImmutableList<Operator> operators = ImmutableList.<Operator>builder()
            .add(firstOperator)
            .add(otherOperators)
            .build();
    return createDriver(driverContext, operators);
}
 
Example 13
Source Project: hadoop-ozone   Source File: ContainerStateMachine.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public void buildMissingContainerSet(File snapshotFile) throws IOException {
  // initialize the dispatcher with snapshot so that it build the missing
  // container list
  try (FileInputStream fin = new FileInputStream(snapshotFile)) {
    ContainerProtos.Container2BCSIDMapProto proto =
            ContainerProtos.Container2BCSIDMapProto
                    .parseFrom(fin);
    // read the created containers list from the snapshot file and add it to
    // the container2BCSIDMap here.
    // container2BCSIDMap will further grow as and when containers get created
    container2BCSIDMap.putAll(proto.getContainer2BCSIDMap());
    dispatcher.buildMissingContainerSetAndValidate(container2BCSIDMap);
  }
}
 
Example 14
Source Project: Bats   Source File: StreamingContainerManager.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected Collection<Pair<Long, Map<String, Object>>> getLogicalMetrics(String operatorName)
{
  if (logicalMetrics.get(operatorName) != null) {
    return Collections.unmodifiableCollection(logicalMetrics.get(operatorName));
  }
  return null;
}
 
Example 15
Source Project: presto   Source File: TestingWarningCollector.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static PrestoWarning createTestWarning(int code)
{
    // format string below is a hack to construct a vendor specific SQLState value
    // 01 is the class of warning code and 5 is the first allowed vendor defined prefix character
    // See the SQL Standard ISO_IEC_9075-2E_2016 24.1: SQLState for more information
    return new PrestoWarning(new WarningCode(code, format("015%02d", code % 100)), "Test warning " + code);
}
 
Example 16
Source Project: presto   Source File: AccessControlManager.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected void setSystemAccessControl(String name, Map<String, String> properties)
{
    requireNonNull(name, "name is null");
    requireNonNull(properties, "properties is null");

    checkState(systemAccessControlLoading.compareAndSet(false, true), "System access control already initialized");

    SystemAccessControlFactory systemAccessControlFactory = systemAccessControlFactories.get(name);
    checkState(systemAccessControlFactory != null, "Access control '%s' is not registered", name);

    SystemAccessControl systemAccessControl = systemAccessControlFactory.create(ImmutableMap.copyOf(properties));
    this.systemAccessControls.set(ImmutableList.of(systemAccessControl));
}
 
Example 17
Source Project: presto   Source File: FileSingleStreamSpillerFactory.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public FileSingleStreamSpillerFactory(
        ListeningExecutorService executor,
        BlockEncodingSerde blockEncodingSerde,
        SpillerStats spillerStats,
        List<Path> spillPaths,
        double maxUsedSpaceThreshold,
        boolean spillCompressionEnabled,
        boolean spillEncryptionEnabled)
{
    this.serdeFactory = new PagesSerdeFactory(blockEncodingSerde, spillCompressionEnabled);
    this.executor = requireNonNull(executor, "executor is null");
    this.spillerStats = requireNonNull(spillerStats, "spillerStats cannot be null");
    requireNonNull(spillPaths, "spillPaths is null");
    this.spillPaths = ImmutableList.copyOf(spillPaths);
    spillPaths.forEach(path -> {
        try {
            createDirectories(path);
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("could not create spill path %s; adjust %s config property or filesystem permissions", path, SPILLER_SPILL_PATH), e);
        }
        if (!isAccessible(path)) {
            throw new IllegalArgumentException(format("spill path %s is not accessible, it must be +rwx; adjust %s config property or filesystem permissions", path, SPILLER_SPILL_PATH));
        }
    });
    this.maxUsedSpaceThreshold = maxUsedSpaceThreshold;
    this.spillEncryptionEnabled = spillEncryptionEnabled;
    this.roundRobinIndex = 0;

    this.spillPathHealthCache = CacheBuilder.newBuilder()
            .expireAfterWrite(SPILL_PATH_HEALTH_EXPIRY_INTERVAL)
            .build(CacheLoader.from(path -> isAccessible(path) && isSeeminglyHealthy(path)));
}
 
Example 18
Source Project: hadoop-ozone   Source File: OzoneManager.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public LifeCycle.State getOmRatisServerState() {
  if (omRatisServer == null) {
    return null;
  } else {
    return omRatisServer.getServerState();
  }
}
 
Example 19
Source Project: java-sdk   Source File: TransactionRequestAssembler.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
NewOrderMessage createNewOrderMessage(
        com.binance.dex.api.client.domain.broadcast.NewOrder newOrder) {
    return NewOrderMessage.newBuilder()
            .setId(generateOrderId())
            .setOrderType(newOrder.getOrderType())
            .setPrice(newOrder.getPrice())
            .setQuantity(newOrder.getQuantity())
            .setSender(wallet.getAddress())
            .setSide(newOrder.getSide())
            .setSymbol(newOrder.getSymbol())
            .setTimeInForce(newOrder.getTimeInForce())
            .build();
}
 
Example 20
Source Project: presto   Source File: PasswordStore.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public PasswordStore(List<String> lines, int cacheMaxSize)
{
    credentials = loadPasswordFile(lines);
    cache = CacheBuilder.newBuilder()
            .maximumSize(cacheMaxSize)
            .build(CacheLoader.from(this::matches));
}
 
Example 21
/**
 * Get Delta updates from OM through RPC call and apply to local OM DB as
 * well as accumulate in a buffer.
 * @param fromSequenceNumber from sequence number to request from.
 * @param omdbUpdatesHandler OM DB updates handler to buffer updates.
 * @throws IOException when OM RPC request fails.
 * @throws RocksDBException when writing to RocksDB fails.
 */
@VisibleForTesting
void getAndApplyDeltaUpdatesFromOM(
    long fromSequenceNumber, OMDBUpdatesHandler omdbUpdatesHandler)
    throws IOException, RocksDBException {
  DBUpdatesRequest dbUpdatesRequest = DBUpdatesRequest.newBuilder()
      .setSequenceNumber(fromSequenceNumber).build();
  DBUpdates dbUpdates = ozoneManagerClient.getDBUpdates(dbUpdatesRequest);
  if (null != dbUpdates) {
    RDBStore rocksDBStore = (RDBStore) omMetadataManager.getStore();
    RocksDB rocksDB = rocksDBStore.getDb();
    int numUpdates = dbUpdates.getData().size();
    LOG.info("Number of updates received from OM : {}", numUpdates);
    if (numUpdates > 0) {
      metrics.incrNumUpdatesInDeltaTotal(numUpdates);
    }
    for (byte[] data : dbUpdates.getData()) {
      try (WriteBatch writeBatch = new WriteBatch(data)) {
        writeBatch.iterate(omdbUpdatesHandler);
        try (RDBBatchOperation rdbBatchOperation =
                 new RDBBatchOperation(writeBatch)) {
          try (WriteOptions wOpts = new WriteOptions()) {
            rdbBatchOperation.commit(rocksDB, wOpts);
          }
        }
      }
    }
  }
}
 
Example 22
Source Project: presto   Source File: HashAggregationOperator.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HashAggregationOperatorFactory(
        int operatorId,
        PlanNodeId planNodeId,
        List<? extends Type> groupByTypes,
        List<Integer> groupByChannels,
        List<Integer> globalAggregationGroupIds,
        Step step,
        boolean produceDefaultOutput,
        List<AccumulatorFactory> accumulatorFactories,
        Optional<Integer> hashChannel,
        Optional<Integer> groupIdChannel,
        int expectedGroups,
        Optional<DataSize> maxPartialMemory,
        boolean spillEnabled,
        DataSize memoryLimitForMerge,
        DataSize memoryLimitForMergeWithMemory,
        SpillerFactory spillerFactory,
        JoinCompiler joinCompiler,
        boolean useSystemMemory)
{
    this.operatorId = operatorId;
    this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
    this.hashChannel = requireNonNull(hashChannel, "hashChannel is null");
    this.groupIdChannel = requireNonNull(groupIdChannel, "groupIdChannel is null");
    this.groupByTypes = ImmutableList.copyOf(groupByTypes);
    this.groupByChannels = ImmutableList.copyOf(groupByChannels);
    this.globalAggregationGroupIds = ImmutableList.copyOf(globalAggregationGroupIds);
    this.step = step;
    this.produceDefaultOutput = produceDefaultOutput;
    this.accumulatorFactories = ImmutableList.copyOf(accumulatorFactories);
    this.expectedGroups = expectedGroups;
    this.maxPartialMemory = requireNonNull(maxPartialMemory, "maxPartialMemory is null");
    this.spillEnabled = spillEnabled;
    this.memoryLimitForMerge = requireNonNull(memoryLimitForMerge, "memoryLimitForMerge is null");
    this.memoryLimitForMergeWithMemory = requireNonNull(memoryLimitForMergeWithMemory, "memoryLimitForMergeWithMemory is null");
    this.spillerFactory = requireNonNull(spillerFactory, "spillerFactory is null");
    this.joinCompiler = requireNonNull(joinCompiler, "joinCompiler is null");
    this.useSystemMemory = useSystemMemory;
}
 
Example 23
Source Project: hadoop-ozone   Source File: KeyOutputStream.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A constructor for testing purpose only.
 */
@VisibleForTesting
public KeyOutputStream() {
  closed = false;
  this.retryPolicyMap = HddsClientUtils.getExceptionList()
      .stream()
      .collect(Collectors.toMap(Function.identity(),
          e -> RetryPolicies.TRY_ONCE_THEN_FAIL));
  retryCount = 0;
  offset = 0;
  blockOutputStreamEntryPool = new BlockOutputStreamEntryPool();
}
 
Example 24
Source Project: singer   Source File: ConfigFileServerSet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Internal constructor. This is provided for use by unit test.
 *
 * @param configFileWatcher ConfigFileWatcher instance to use.
 * @param serverSetFilePath Path the server set file on local disk. This is expected to contain a list of host:port
 * pairs, one per line. An external daemon will be responsible for keeping this in sync with the actual server set in
 * ZooKeeper.
 */
@VisibleForTesting
ConfigFileServerSet(ConfigFileWatcher configFileWatcher, String serverSetFilePath) {
  this.serverSetFilePath = MorePreconditions.checkNotBlank(serverSetFilePath);
  this.configFileWatcher = Preconditions.checkNotNull(configFileWatcher);

  File file = new File(serverSetFilePath);
  if (!file.exists()) {
    String message = String.format("Server set file: %s doesn't exist", serverSetFilePath);
    throw new IllegalArgumentException(message);
  }
}
 
Example 25
Source Project: grpc-nebula-java   Source File: NettyClientTransport.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
KeepAliveManager keepAliveManager() {
  return keepAliveManager;
}
 
Example 26
Source Project: hadoop-ozone   Source File: BackgroundService.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public void triggerBackgroundTaskForTesting() {
  service.run();
}
 
Example 27
Source Project: presto   Source File: DynamicFilterService.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
synchronized void registerQuery(QueryId queryId, Supplier<List<StageDynamicFilters>> stageDynamicFiltersSupplier, Set<SourceDescriptor> dynamicFilters)
{
    queries.putIfAbsent(queryId, stageDynamicFiltersSupplier);
    queryDynamicFilters.put(queryId, dynamicFilters);
}
 
Example 28
Source Project: presto   Source File: PartitionedOutputBuffer.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
OutputBufferMemoryManager getMemoryManager()
{
    return memoryManager;
}
 
Example 29
Source Project: plugins   Source File: ScreenshotPlugin.java    License: GNU General Public License v3.0 4 votes vote down vote up
@VisibleForTesting
int getClueNumber()
{
	return clueNumber;
}
 
Example 30
Source Project: presto   Source File: ElasticsearchPlugin.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
ElasticsearchPlugin(ElasticsearchConnectorFactory factory)
{
    connectorFactory = requireNonNull(factory, "factory is null");
}