Java Code Examples for org.springframework.cloud.commons.util.InetUtils

The following examples show how to use org.springframework.cloud.commons.util.InetUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: influx-proxy   Source File: HeartBeatService.java    License: Apache License 2.0 6 votes vote down vote up
@Scheduled(fixedRate = 5_000)
public void heartBeat() {
    if(proxyConfiguration.isEnable()||StringUtils.isEmpty(opsPath)){
        return;
    }
    try{
        InetUtils.HostInfo hostInfo = inetUtils.findFirstNonLoopbackHostInfo();
        restTemplate.getForObject(opsPath + "/ping?ip={1}&port={2}&managementPort={3}&hostname={4}",
                String.class,
                hostInfo.getIpAddress(),
                port,
                managementPort,
                hostInfo.getHostname());
    }catch (Throwable ignore){
        log.warn("Failed to ping {}",opsPath);
    }
}
 
Example 2
private SanitizingEurekaInstanceConfigBean getDefaults() {
	InetUtilsProperties inetUtilsProperties = new InetUtilsProperties();
	inetUtilsProperties.setDefaultHostname(hostname);
	inetUtilsProperties.setDefaultIpAddress(ip);

	SanitizingEurekaInstanceConfigBean eurekaInstanceConfigBean = new SanitizingEurekaInstanceConfigBean(new InetUtils(inetUtilsProperties));
	eurekaInstanceConfigBean.setHostname(hostname);
	eurekaInstanceConfigBean.setIpAddress(ip);
	Map<String, String> metadataMap = eurekaInstanceConfigBean.getMetadataMap();
	metadataMap.put(SurgicalRoutingRequestTransformer.CF_APP_GUID, cfAppGuid);
	metadataMap.put(SurgicalRoutingRequestTransformer.CF_INSTANCE_INDEX, cfInstanceIndex);
	metadataMap.put(INSTANCE_ID, instanceId);
	metadataMap.put(ZONE, zoneFromUri(zoneUri));

	return eurekaInstanceConfigBean;
}
 
Example 3
private SanitizingEurekaInstanceConfigBean getDefaults() {
	InetUtilsProperties inetUtilsProperties = new InetUtilsProperties();
	inetUtilsProperties.setDefaultHostname(hostname);
	inetUtilsProperties.setDefaultIpAddress(ip);

	SanitizingEurekaInstanceConfigBean eurekaInstanceConfigBean = new SanitizingEurekaInstanceConfigBean(
			new InetUtils(inetUtilsProperties));
	eurekaInstanceConfigBean.setHostname(hostname);
	eurekaInstanceConfigBean.setIpAddress(ip);
	Map<String, String> metadataMap = eurekaInstanceConfigBean.getMetadataMap();
	metadataMap.put(SurgicalRoutingRequestTransformer.CF_APP_GUID, cfAppGuid);
	metadataMap.put(SurgicalRoutingRequestTransformer.CF_INSTANCE_INDEX, cfInstanceIndex);
	metadataMap.put(INSTANCE_ID, instanceId);
	metadataMap.put(ZONE, zoneFromUri(zoneUri));

	return eurekaInstanceConfigBean;
}
 
Example 4
@Test
public void shouldUseDefaults() {
	this.contextRunner.run((context) -> {
		ReactiveDiscoveryClient client = context
				.getBean(ReactiveDiscoveryClient.class);
		assertThat(client).isNotNull();
		assertThat(client.getOrder())
				.isEqualTo(ReactiveDiscoveryClient.DEFAULT_ORDER);
		InetUtils inet = context.getBean(InetUtils.class);
		assertThat(inet).isNotNull();
		SimpleReactiveDiscoveryProperties properties = context
				.getBean(SimpleReactiveDiscoveryProperties.class);
		assertThat(properties).isNotNull();
		assertThat(properties.getLocal().getServiceId()).isEqualTo("application");
		assertThat(properties.getLocal().getHost())
				.isEqualTo(inet.findFirstNonLoopbackHostInfo().getHostname());
		assertThat(properties.getLocal().getPort()).isEqualTo(8080);
	});
}
 
