类com.google.common.net.HostAndPort源码实例Demo

下面列出了怎么用com.google.common.net.HostAndPort的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: connect-utils   文件: ValidHostAndPort.java
void validate(final String setting, final String input) {
  HostAndPort hostAndPort = HostAndPort.fromString(input);
  if (this.requireBracketsForIPv6) {
    hostAndPort = hostAndPort.requireBracketsForIPv6();
  }
  if (null != this.defaultPort) {
    hostAndPort.withDefaultPort(this.defaultPort);
  }

  if (Strings.isNullOrEmpty(hostAndPort.getHost())) {
    throw new ConfigException(String.format("'%s'(%s) host cannot be blank or null.", setting, input));
  }

  if (this.portRequired && !hostAndPort.hasPort()) {
    throw new ConfigException(String.format("'%s'(%s) must specify a port.", setting, input));
  }
}
 
@Test
public <T> void testDoesNotDoRegexMatchingWhenSensorsSpecified() throws Exception {
    AttributeSensor<String> sensor = Sensors.newStringSensor("mysensor");
    AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port");

    entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1");
    entity.sensors().set(intPort, 1234);
    entity.sensors().set(sensor, "127.0.0.1:1234");
    portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234);
    entity.addLocations(ImmutableList.of(machine));
    
    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(sensor)));

    assertAttributeEqualsEventually("mysensor.mapped.public", "mypublichost:5678");
    assertAttributeEqualsContinually("int.endpoint.mapped.public", null, VERY_SHORT_WAIT);
}
 
源代码3 项目: datacollector   文件: KafkaLowLevelConsumer08.java
public KafkaLowLevelConsumer08(
    String topic,
    int partition,
    HostAndPort broker,
    int minFetchSize,
    int maxFetchSize,
    int maxWaitTime,
    String clientName
) {
  this.topic = topic;
  this.partition = partition;
  this.broker = broker;
  this.maxFetchSize = maxFetchSize;
  this.minFetchSize = minFetchSize;
  this.maxWaitTime = maxWaitTime;
  this.clientName = clientName;
  this.replicaBrokers = new ArrayList<>();
}
 
源代码4 项目: drift   文件: LegacyApacheThriftTesterUtil.java
private static TSocket createClientSocket(boolean secure, HostAndPort address)
        throws TTransportException
{
    if (!secure) {
        return new TSocket(address.getHost(), address.getPort());
    }

    try {
        SSLContext serverSslContext = ClientTestUtils.getClientSslContext();
        SSLSocket clientSocket = (SSLSocket) serverSslContext.getSocketFactory().createSocket(address.getHost(), address.getPort());
        //            clientSocket.setSoTimeout(timeout);
        return new TSocket(clientSocket);
    }
    catch (Exception e) {
        throw new TTransportException("Error initializing secure socket", e);
    }
}
 
源代码5 项目: drift   文件: TestClientsWithDriftNettyServer.java
private static void testDriftServer(DriftService service, Consumer<HostAndPort> task)
{
    DriftNettyServerConfig config = new DriftNettyServerConfig()
            .setSslEnabled(true)
            .setTrustCertificate(ClientTestUtils.getCertificateChainFile())
            .setKey(ClientTestUtils.getPrivateKeyFile());
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    DriftServer driftServer = new DriftServer(
            new DriftNettyServerTransportFactory(config, testingAllocator),
            CODEC_MANAGER,
            new NullMethodInvocationStatsFactory(),
            ImmutableSet.of(service),
            ImmutableSet.of());
    try {
        driftServer.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) driftServer.getServerTransport()).getPort());

        task.accept(address);
    }
    finally {
        driftServer.shutdown();
        testingAllocator.close();
    }
}
 
