Java Code Examples for com.google.common.net.HostAndPort#hasPort()

The following examples show how to use com.google.common.net.HostAndPort#hasPort() . 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: SshMachineLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();

    // Register any pre-existing port-mappings with the PortForwardManager
    Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
    if (tcpPortMappings != null) {
        PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
        for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
            int targetPort = entry.getKey();
            HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
            if (!publicEndpoint.hasPort()) {
                throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
            }
            pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
        }
    }
}
 
Example 2
Source File: WinRmMachineLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();

    // Register any pre-existing port-mappings with the PortForwardManager
    Map<Integer, String> tcpPortMappings = getConfig(TCP_PORT_MAPPINGS);
    if (tcpPortMappings != null) {
        PortForwardManager pfm = (PortForwardManager) getManagementContext().getLocationRegistry().getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
        for (Map.Entry<Integer, String> entry : tcpPortMappings.entrySet()) {
            int targetPort = entry.getKey();
            HostAndPort publicEndpoint = HostAndPort.fromString(entry.getValue());
            if (!publicEndpoint.hasPort()) {
                throw new IllegalArgumentException("Invalid portMapping ('"+entry.getValue()+"') for port "+targetPort+" in machine "+this);
            }
            pfm.associate(publicEndpoint.getHostText(), publicEndpoint, this, targetPort);
        }
    }
}
 
Example 3
Source File: ParquetGroupScanUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: AbstractOnNetworkEnricher.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 5
Source File: MongoStoreProvider.java    From alchemy with MIT License 6 votes vote down vote up
@Override
public ExperimentsStoreProvider createProvider() throws UnknownHostException {
    final io.rtr.alchemy.db.mongo.MongoStoreProvider.Builder builder = io.rtr.alchemy.db.mongo.MongoStoreProvider.newBuilder();
    for (final HostAndPort host : hosts) {
        if (!host.hasPort()) {
            builder.addHost(new ServerAddress(host.getHost()));
        } else {
            builder.addHost(new ServerAddress(host.getHost(), host.getPort()));
        }
    }

    if (username != null) {
        builder.addCredential(MongoCredential.createPlainCredential(username, db, password.toCharArray()));
    }

    builder.setDatabase(db);

    return builder.build();
}
 
Example 6
Source File: TestEndpointReachableImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected HostAndPort toHostAndPort(String endpoint) {
    if (Strings.isEmpty(endpoint)) {
        throw new IllegalArgumentException(String.format("The entity [%s] has no endpoint", getClass().getName()));
    }
    try {
        URI uri = URI.create(endpoint);
        int port;
        if (uri.getPort() != -1) {
            port = uri.getPort();
        } else {
            if ("http".equalsIgnoreCase(uri.getScheme())) {
                port = 80;
            } else if ("https".equalsIgnoreCase(uri.getScheme())) {
                port = 443;
            } else {
                throw new IllegalArgumentException(String.format("The entity [%s] with endpoint [%s] has no port", getClass().getName(), endpoint));
            }
        }
        return HostAndPort.fromParts(uri.getHost(), port);
    } catch (IllegalArgumentException e) {
        // Not a URL; fall-back to host-and-port
    }
    
    HostAndPort result = HostAndPort.fromString(endpoint);
    if (!result.hasPort()) {
        throw new IllegalArgumentException(String.format("The entity [%s] with endpoint [%s] has no port", getClass().getName(), endpoint));
    }
    return result;
}
 
Example 7
Source File: UserAndHostAndPortTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void assertIt(UserAndHostAndPort actual, String user, HostAndPort hostAndPort) {
    assertEquals(actual.getUser(), user);
    assertEquals(actual.getHostAndPort(), hostAndPort);
    if (hostAndPort.hasPort()) {
        assertEquals(actual.toString(), user + "@" + hostAndPort.getHostText() + ":" + hostAndPort.getPort());
    } else {
        assertEquals(actual.toString(), user + "@" + hostAndPort.getHostText());
    }
}
 
Example 8
Source File: UserAndHostAndPort.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static UserAndHostAndPort fromParts(String user, String host, Optional<Integer> port) {
    HostAndPort hostAndPort = port.isPresent() ? HostAndPort.fromParts(host, port.get()) : HostAndPort.fromString(host);
    if (!port.isPresent() && hostAndPort.hasPort()) {
        throw new IllegalArgumentException("optional port absent, but host '"+host+"' parsed as containing port");
    }
    return new UserAndHostAndPort(user, hostAndPort);
}
 