Example 5
@Test
public void shouldUseCustomConfiguration() {
	this.contextRunner.withUserConfiguration(Configuration.class)
			.withPropertyValues("spring.application.name=my-service",
					"spring.cloud.discovery.client.simple.order=1",
					"server.port=8443")
			.run((context) -> {
				ReactiveDiscoveryClient client = context
						.getBean(ReactiveDiscoveryClient.class);
				assertThat(client).isNotNull();
				assertThat(client.getOrder()).isEqualTo(1);
				InetUtils inet = context.getBean(InetUtils.class);
				assertThat(inet).isNotNull();
				SimpleReactiveDiscoveryProperties properties = context
						.getBean(SimpleReactiveDiscoveryProperties.class);
				assertThat(properties).isNotNull();
				assertThat(properties.getLocal().getServiceId())
						.isEqualTo("my-service");
				assertThat(properties.getLocal().getHost())
						.isEqualTo(inet.findFirstNonLoopbackHostInfo().getHostname());
				assertThat(properties.getLocal().getPort()).isEqualTo(8443);
			});
}
 
Example 6
@Test
public void eurekaClientNotShutdownInDeregister() {
	EurekaServiceRegistry registry = new EurekaServiceRegistry();

	CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
	ApplicationInfoManager applicationInfoManager = mock(
			ApplicationInfoManager.class);

	when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class));

	EurekaRegistration registration = EurekaRegistration
			.builder(new EurekaInstanceConfigBean(
					new InetUtils(new InetUtilsProperties())))
			.with(eurekaClient).with(applicationInfoManager)
			.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
			.build();

	registry.deregister(registration);

	verifyNoInteractions(eurekaClient);
}
 
Example 7
@Bean
@ConditionalOnProperty(prefix = "xxl.job", value = "enabled", havingValue = "true")
public XxlJobSpringExecutor xxlJobExecutor(XxlJobClientProperties properties,
										   DiscoveryClient discoveryClient,
										   Environment environment,
										   InetUtils inetUtils) {
	log.info(">>>>>>>>>>> xxl-job client config init.");
	XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
	XxlJobAdminProps admin = properties.getAdmin();
	xxlJobSpringExecutor.setAccessToken(admin.getAccessToken());
	// 获取 admin 管理端的地址
	xxlJobSpringExecutor.setAdminAddresses(getAdminServiceUrl(discoveryClient, admin));

	XxlJobExecutorProps executor = properties.getExecutor();
	// 微服务 服务名
	String serviceId = getAppName(environment);
	xxlJobSpringExecutor.setAppname(getExecutorName(executor, serviceId));
	String ipAddress = executor.getIp();
	if (StringUtils.isEmpty(ipAddress)) {
		ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
	}
	xxlJobSpringExecutor.setIp(ipAddress);
	xxlJobSpringExecutor.setPort(executor.getPort());
	xxlJobSpringExecutor.setLogPath(getLogPath(executor, environment, serviceId));
	xxlJobSpringExecutor.setLogRetentionDays(executor.getLogRetentionDays());
	return xxlJobSpringExecutor;
}
 
Example 8
private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) {
    InetUtilsProperties target = new InetUtilsProperties();
    ConfigurationPropertySources.attach(environment);
    Binder.get(environment).bind(InetUtilsProperties.PREFIX, Bindable.ofInstance(target));
    try (InetUtils utils = new InetUtils(target)) {
        return utils.findFirstNonLoopbackHostInfo();
    }
}
 
Example 9
@Bean
@ConditionalOnMissingBean(value = EurekaInstanceConfig.class, search = SearchStrategy.CURRENT)
public EurekaInstanceConfigBean eurekaInstanceConfigBean(
        InetUtils inetUtils, ManagementMetadataProvider managementMetadataProvider) {
    EurekaInstanceConfigBean instance = new EurekaClientAutoConfiguration(env)
            .eurekaInstanceConfigBean(inetUtils, managementMetadataProvider);

    String brpcPort = env.getProperty(ENV_PORT_KEY);
    if (StringUtils.isNoneBlank(brpcPort)) {
        instance.getMetadataMap().put(META_DATA_PORT_KEY, brpcPort);
    }
    return instance;
}
 