源代码6 项目: emodb   文件: CompactionControlMonitorManager.java
@Inject
CompactionControlMonitorManager(LifeCycleRegistry lifeCycle,
                                @LocalCompactionControl CompactionControlSource compactionControlSource,
                                @GlobalFullConsistencyZooKeeper CuratorFramework curator,
                                @SelfHostAndPort HostAndPort self,
                                Clock clock,
                                LeaderServiceTask dropwizardTask,
                                final MetricRegistry metricRegistry) {
    LeaderService leaderService = new LeaderService(
            curator,
            "/leader/compaction-control-monitor",
            self.toString(),
            "Leader-CompactionControlMonitor",
            30, TimeUnit.MINUTES,
            () -> new CompactionControlMonitor(compactionControlSource, clock, metricRegistry)
    );

    ServiceFailureListener.listenTo(leaderService, metricRegistry);
    dropwizardTask.register("stash-runtime-monitor", leaderService);
    lifeCycle.manage(new ManagedGuavaService(leaderService));
}
 
protected Maybe<String> transformHostAndPort(Entity source, MachineLocation machine, String sensorVal) {
    HostAndPort hostAndPort = HostAndPort.fromString(sensorVal);
    if (hostAndPort.hasPort()) {
        int port = hostAndPort.getPort();
        Optional<HostAndPort> mappedEndpoint = getMappedEndpoint(source, machine, port);
        if (!mappedEndpoint.isPresent()) {
            LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}", new Object[] {source, sensorVal, machine});
            return Maybe.absent();
        }
        if (!mappedEndpoint.get().hasPort()) {
            LOG.debug("network-facing enricher not transforming {} host-and-port {}, because no port in target {} for {}", new Object[] {source, sensorVal, mappedEndpoint, machine});
            return Maybe.absent();
        }
        return Maybe.of(mappedEndpoint.get().toString());
    } else {
        LOG.debug("network-facing enricher not transforming {} host-and-port {} because defines no port", source, hostAndPort);
        return Maybe.absent();
    }
}
 
源代码8 项目: mongowp   文件: GuavaCachedMongoClientFactory.java
@Override
public MongoClient createClient(HostAndPort address) throws
    UnreachableMongoServerException {
  try {
    return cachedClients.get(address, () -> {
      return new CachedMongoClient(factory.createClient(address));
    });
  } catch (ExecutionException ex) {
    Throwable cause = ex.getCause();
    if (cause instanceof UnreachableMongoServerException) {
      throw (UnreachableMongoServerException) cause;
    }
    if (cause instanceof RuntimeException) {
      throw (RuntimeException) cause;
    }
    throw new RuntimeException(ex);
  }
}
 
@Test
public void testAssociationPreservedOnRebind() throws Exception {
    String publicIpId = "5.6.7.8";
    String publicAddress = "5.6.7.8";

    TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntity.class));
    PortForwardManager origPortForwardManager = origEntity.getConfig(MyEntity.PORT_FORWARD_MANAGER);

    // We first wait for persisted, to ensure that it is the PortForwardManager.onChanged that is causing persistence.
    RebindTestUtils.waitForPersisted(origApp);
    origPortForwardManager.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40080), origSimulatedMachine, 80);
 
    newApp = rebind();
    
    // After rebind, confirm that lookups still work
    TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class));
    Location newSimulatedMachine = newApp.getManagementContext().getLocationManager().getLocation(origSimulatedMachine.getId());
    PortForwardManager newPortForwardManager = newEntity.getConfig(MyEntity.PORT_FORWARD_MANAGER);
    
    assertEquals(newPortForwardManager.lookup(newSimulatedMachine, 80), HostAndPort.fromParts(publicAddress, 40080));
    assertEquals(newPortForwardManager.lookup(publicIpId, 80), HostAndPort.fromParts(publicAddress, 40080));
}
 