Example 9
Source File: BaseKafkaValidationUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public List<HostAndPort> validateKafkaBrokerConnectionString(
  List<Stage.ConfigIssue> issues,
  String connectionString,
  String configGroupName,
  String configName,
  Stage.Context context
) {
  List<HostAndPort> kafkaBrokers = new ArrayList<>();
  if (connectionString == null || connectionString.isEmpty()) {
    issues.add(context.createConfigIssue(configGroupName, configName,
      KafkaErrors.KAFKA_06, configName));
  } else {
    String[] brokers = connectionString.split(",");
    for (String broker : brokers) {
      try {
        HostAndPort hostAndPort = HostAndPort.fromString(broker);
        if(!hostAndPort.hasPort() || hostAndPort.getPort() < 0) {
          issues.add(context.createConfigIssue(configGroupName, configName, KafkaErrors.KAFKA_07, connectionString));
        } else {
          kafkaBrokers.add(hostAndPort);
        }
      } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(configGroupName, configName, KafkaErrors.KAFKA_07, connectionString));
      }
    }
  }
  return kafkaBrokers;
}
 
Example 10
Source File: AerospikeBeanConfig.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static List<Host> getAerospikeHosts(
    List<Target.ConfigIssue> issues,
    List<String> connectionString,
    String configGroupName,
    String configName,
    Target.Context context
) {
  List<Host> clusterNodesList = new ArrayList<>();
  if (connectionString == null || connectionString.isEmpty()) {
    issues.add(context.createConfigIssue(configGroupName, configName,
        AerospikeErrors.AEROSPIKE_01, configName));
  } else {
    for (String node : connectionString) {
      try {
        HostAndPort hostAndPort = HostAndPort.fromString(node);
        if (!hostAndPort.hasPort() || hostAndPort.getPort() < 0) {
          issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_02, connectionString));
        } else {
          clusterNodesList.add(new Host(hostAndPort.getHostText(), hostAndPort.getPort()));
        }
      } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_02, connectionString));
      }
    }
  }
  return clusterNodesList;
}
 
Example 11
Source File: AbstractOnNetworkEnricher.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected boolean isHostAndPort(Object sensorVal) {
    if (sensorVal instanceof HostAndPort) {
        return true;
    } else if (sensorVal instanceof String) {
        try {
            HostAndPort hostAndPort = HostAndPort.fromString((String)sensorVal);
            return hostAndPort.hasPort();
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
    return false;
}
 
Example 12
Source File: PayloadBuilder.java    From emodb with Apache License 2.0 5 votes vote down vote up
public PayloadBuilder withHostAndPort(HostAndPort host) {
    withHost(host.getHostText());
    if (host.hasPort()) {
        withPort(host.getPort());
        withAdminPort(host.getPort() + 1);
    }
    return this;
}
 
Example 13
Source File: SplitWork.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
NodeEndpoint getMatchingNode(HostAndPort hostPort) {
  if (!hostPort.hasPort()) {
    return nodeMap.getEndpoint(hostPort.getHost());
  }

  // affinity host has port information
  // match it exactly
  return nodeMap.getExactEndpoint(hostPort.getHost(), hostPort.getPort());
}
 
Example 14
Source File: EndpointAffinity.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
static NodeEndpoint getNodeEndpointFromHostPort(HostAndPort hostAndPort) {
  NodeEndpoint.Builder builder = NodeEndpoint.newBuilder().setAddress(hostAndPort.getHost());
  if (hostAndPort.hasPort()) {
    builder.setFabricPort(hostAndPort.getPort());
  }

  return builder.build();
}
 
Example 15
Source File: HostProxy.java    From styx with Apache License 2.0 5 votes vote down vote up
private static HostAndPort addDefaultPort(HostAndPort hostAndPort, TlsSettings tlsSettings) {
    if (hostAndPort.hasPort()) {
        return hostAndPort;
    }

    int defaultPort = Optional.ofNullable(tlsSettings)
            .map(it -> DEFAULT_TLS_PORT)
            .orElse(DEFAULT_HTTP_PORT);

    return HostAndPort.fromParts(hostAndPort.getHost(), defaultPort);
}
 
Example 16
Source File: CassandraConfiguration.java    From emodb with Apache License 2.0 4 votes vote down vote up
private com.datastax.driver.core.Cluster.Builder newCqlDriverBuilder(ConnectionPoolConfiguration poolConfig,
                                                                     MetricRegistry metricRegistry) {
    performHostDiscovery(metricRegistry);

    String[] seeds = _seeds.split(",");
    List<String> contactPoints = Lists.newArrayListWithCapacity(seeds.length);

    // Each seed may be a host name or a host name and port (e.g.; "1.2.3.4" or "1.2.3.4:9160").  These need
    // to be converted into host names only.
    for (String seed : seeds) {
        HostAndPort hostAndPort = HostAndPort.fromString(seed);
        seed = hostAndPort.getHostText();
        if (hostAndPort.hasPort()) {
            if (hostAndPort.getPort() == _thriftPort) {
                _log.debug("Seed {} found using RPC port; swapping for native port {}", seed, _cqlPort);
            } else if (hostAndPort.getPort() != _cqlPort) {
                throw new IllegalArgumentException(String.format(
                        "Seed %s found with invalid port %s.  The port must match either the RPC (thrift) port %s " +
                        "or the native (CQL) port %s", seed, hostAndPort.getPort(), _thriftPort, _cqlPort));
            }
        }

        contactPoints.add(seed);
    }

    PoolingOptions poolingOptions = new PoolingOptions();
    if (poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).isPresent()) {
        poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).get());
    }
    if (poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).isPresent()) {
        poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).get());
    }

    SocketOptions socketOptions = new SocketOptions();
    if (poolConfig.getConnectTimeout().or(getConnectTimeout()).isPresent()) {
        socketOptions.setConnectTimeoutMillis(poolConfig.getConnectTimeout().or(getConnectTimeout()).get());
    }
    if (poolConfig.getSocketTimeout().or(getSocketTimeout()).isPresent()) {
        socketOptions.setReadTimeoutMillis(poolConfig.getSocketTimeout().or(getSocketTimeout()).get());
    }

    AuthProvider authProvider = _authenticationCredentials != null
            ? new PlainTextAuthProvider(_authenticationCredentials.getUsername(), _authenticationCredentials.getPassword())
            : AuthProvider.NONE;

    return com.datastax.driver.core.Cluster.builder()
            .addContactPoints(contactPoints.toArray(new String[contactPoints.size()]))
            .withPort(_cqlPort)
            .withPoolingOptions(poolingOptions)
            .withSocketOptions(socketOptions)
            .withRetryPolicy(Policies.defaultRetryPolicy())
            .withAuthProvider(authProvider);
}
 