Example 10
public void exportURL(URL url) {
	URL actualURL = url;
	InetUtils.HostInfo hostInfo = inetUtils.findFirstNonLoopbackHostInfo();
	String ipAddress = hostInfo.getIpAddress();
	// To use InetUtils to set IP if they are different
	// issue :
	// https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/589
	if (!Objects.equals(url.getHost(), ipAddress)) {
		actualURL = url.setHost(ipAddress);
	}
	this.allExportedURLs.add(actualURL.getServiceKey(), actualURL);
}
 
Example 11
public ConsulStubsRegistrar(StubRunning stubRunning, ConsulClient consulClient,
		StubMapperProperties stubMapperProperties,
		ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
	this.stubRunning = stubRunning;
	this.consulClient = consulClient;
	this.stubMapperProperties = stubMapperProperties;
	this.consulDiscoveryProperties = consulDiscoveryProperties;
	this.inetUtils = inetUtils;
}
 
Example 12
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
		ConsulClient consulClient, StubMapperProperties stubMapperProperties,
		ConsulDiscoveryProperties consulDiscoveryProperties, InetUtils inetUtils) {
	return new ConsulStubsRegistrar(stubRunning, consulClient, stubMapperProperties,
			consulDiscoveryProperties, inetUtils);
}
 
Example 13
@Bean(initMethod = "registerStubs")
public StubsRegistrar stubsRegistrar(StubRunning stubRunning,
		ServiceRegistry<EurekaRegistration> serviceRegistry,
		ApplicationContext context, StubMapperProperties stubMapperProperties,
		InetUtils inetUtils, EurekaInstanceConfigBean eurekaInstanceConfigBean,
		EurekaClientConfigBean eurekaClientConfigBean) {
	return new EurekaStubsRegistrar(stubRunning, serviceRegistry,
			stubMapperProperties, inetUtils, eurekaInstanceConfigBean,
			eurekaClientConfigBean, context);
}
 
Example 14
public EurekaStubsRegistrar(StubRunning stubRunning,
		ServiceRegistry<EurekaRegistration> serviceRegistry,
		StubMapperProperties stubMapperProperties, InetUtils inetUtils,
		EurekaInstanceConfigBean eurekaInstanceConfigBean,
		EurekaClientConfigBean eurekaClientConfigBean, ApplicationContext context) {
	this.stubRunning = stubRunning;
	this.stubMapperProperties = stubMapperProperties;
	this.serviceRegistry = serviceRegistry;
	this.inetUtils = inetUtils;
	this.eurekaInstanceConfigBean = eurekaInstanceConfigBean;
	this.eurekaClientConfigBean = eurekaClientConfigBean;
	this.context = context;
}
 
Example 15
DefaultEndpointLocator(Registration registration, ServerProperties serverProperties,
		Environment environment, ZipkinProperties zipkinProperties,
		InetUtils inetUtils) {
	this.registration = registration;
	this.serverProperties = serverProperties;
	this.environment = environment;
	this.zipkinProperties = zipkinProperties;
	this.firstNonLoopbackAddress = findFirstNonLoopbackAddress(inetUtils);
}
 
Example 16
@Bean
public ZookeeperDiscoveryProperties zookeeperDiscoveryProperties(
		InetUtils inetUtils) {
	ZookeeperDiscoveryProperties properties = new ZookeeperDiscoveryProperties(
			inetUtils);
	// for bootstrap, registration is not needed, just discovery client
	properties.setRegister(false);
	return properties;
}
 
Example 17
@Test
public void should_escape_root() {
	// given:
	ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = new ZookeeperDiscoveryProperties(
			new InetUtils(new InetUtilsProperties()));
	// when:
	zookeeperDiscoveryProperties.setRoot(root);
	// then:
	then(zookeeperDiscoveryProperties.getRoot()).isEqualTo("/es");
}
 
Example 18
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
		SpringApplication application) {
	InetUtils.HostInfo hostInfo = getFirstNonLoopbackHostInfo(environment);
	LinkedHashMap<String, Object> map = new LinkedHashMap<>();
	map.put("spring.cloud.client.hostname", hostInfo.getHostname());
	map.put("spring.cloud.client.ip-address", hostInfo.getIpAddress());
	MapPropertySource propertySource = new MapPropertySource(
			"springCloudClientHostInfo", map);
	environment.getPropertySources().addLast(propertySource);
}
 