源代码10 项目: brooklyn-server   文件: PortForwardManagerTest.java
@Test
public void testForgetPortMappingsOfMachine() throws Exception {
    String publicIpId = "myipid";
    String publicIpId2 = "myipid2";
    String publicAddress = "5.6.7.8";

    pfm.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40080), machine1, 80);
    pfm.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40081), machine1, 81);
    pfm.associate(publicIpId2, HostAndPort.fromParts(publicAddress, 40082), machine2, 80);
    pfm.forgetPortMappings(machine1);
    
    assertNull(pfm.lookup(machine1, 80));
    assertNull(pfm.lookup(machine1, 81));
    assertNull(pfm.lookup(publicIpId, 80));
    assertEquals(pfm.lookup(machine2, 80), HostAndPort.fromParts(publicAddress, 40082));
}
 
@Override
public String getConnectionString() {
    StringBuilder connectStringBuilder = new StringBuilder();
    SortedSet<String> addresses = new TreeSet<>();

    for (InetSocketAddress hostAndPort : _connectStringParser.getServerAddresses()) {
        try {
            for (InetAddress address : _resolver.lookupAllHostAddr(hostAndPort.getHostName())) {
                addresses.add(HostAndPort.fromParts(address.getHostAddress(), hostAndPort.getPort()).toString());
            }
        } catch (UnknownHostException e) {
            // Leave unresolvable host in connect string as-is.
            addresses.add(hostAndPort.toString());
        }
    }

    Joiner.on(',').appendTo(connectStringBuilder, addresses);

    if (_connectStringParser.getChrootPath() != null) {
        connectStringBuilder.append(_connectStringParser.getChrootPath());
    }

    return connectStringBuilder.toString();
}
 
源代码12 项目: AndroidHttpCapture   文件: HttpUtil.java
/**
 * Retrieves the host and, optionally, the port from the specified request's Host header.
 *
 * @param httpRequest HTTP request
 * @param includePort when true, include the port
 * @return the host and, optionally, the port specified in the request's Host header
 */
private static String parseHostHeader(HttpRequest httpRequest, boolean includePort) {
    // this header parsing logic is adapted from ClientToProxyConnection#identifyHostAndPort.
    List<String> hosts = httpRequest.headers().getAll(HttpHeaders.Names.HOST);
    if (!hosts.isEmpty()) {
        String hostAndPort = hosts.get(0);

        if (includePort) {
            return hostAndPort;
        } else {
            HostAndPort parsedHostAndPort = HostAndPort.fromString(hostAndPort);
            return parsedHostAndPort.getHost();
        }
    } else {
        return null;
    }
}
 
@Override
public GraphiteSender get() {
    HostAndPort hostAndPort = configuration.getAddress();
    String host = hostAndPort.getHost();
    int port = hostAndPort.getPortOrDefault(2003);

    switch (configuration.getProtocol()) {
        case PICKLE:
            return new PickledGraphite(
                    host,
                    port,
                    SocketFactory.getDefault(),
                    configuration.getCharset(),
                    configuration.getPickleBatchSize());
        case TCP:
            return new Graphite(host, port, SocketFactory.getDefault(), configuration.getCharset());
        case UDP:
            return new GraphiteUDP(host, port);
        default:
            throw new IllegalArgumentException("Unknown Graphite protocol \"" + configuration.getProtocol() + "\"");
    }
}
 
源代码14 项目: brooklyn-server   文件: JcloudsLocation.java
protected ConnectivityResolverOptions.Builder getConnectivityOptionsBuilder(ConfigBag setup, boolean isWindows) {
    boolean waitForSshable = !"false".equalsIgnoreCase(setup.get(JcloudsLocationConfig.WAIT_FOR_SSHABLE));
    boolean waitForWinRmable = !"false".equalsIgnoreCase(setup.get(JcloudsLocationConfig.WAIT_FOR_WINRM_AVAILABLE));
    boolean waitForConnectable = isWindows ? waitForWinRmable : waitForSshable;

    boolean usePortForwarding = setup.get(JcloudsLocationConfig.USE_PORT_FORWARDING);
    boolean skipJcloudsSshing = usePortForwarding ||
            Boolean.FALSE.equals(setup.get(JcloudsLocationConfig.USE_JCLOUDS_SSH_INIT));

    ConnectivityResolverOptions.Builder builder = ConnectivityResolverOptions.builder()
            .waitForConnectable(waitForConnectable)
            .usePortForwarding(usePortForwarding)
            .skipJcloudsSshing(skipJcloudsSshing);

    String pollForFirstReachable = setup.get(JcloudsLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS);
    boolean pollEnabled = !"false".equalsIgnoreCase(pollForFirstReachable);

    if (pollEnabled) {
        Predicate<? super HostAndPort> reachableAddressesPredicate = getReachableAddressesPredicate(setup);
        Duration pollTimeout = "true".equals(pollForFirstReachable)
                               ? Duration.FIVE_MINUTES
                               : Duration.of(pollForFirstReachable);
        builder.pollForReachableAddresses(reachableAddressesPredicate, pollTimeout, true);
    }
    return builder;
}
 