Example 17
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(
        ComputeService computeService, NodeMetadata node, Optional<Template> template,
        LoginCredentials userCredentials, HostAndPort managementHostAndPort, ConfigBag setup) throws IOException {

    Collection<JcloudsLocationCustomizer> customizers = getCustomizers(setup);
    Collection<MachineLocationCustomizer> machineCustomizers = getMachineCustomizers(setup);
    Map<?,?> sshConfig = extractSshConfig(setup, node);
    String nodeAvailabilityZone = extractAvailabilityZone(setup, node);
    String nodeRegion = extractRegion(setup, node);
    if (nodeRegion == null) {
        // e.g. rackspace doesn't have "region", so rackspace-uk is best we can say (but zone="LON")
        nodeRegion = extractProvider(setup, node);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("creating JcloudsSshMachineLocation representation for {}@{} ({}) for {}/{}",
                new Object[]{
                        getUser(setup),
                        managementHostAndPort,
                        Sanitizer.sanitize(sshConfig),
                        getCreationString(setup),
                        node
                });
    }

    String address = managementHostAndPort.getHostText();
    int port = managementHostAndPort.hasPort() ? managementHostAndPort.getPort() : node.getLoginPort();
    
    // The display name will be one of the IPs of the VM (preferring public if there are any).
    // If the managementHostAndPort matches any of the IP contenders, then prefer that.
    // (Don't just use the managementHostAndPort, because that could be using DNAT so could be
    // a shared IP address, for example).
    String displayName = getPublicHostnameGeneric(node, setup, Optional.of(address));
    
    final Object password = sshConfig.get(SshMachineLocation.PASSWORD.getName()) != null
            ? sshConfig.get(SshMachineLocation.PASSWORD.getName())
            : userCredentials.getOptionalPassword().orNull();
    final Object privateKeyData = sshConfig.get(SshMachineLocation.PRIVATE_KEY_DATA.getName()) != null
            ? sshConfig.get(SshMachineLocation.PRIVATE_KEY_DATA.getName())
            : userCredentials.getOptionalPrivateKey().orNull();
    if (isManaged()) {
        final LocationSpec<JcloudsSshMachineLocation> spec = LocationSpec.create(JcloudsSshMachineLocation.class)
                .configure(sshConfig)
                .configure("displayName", displayName)
                .configure("address", address)
                .configure(JcloudsSshMachineLocation.SSH_PORT, port)
                .configure("user", userCredentials.getUser())
                // The use of `getName` is intentional. See 11741d85b9f54 for details.
                .configure(SshMachineLocation.PASSWORD.getName(), password)
                .configure(SshMachineLocation.PRIVATE_KEY_DATA.getName(), privateKeyData)
                .configure("jcloudsParent", this)
                .configure("node", node)
                .configure("template", template.orNull())
                .configureIfNotNull(CLOUD_AVAILABILITY_ZONE_ID, nodeAvailabilityZone)
                .configureIfNotNull(CLOUD_REGION_ID, nodeRegion)
                .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT))
                .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, setup.get(SshMachineLocation.DETECT_MACHINE_DETAILS))
                .configureIfNotNull(SshMachineLocation.SCRIPT_DIR, setup.get(SshMachineLocation.SCRIPT_DIR))
                .configureIfNotNull(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
                .configureIfNotNull(PORT_FORWARDER, setup.get(PORT_FORWARDER))
                .configureIfNotNull(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER))
                .configureIfNotNull(SshMachineLocation.PRIVATE_ADDRESSES, node.getPrivateAddresses())
                .configureIfNotNull(JCLOUDS_LOCATION_CUSTOMIZERS, customizers.size() > 0 ? customizers : null)
                .configureIfNotNull(MACHINE_LOCATION_CUSTOMIZERS, machineCustomizers.size() > 0 ? machineCustomizers : null);
        return getManagementContext().getLocationManager().createLocation(spec);
    } else {
        LOG.warn("Using deprecated JcloudsSshMachineLocation constructor because " + this + " is not managed");
        final MutableMap.Builder<Object, Object> builder = MutableMap.builder()
            .putAll(sshConfig)
            .put("displayName", displayName)
            .put("address", address)
            .put("port", port)
            .put("user", userCredentials.getUser())
            // The use of `getName` is intentional. See 11741d85b9f54 for details.
            .putIfNotNull(SshMachineLocation.PASSWORD.getName(), password)
            .putIfNotNull(SshMachineLocation.PRIVATE_KEY_DATA.getName(), privateKeyData)
            .put("callerContext", setup.get(CALLER_CONTEXT))
            .putIfNotNull(CLOUD_AVAILABILITY_ZONE_ID.getName(), nodeAvailabilityZone)
            .putIfNotNull(CLOUD_REGION_ID.getName(), nodeRegion)
            .put(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
            .put(PORT_FORWARDER, setup.get(PORT_FORWARDER))
            .put(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER))
            .put(SshMachineLocation.PRIVATE_ADDRESSES, node.getPrivateAddresses());
        if (customizers.size() > 0) {
            builder.put(JCLOUDS_LOCATION_CUSTOMIZERS, customizers);
        }
        if (machineCustomizers.size() > 0) {
            builder.put(MACHINE_LOCATION_CUSTOMIZERS, machineCustomizers);
        }
        final MutableMap<Object, Object> properties = builder.build();
        return new JcloudsSshMachineLocation(properties, this, node);
    }
}
 