Example 19
private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) {
	InetUtilsProperties target = new InetUtilsProperties();
	ConfigurationPropertySources.attach(environment);
	Binder.get(environment).bind(InetUtilsProperties.PREFIX,
			Bindable.ofInstance(target));
	try (InetUtils utils = new InetUtils(target)) {
		return utils.findFirstNonLoopbackHostInfo();
	}
}
 
Example 20
@Test
public void eurekaClientGetStatus() {
	EurekaServiceRegistry registry = new EurekaServiceRegistry();

	EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(
			new InetUtils(new InetUtilsProperties()));
	config.setAppname("myapp");
	config.setInstanceId("1234");

	InstanceInfo local = InstanceInfo.Builder.newBuilder().setAppName("myapp")
			.setInstanceId("1234").setStatus(DOWN).build();

	InstanceInfo remote = InstanceInfo.Builder.newBuilder().setAppName("myapp")
			.setInstanceId("1234").setStatus(DOWN).setOverriddenStatus(OUT_OF_SERVICE)
			.build();

	CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
	when(eurekaClient.getInstanceInfo(local.getAppName(), local.getId()))
			.thenReturn(remote);

	ApplicationInfoManager applicationInfoManager = mock(
			ApplicationInfoManager.class);
	when(applicationInfoManager.getInfo()).thenReturn(local);

	EurekaRegistration registration = EurekaRegistration.builder(config)
			.with(eurekaClient).with(applicationInfoManager)
			.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
			.build();

	Object status = registry.getStatus(registration);

	assertThat(registration.getInstanceId()).isEqualTo("1234");

	assertThat(status).isInstanceOf(Map.class);

	Map<Object, Object> map = (Map<Object, Object>) status;

	assertThat(map).hasSize(2).containsEntry("status", DOWN.toString())
			.containsEntry("overriddenStatus", OUT_OF_SERVICE.toString());
}
 
Example 21
@Test
public void eurekaClientGetStatusNoInstance() {
	EurekaServiceRegistry registry = new EurekaServiceRegistry();

	EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(
			new InetUtils(new InetUtilsProperties()));
	config.setAppname("myapp");
	config.setInstanceId("1234");

	CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);

	when(eurekaClient.getInstanceInfo("myapp", "1234")).thenReturn(null);

	ApplicationInfoManager applicationInfoManager = mock(
			ApplicationInfoManager.class);
	when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class));

	EurekaRegistration registration = EurekaRegistration.builder(config)
			.with(eurekaClient).with(applicationInfoManager)
			.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
			.build();

	Object status = registry.getStatus(registration);

	assertThat(registration.getInstanceId()).isEqualTo("1234");

	assertThat(status).isInstanceOf(Map.class);

	Map<Object, Object> map = (Map<Object, Object>) status;

	assertThat(map).hasSize(1).containsEntry("status", UNKNOWN.toString());
}
 
Example 22
@Test
public void instanceIdIsHostNameByDefault() throws IOException {
	InstanceInfo instanceInfo = setupInstance();
	try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
		assertThat(instanceInfo.getId())
				.isEqualTo(utils.findFirstNonLoopbackHostInfo().getHostname());
	}
}
 
Example 23
@Before
public void init() throws Exception {
	try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
		InetUtils.HostInfo hostInfo = utils.findFirstNonLoopbackHostInfo();
		this.hostName = hostInfo.getHostname();
		this.ipAddress = hostInfo.getIpAddress();
	}
}
 
Example 24
@Bean
public EurekaInstanceConfigBean eurekaInstanceConfigBean() {
	EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean(
			new InetUtils(new InetUtilsProperties()));
	String springAppName = this.env.getProperty("spring.application.name", "");
	if (StringUtils.hasText(springAppName)) {
		configBean.setSecureVirtualHostName(springAppName);
		configBean.setVirtualHostName(springAppName);
		configBean.setAppname(springAppName);
	}
	return configBean;
}
 