源代码15 项目: soabase   文件: ZooKeeperDiscovery.java
@Override
public void setForcedState(String serviceName, String instanceId, ForcedState forcedState)
{
    try
    {
        ServiceInstance<Payload> foundInstance = discovery.queryForInstance(serviceName, instanceId);
        if ( foundInstance != null )
        {
            DiscoveryInstance soaInstance = toSoaInstance(foundInstance);
            Payload oldPayload = foundInstance.getPayload();
            Payload newPayload = new Payload(null, oldPayload.getAdminPort(), oldPayload.getMetaData(), forcedState, oldPayload.getHealthyState());
            ServiceInstance<Payload> updatedInstance = buildInstance(serviceName, HostAndPort.fromParts(soaInstance.getHost(), soaInstance.getPort()), newPayload, instanceId, soaInstance.getHost());
            discovery.updateService(updatedInstance);
        } // TODO else?
    }
    catch ( Exception e )
    {
        log.error("Could not update service: " + (serviceName + ":" + instanceId), e);
        throw new RuntimeException(e);
    }
}
 
源代码16 项目: Singularity   文件: SingularityAbort.java
@Inject
public SingularityAbort(
  SingularitySmtpSender smtpSender,
  ServerProvider serverProvider,
  SingularityConfiguration configuration,
  SingularityExceptionNotifier exceptionNotifier,
  Injector injector,
  @Named(SingularityMainModule.HTTP_HOST_AND_PORT) HostAndPort hostAndPort
) {
  this.maybeSmtpConfiguration = configuration.getSmtpConfigurationOptional();
  this.serverProvider = serverProvider;
  this.smtpSender = smtpSender;
  this.exceptionNotifier = exceptionNotifier;
  this.injector = injector;
  this.hostAndPort = hostAndPort;
}
 
源代码17 项目: dremio-oss   文件: ParquetGroupScanUtils.java
public static EndpointByteMap buildEndpointByteMap(
  Set<HostAndPort> activeHostMap, Set<HostAndPort> activeHostPortMap,
  Map<com.google.common.net.HostAndPort, Float> affinities, long totalLength) {

  EndpointByteMap endpointByteMap = new EndpointByteMapImpl();
  for (HostAndPort host : affinities.keySet()) {
    HostAndPort endpoint = null;
    if (!host.hasPort()) {
      if (activeHostMap.contains(host)) {
        endpoint = host;
      }
    } else {
      // multi executor deployment and affinity provider is sensitive to the port
      // picking the map late as it allows a source that contains files in HDFS and S3
      if (activeHostPortMap.contains(host)) {
        endpoint = host;
      }
    }

    if (endpoint != null) {
      endpointByteMap.add(endpoint, (long) (affinities.get(host) * totalLength));
    }
  }
  return endpointByteMap;
}
 