Example 18
Source File: CentralDogmaClientAutoConfiguration.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a newly created {@link CentralDogma} client.
 */
@Bean
public CentralDogma dogmaClient(
        Environment env,
        CentralDogmaSettings settings,
        @ForCentralDogma ClientFactory clientFactory,
        Optional<ArmeriaClientConfigurator> armeriaClientConfigurator) throws UnknownHostException {

    final ArmeriaCentralDogmaBuilder builder = new ArmeriaCentralDogmaBuilder();

    builder.clientFactory(clientFactory);
    builder.clientConfigurator(cb -> armeriaClientConfigurator.ifPresent(
            configurator -> configurator.configure(cb)));

    // Set health check interval.
    final Long healthCheckIntervalMillis = settings.getHealthCheckIntervalMillis();
    if (healthCheckIntervalMillis != null) {
        builder.healthCheckIntervalMillis(healthCheckIntervalMillis);
    }

    // Enable or disable TLS.
    final Boolean useTls = settings.getUseTls();
    if (useTls != null) {
        builder.useTls(useTls);
    }

    // Set access token.
    final String accessToken = settings.getAccessToken();
    if (accessToken != null) {
        builder.accessToken(accessToken);
    }

    // Set profile or hosts.
    final String profile = settings.getProfile();
    final List<String> hosts = settings.getHosts();
    if (profile != null) {
        if (hosts != null) {
            throw new IllegalStateException(
                    "'hosts' and 'profile' are mutually exclusive. Do not set both of them.");
        }
        builder.profile(CentralDogmaClientAutoConfiguration.class.getClassLoader(), profile);
    } else if (hosts != null) {
        for (String h : hosts) {
            final HostAndPort hostAndPort = HostAndPort.fromString(h);
            if (hostAndPort.hasPort()) {
                builder.host(hostAndPort.getHost(), hostAndPort.getPort());
            } else {
                builder.host(hostAndPort.getHost());
            }
        }
    } else {
        // Use the currently active Spring Boot profiles if neither profile nor hosts was specified.
        final String[] springBootProfiles = env.getActiveProfiles();
        logger.info("Using the Spring Boot profiles as the source of the Central Dogma client profile: {}",
                    springBootProfiles);
        builder.profile(springBootProfiles);
    }

    // Replication lag tolerance settings.
    final Integer maxNumRetriesOnReplicationLag = settings.getMaxNumRetriesOnReplicationLag();
    if (maxNumRetriesOnReplicationLag != null) {
        builder.maxNumRetriesOnReplicationLag(maxNumRetriesOnReplicationLag);
    }

    final Long retryIntervalOnReplicationLagMillis = settings.getRetryIntervalOnReplicationLagMillis();
    if (retryIntervalOnReplicationLagMillis != null) {
        builder.retryIntervalOnReplicationLagMillis(retryIntervalOnReplicationLagMillis);
    }

    return builder.build();
}
 