Example 25
@Before
public void setUp() {
	this.properties = new ConsulDiscoveryProperties(
			new InetUtils(new InetUtilsProperties()));
	this.properties.setDefaultQueryTag(DEFAULT_TAG);
	this.properties.setServerListQueryTags(this.serverListQueryTags);
	this.properties.setDatacenters(this.datacenters);
}
 
Example 26
Source Project: Moss   Source File: MossServerDiscoveryAutoConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public ConsulDiscoveryProperties consulDiscoveryProperties(InetUtils inetUtils) {
    return new ConsulDiscoveryProperties(inetUtils);
}
 
Example 27
Source Project: Moss   Source File: MultRegisterCenterServerMgmtConfig.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 构造 EurekaInstanceConfigBean
 *
 * @param inetUtils
 * @param env
 * @param managementMetadataProvider
 * @return
 */
public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils, ConfigurableEnvironment env
        , ManagementMetadataProvider managementMetadataProvider) {
    String hostname = getProperty("eureka.instance.hostname", env);
    boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address", env));
    String ipAddress = getProperty("eureka.instance.ip-address", env);
    boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled", env));

    String serverContextPath = env.getProperty("server.context-path", "/");
    int serverPort = Integer.valueOf(env.getProperty("server.port", env.getProperty("port", "8080")));

    Integer managementPort = env.getProperty("management.server.port", Integer.class);// nullable. should be wrapped into optional
    String managementContextPath = env.getProperty("management.server.servlet.context-path");// nullable. should be wrapped into optional
    Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);//nullable
    EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils);

    instance.setNonSecurePort(serverPort);
    instance.setInstanceId(getDefaultInstanceId(env));
    instance.setPreferIpAddress(preferIpAddress);
    instance.setSecurePortEnabled(isSecurePortEnabled);
    if (StringUtils.hasText(ipAddress)) {
        instance.setIpAddress(ipAddress);
    }

    if (isSecurePortEnabled) {
        instance.setSecurePort(serverPort);
    }

    if (StringUtils.hasText(hostname)) {
        instance.setHostname(hostname);
    }
    String statusPageUrlPath = getProperty("eureka.instance.status-page-url-path", env);
    String healthCheckUrlPath = getProperty("eureka.instance.health-check-url-path", env);

    if (StringUtils.hasText(statusPageUrlPath)) {
        instance.setStatusPageUrlPath(statusPageUrlPath);
    }
    if (StringUtils.hasText(healthCheckUrlPath)) {
        instance.setHealthCheckUrlPath(healthCheckUrlPath);
    }

    ManagementMetadata metadata = managementMetadataProvider.get(instance, serverPort,
            serverContextPath, managementContextPath, managementPort);

    if (metadata != null) {
        instance.setStatusPageUrl(metadata.getStatusPageUrl());
        instance.setHealthCheckUrl(metadata.getHealthCheckUrl());
        if (instance.isSecurePortEnabled()) {
            instance.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl());
        }
        Map<String, String> metadataMap = instance.getMetadataMap();
        if (metadataMap.get("management.port") == null) {
            metadataMap.put("management.port", String.valueOf(metadata.getManagementPort()));
        }
    } else {
        //without the metadata the status and health check URLs will not be set
        //and the status page and health check url paths will not include the
        //context path so set them here
        if (StringUtils.hasText(managementContextPath)) {
            instance.setHealthCheckUrlPath(managementContextPath + instance.getHealthCheckUrlPath());
            instance.setStatusPageUrlPath(managementContextPath + instance.getStatusPageUrlPath());
        }
    }

    setupJmxPort(instance, jmxPort);
    return instance;
}
 
Example 28
public TarsEurekaInstance(InetUtils inetUtils) {
    super(inetUtils);
}
 
Example 29
public void setInetUtils(InetUtils inetUtils) {
	this.inetUtils = inetUtils;
}
 
Example 30
private InetUtils localAddress(byte[] address) throws UnknownHostException {
	InetUtils mocked = Mockito.spy(new InetUtils(new InetUtilsProperties()));
	Mockito.when(mocked.findFirstNonLoopbackAddress())
			.thenReturn(InetAddress.getByAddress(address));
	return mocked;
}