源代码18 项目: drift   文件: TestDriftNettyServerTransport.java
private static int testServerMethodInvoker(ServerMethodInvoker methodInvoker, boolean assumeClientsSupportOutOfOrderResponses, List<ToIntFunction<HostAndPort>> clients)
{
    DriftNettyServerConfig config = new DriftNettyServerConfig()
            .setAssumeClientsSupportOutOfOrderResponses(assumeClientsSupportOutOfOrderResponses);
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    ServerTransport serverTransport = new DriftNettyServerTransportFactory(config, testingAllocator).createServerTransport(methodInvoker);
    try {
        serverTransport.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort());

        int sum = 0;
        for (ToIntFunction<HostAndPort> client : clients) {
            sum += client.applyAsInt(address);
        }
        return sum;
    }
    finally {
        serverTransport.shutdown();
        testingAllocator.close();
    }
}
 
源代码19 项目: g4proxy   文件: ProxyToServerConnection.java
/**
 * Build an {@link InetSocketAddress} for the given hostAndPort.
 *
 * @param hostAndPort String representation of the host and port
 * @param proxyServer the current {@link DefaultHttpProxyServer}
 * @return a resolved InetSocketAddress for the specified hostAndPort
 * @throws UnknownHostException if hostAndPort could not be resolved, or if the input string could not be parsed into
 *          a host and port.
 */
public static InetSocketAddress addressFor(String hostAndPort, DefaultHttpProxyServer proxyServer)
        throws UnknownHostException {
    HostAndPort parsedHostAndPort;
    try {
        parsedHostAndPort = HostAndPort.fromString(hostAndPort);
    } catch (IllegalArgumentException e) {
        // we couldn't understand the hostAndPort string, so there is no way we can resolve it.
        throw new UnknownHostException(hostAndPort);
    }

    String host = parsedHostAndPort.getHost();
    int port = parsedHostAndPort.getPortOrDefault(80);

    return proxyServer.getServerResolver().resolve(host, port);
}
 
源代码20 项目: data-highway   文件: MetricsConfiguration.java
@Autowired
public MetricsConfiguration(
    @Value("${metrics.graphiteEndpoint:disabled}") String graphiteEndpoint,
    @Value("${road.name}") String roadName) {
  if ("disabled".equalsIgnoreCase(graphiteEndpoint)) {
    log.info("Graphite metrics reporting is disabled");
    this.graphiteEndpoint = null;
  } else {
    log.info("Graphite reporting is configured for {}", graphiteEndpoint);
    HostAndPort hostAndPort = HostAndPort.fromString(graphiteEndpoint);
    this.graphiteEndpoint = new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());
  }
  this.roadName = roadName;
}
 
源代码21 项目: hadoop-ozone   文件: HddsUtils.java
/**
 * Gets the port if there is one, returns empty {@code OptionalInt} otherwise.
 * @param value  String in host:port format.
 * @return Port
 */
public static OptionalInt getHostPort(String value) {
  if ((value == null) || value.isEmpty()) {
    return OptionalInt.empty();
  }
  int port = HostAndPort.fromString(value).getPortOrDefault(NO_PORT);
  if (port == NO_PORT) {
    return OptionalInt.empty();
  } else {
    return OptionalInt.of(port);
  }
}
 
源代码22 项目: rapid   文件: ClusterTest.java
/**
 * Verify public API that uses HostAndPort
 */
@Test(timeout = 30000)
public void hostAndPortBuilderTests() throws IOException, InterruptedException, ExecutionException {
    final HostAndPort addr1 = HostAndPort.fromParts("127.0.0.1", 1255);
    final HostAndPort addr2 = HostAndPort.fromParts("127.0.0.1", 1256);
    final Cluster seed = new Cluster.Builder(addr1).start();
    final Cluster joiner = new Cluster.Builder(addr2).join(addr1);
    assertEquals(2, seed.getMembershipSize());
    assertEquals(2, joiner.getMembershipSize());
    joiner.shutdown();
    seed.shutdown();
}
 