Example 19
Source File: BrowserMobHttpUtil.java    From Dream-Catcher with MIT License 3 votes vote down vote up
/**
 * Removes a port from a host+port if the string contains the specified port. If the host+port does not contain
 * a port, or contains another port, the string is returned unaltered. For example, if hostWithPort is the
 * string {@code www.website.com:443}, this method will return {@code www.website.com}.
 *
 * <b>Note:</b> The hostWithPort string is not a URI and should not contain a scheme or resource. This method does
 * not attempt to validate the specified host; it <i>might</i> throw IllegalArgumentException if there was a problem
 * parsing the hostname, but makes no guarantees. In general, it should be validated externally, if necessary.
 *
 * @param hostWithPort string containing a hostname and optional port
 * @param portNumber port to remove from the string
 * @return string with the specified port removed, or the original string if it did not contain the portNumber
 */
public static String removeMatchingPort(String hostWithPort, int portNumber) {
    HostAndPort parsedHostAndPort = HostAndPort.fromString(hostWithPort);
    if (parsedHostAndPort.hasPort() && parsedHostAndPort.getPort() == portNumber) {
        // HostAndPort.getHostText() strips brackets from ipv6 addresses, so reparse using fromHost
        return HostAndPort.fromHost(parsedHostAndPort.getHostText()).toString();
    } else {
        return hostWithPort;
    }
}
 
Example 20
Source File: BrowserMobHttpUtil.java    From CapturePacket with MIT License 3 votes vote down vote up
/**
 * Removes a port from a host+port if the string contains the specified port. If the host+port does not contain
 * a port, or contains another port, the string is returned unaltered. For example, if hostWithPort is the
 * string {@code www.website.com:443}, this method will return {@code www.website.com}.
 *
 * <b>Note:</b> The hostWithPort string is not a URI and should not contain a scheme or resource. This method does
 * not attempt to validate the specified host; it <i>might</i> throw IllegalArgumentException if there was a problem
 * parsing the hostname, but makes no guarantees. In general, it should be validated externally, if necessary.
 *
 * @param hostWithPort string containing a hostname and optional port
 * @param portNumber port to remove from the string
 * @return string with the specified port removed, or the original string if it did not contain the portNumber
 */
public static String removeMatchingPort(String hostWithPort, int portNumber) {
    HostAndPort parsedHostAndPort = HostAndPort.fromString(hostWithPort);
    if (parsedHostAndPort.hasPort() && parsedHostAndPort.getPort() == portNumber) {
        // HostAndPort.getHostText() strips brackets from ipv6 addresses, so reparse using fromHost
        return HostAndPort.fromHost(parsedHostAndPort.getHost()).toString();
    } else {
        return hostWithPort;
    }
}