@Override
public JsonSerializer<?> findSerializer(SerializationConfig config, JavaType type,
        BeanDescription beanDesc, JsonFormat.Value formatOverrides)
{
    Class<?> raw = type.getRawClass();
    if (RangeSet.class.isAssignableFrom(raw)) {
        return new RangeSetSerializer();
    }
    if (Range.class.isAssignableFrom(raw)) {
        return new RangeSerializer(_findDeclared(type, Range.class));
    }
    if (Table.class.isAssignableFrom(raw)) {
        return new TableSerializer(_findDeclared(type, Table.class));
    }
    if (HostAndPort.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (InternetDomainName.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    // not sure how useful, but why not?
    if (CacheBuilderSpec.class.isAssignableFrom(raw) || CacheBuilder.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (HashCode.class.isAssignableFrom(raw)) {
        return ToStringSerializer.instance;
    }
    if (FluentIterable.class.isAssignableFrom(raw)) {
        JavaType iterableType = _findDeclared(type, Iterable.class);
        return new StdDelegatingSerializer(FluentConverter.instance, iterableType, null, null);
    }
    return null;
}
 
源代码24 项目: armeria   文件: HttpHeaderUtil.java
@Nullable
private static InetSocketAddress createInetSocketAddress(String address) throws UnknownHostException {
    final char firstChar = address.charAt(0);
    if (firstChar == '_' ||
        (firstChar == 'u' && "unknown".equals(address))) {
        // To early return when the address is not an IP address.
        // - an obfuscated identifier which must start with '_'
        //   - https://tools.ietf.org/html/rfc7239#section-6.3
        // - the "unknown" identifier
        return null;
    }

    // Remote quotes. e.g. "[2001:db8:cafe::17]:4711" => [2001:db8:cafe::17]:4711
    final String addr = firstChar == '"' ? QUOTED_STRING_TRIMMER.trimFrom(address) : address;
    try {
        final HostAndPort hostAndPort = HostAndPort.fromString(addr);
        final byte[] addressBytes = NetUtil.createByteArrayFromIpAddressString(hostAndPort.getHost());
        if (addressBytes == null) {
            logger.debug("Failed to parse an address: {}", address);
            return null;
        }
        return new InetSocketAddress(InetAddress.getByAddress(addressBytes),
                                     hostAndPort.getPortOrDefault(0));
    } catch (IllegalArgumentException e) {
        logger.debug("Failed to parse an address: {}", address, e);
        return null;
    }
}
 
源代码25 项目: attic-aurora   文件: LeaderRedirectTest.java
@Test
public void testRedirectTargetNoAttribute() throws Exception {
  HttpServletRequest mockRequest = mockRequest(null, null);

  replayAndMonitor(1);

  HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
  publishSchedulers(remote);

  assertEquals(
      Optional.of("http://foobar:500/some/path"),
      leaderRedirector.getRedirectTarget(mockRequest));
}
 
源代码26 项目: datacollector   文件: KafkaTargetConfig.java
private void validateTopicWhiteList(
    Stage.Context context,
    List<Stage.ConfigIssue> issues,
    List<HostAndPort> kafkaBrokers
) {
  //if runtimeTopicResolution then topic white list cannot be empty
  if(isEmpty(topicWhiteList)) {
    issues.add(
        context.createConfigIssue(
            KafkaDestinationGroups.KAFKA.name(),
            KAFKA_CONFIG_BEAN_PREFIX + "topicWhiteList",
            KafkaErrors.KAFKA_64
        )
    );
  } else if ("*".equals(topicWhiteList)) {
    allowAllTopics = true;
  } else {
    //Must be comma separated list of topic names
    if(kafkaBrokers != null && !kafkaBrokers.isEmpty()) {
      String[] topics = topicWhiteList.split(",");
      for (String t : topics) {
        t = t.trim();
        //validate supplied topic names in the white list
        validateTopicExistence(context, issues, t);
      }
    }
  }
}
 
源代码27 项目: drift   文件: TestApacheThriftMethodInvoker.java
private static int logApacheThriftInvocationHandlerOptional(HostAndPort address, List<DriftLogEntry> entries)
{
    ApacheThriftClientConfig config = new ApacheThriftClientConfig();
    ApacheThriftConnectionFactoryConfig factoryConfig = new ApacheThriftConnectionFactoryConfig();
    try (ApacheThriftMethodInvokerFactory<Void> methodInvokerFactory = new ApacheThriftMethodInvokerFactory<>(factoryConfig, clientIdentity -> config)) {
        MethodInvoker methodInvoker = methodInvokerFactory.createMethodInvoker(null);

        ThriftType optionalType = optional(list(codecManager.getCatalog().getThriftType(DriftLogEntry.class)));
        ParameterMetadata parameter = new ParameterMetadata(
                (short) 1,
                "messages",
                (ThriftCodec<Object>) codecManager.getCodec(optionalType));

        MethodMetadata methodMetadata = new MethodMetadata(
                "Log",
                ImmutableList.of(parameter),
                (ThriftCodec<Object>) (Object) codecManager.getCodec(DriftResultCode.class),
                ImmutableMap.of(),
                ImmutableMap.of(),
                false,
                true);

        ListenableFuture<Object> future = methodInvoker.invoke(new InvokeRequest(methodMetadata, () -> address, ImmutableMap.of(), ImmutableList.of(Optional.of(entries))));
        assertEquals(future.get(), DRIFT_OK);

        future = methodInvoker.invoke(new InvokeRequest(methodMetadata, () -> address, ImmutableMap.of(), ImmutableList.of(Optional.empty())));
        assertEquals(future.get(), DRIFT_OK);

        return 1;
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码28 项目: emodb   文件: ResilientMissingRefDelayProcessor.java
@Inject
public ResilientMissingRefDelayProcessor(@RetryRefTopic Topic retryRefTopic,
                                         @MissingRefTopic Topic missingRefTopic,
                                         KafkaCluster kafkaCluster, Clock clock,
                                         @SelfHostAndPort HostAndPort hostAndPort,
                                         @DelayProcessorConsumerGroup String delayProcessorConsumerGroup,
                                         MetricRegistry metricRegistry) {
    super(SERVICE_NAME,
            () -> new MissingRefDelayProcessor(retryRefTopic, missingRefTopic,
                    kafkaCluster, clock, hostAndPort, delayProcessorConsumerGroup, metricRegistry),
            RESTART_DELAY, false);
}
 
源代码29 项目: emissary   文件: PeersCommand.java
@Override
public void run(JCommander jc) {
    setup();
    try {
        System.out.print(String.join(delimiter, getPeers(HostAndPort.fromString(ignoreHost), this.withPort)));
    } catch (IOException e) {
        LOG.debug("Problem reading file", e);
    }
}
 
源代码30 项目: ChangeSkin   文件: ChangeSkinCore.java
public void load(boolean database) {
    saveDefaultFile("messages.yml");
    saveDefaultFile("config.yml");

    try {
        config = loadFile("config.yml");
        int rateLimit = config.getInt("mojang-request-limit");

        cooldownService = new CooldownService(Duration.ofSeconds(config.getInt("cooldown")));

        autoUpdateDiff = Duration.ofMinutes(config.getInt("auto-skin-update"));
        List<HostAndPort> proxies = config.getStringList("proxies")
                .stream().map(HostAndPort::fromString).collect(toList());
        skinApi = new MojangSkinApi(plugin.getLog(), rateLimit, proxies);

        if (database) {
            if (!setupDatabase(config.getSection("storage"))) {
                return;
            }

            loadDefaultSkins(config.getStringList("default-skins"));
            loadAccounts(config.getStringList("upload-accounts"));
        }

        Configuration messages = loadFile("messages.yml");

        messages.getKeys()
                .stream()
                .filter(key -> messages.get(key) != null)
                .collect(toMap(identity(), messages::get))
                .forEach((key, message) -> {
                    String colored = CommonUtil.translateColorCodes((String) message);
                    if (!colored.isEmpty()) {
                        localeMessages.put(key, colored.replace("/newline", "\n"));
                    }
                });
    } catch (IOException ioEx) {
        plugin.getLog().info("Failed to load yaml file", ioEx);
    }
}