Java Code Examples for com.ecwid.consul.v1.Response#getValue()

The following examples show how to use com.ecwid.consul.v1.Response#getValue() . 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: ConsulAutoServiceRegistrationManagementDisabledServiceTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();

	Service mgmtService = services.get("myTestService-NM-0-management");
	assertThat(mgmtService).as("Management service was not null").isNull();

	Service service = services.get("myTestService1-NM");
	assertThat(service).as("Service was not null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-NM");
	assertThat(service.getService()).as("service name was wrong")
			.isEqualTo("myTestService-NM");
	assertThat(StringUtils.isEmpty(service.getAddress()))
			.as("service address must not be empty").isFalse();
	assertThat(service.getAddress())
			.as("service address must equals hostname from discovery properties")
			.isEqualTo(this.discoveryProperties.getHostname());

}
 
Example 2
Source File: ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore // FIXME: 3.0.0
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-WithGroup");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-WithGroup");
	assertThat(service.getTags().contains("group=test")).as("service group was wrong")
			.isTrue();

	// ConsulServerList serverList = new ConsulServerList(this.consul,
	// this.properties);
	// DefaultClientConfigImpl config = new DefaultClientConfigImpl();
	// config.setClientName("myTestService-WithGroup");
	// serverList.initWithNiwsConfig(config);
	//
	// List<ConsulServer> servers = serverList.getInitialListOfServers();
	// assertThat(servers.size()).as("servers was wrong size").isEqualTo(1);
	// assertThat(servers.get(0).getMetaInfo().getServerGroup())
	// .as("service group was wrong").isEqualTo("test");
}
 
Example 3
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sync(TaskDO taskDO) {
    try {
        ConsulClient consulClient = consulServerHolder.get(taskDO.getSourceClusterId(), null);
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        Response<List<HealthService>> response =
            consulClient.getHealthServices(taskDO.getServiceName(), true, QueryParams.DEFAULT);
        List<HealthService> healthServiceList = response.getValue();
        Set<String> instanceKeys = new HashSet<>();
        overrideAllInstance(taskDO, destNamingService, healthServiceList, instanceKeys);
        cleanAllOldInstance(taskDO, destNamingService, instanceKeys);
        specialSyncEventBus.subscribe(taskDO, this::sync);
    } catch (Exception e) {
        log.error("Sync task from consul to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.SYNC_ERROR);
        return false;
    }
    return true;
}
 
Example 4
Source File: AclConsulClientTest.java    From consul-api with Apache License 2.0 6 votes vote down vote up
private void should_create_acl_token(AclType aclType) {
    // given
    NewAcl newAcl = new NewAcl();
    newAcl.setName("test-acl");
    newAcl.setType(aclType);
    newAcl.setRules("");

    // when
    Response<String> response = aclClient.aclCreate(newAcl, ACL_MASTER_TOKEN);
    String aclId = response.getValue();

    // then
    Acl createdAcl = aclClient.getAcl(aclId).getValue();
    assertThat(createdAcl.getName(), equalTo(newAcl.getName()));
    assertThat(createdAcl.getType(), equalTo(newAcl.getType()));
    assertThat(createdAcl.getRules(), equalTo(newAcl.getRules()));
}
 
Example 5
Source File: ConsulAutoServiceDeRegistrationDisabledTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private void checkService(final boolean expected) {
	final Response<Map<String, Service>> response = this.consul.getAgentServices();
	final Map<String, Service> services = response.getValue();
	final Service service = services.get("myTestNotDeRegisteredService-D");
	if (expected) {
		assertThat(service).as("service was not registered").isNotNull();
	}
	else {
		assertThat(service).as("service was registered").isNull();
	}
}
 
Example 6
Source File: ConsulAutoServiceRegistrationNonWebTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	assertThat(this.autoServiceRegistration)
			.as("ConsulAutoServiceRegistration was created").isNotNull();

	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("consulNonWebTest");
	assertThat(service).as("service was registered").isNull(); // no port to listen,
																// hence no
	// registration
}
 
Example 7
Source File: ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	final Response<Map<String, Service>> response = this.consul.getAgentServices();
	final Map<String, Service> services = response.getValue();

	final Service service = services.get("myTestService1-GG");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-GG");
	assertThat(service.getService()).as("service name was wrong")
			.isEqualTo("myprefix-myTestService-GG");
	assertThat(StringUtils.isEmpty(service.getAddress()))
			.as("service address must not be empty").isFalse();
	assertThat(service.getAddress())
			.as("service address must equals hostname from discovery properties")
			.isEqualTo(this.discoveryProperties.getHostname());

	final Service managementService = services.get("myTestService1-GG-management");
	assertThat(managementService).as("management service was null").isNotNull();
	assertThat(managementService.getPort().intValue())
			.as("management service port is not 4452").isEqualTo(4452);
	assertThat(this.managementServerProperties.getPort().intValue())
			.as("management port is not 0").isEqualTo(0);
	assertThat(managementService.getId()).as("management service id was wrong")
			.isEqualTo("myTestService1-GG-management");
	assertThat(managementService.getService()).as("management service name was wrong")
			.isEqualTo("myprefix-myTestService-GG-management");
	assertThat(StringUtils.isEmpty(managementService.getAddress()))
			.as("management service address must not be empty").isFalse();
	assertThat(managementService.getAddress()).as(
			"management service address must equals hostname from discovery properties")
			.isEqualTo(this.discoveryProperties.getHostname());
}
 
Example 8
Source File: ConsulAutoServiceRegistrationDefaultPortTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService2-DD");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
}
 
Example 9
Source File: ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-WithZone");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-WithZone");
	assertThat(service.getMeta()).as("service zone was wrong").containsEntry("myZone",
			"zone1");
}
 
Example 10
Source File: ConsulAutoServiceRegistrationCustomizedServletContextTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-WithServletContext");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-WithServletContext");
	assertThat(service.getTags()).as("contextPath tag missing")
			.contains("contextPath=/customContext");
}
 
Example 11
Source File: NotifyListenerConsulWrapper.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public List<URL> getProviderUrls(String serviceName) {
    List<URL> urls = new ArrayList<>();
    Response<List<HealthService>> healthServices = consulClient.getHealthServices(serviceName, true, null);
    for (HealthService healthService : healthServices.getValue()) {
        urls.add(URL.valueOf(healthService.getService().getAddress()));
    }
    return urls;
}
 
Example 12
Source File: ConsulRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void doNotify(URL url, Collection<NotifyListener> listeners) {
	List<URL> result = new ArrayList<URL>();
	String consumerService = url.getServiceInterface();
	try {
		Response<List<HealthService>> response = this.consulClient.getHealthServices(consumerService, true, QueryParams.DEFAULT);
		List<HealthService> healthServices = (List<HealthService>) response.getValue();
		Iterator<HealthService> iterator = healthServices.iterator();
		while (iterator.hasNext()) {
			HealthService healthService = (HealthService) iterator.next();
			HealthService.Service service = healthService.getService();
			List<URL> urls = new ArrayList<URL>();
			String serviceURL = URL.decode(service.getAddress());
			URL u = URL.valueOf(serviceURL);
			if (UrlUtils.isMatch(url, u)) {
				urls.add(u);
			}
			result.addAll(urls);
			if (logger.isInfoEnabled()) {
				logger.info("Consul notify:  = " + urls);
			}
		}
		if (result == null || result.size() == 0) {
			return;
		}
		for (NotifyListener listener : listeners) {
			notify(url, listener, result);
		}
	} catch (OperationException e) {
		throw e;
	}
}
 
Example 13
Source File: ConsulAutoServiceRegistrationManagementServiceTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	final Response<Map<String, Service>> response = this.consul.getAgentServices();
	final Map<String, Service> services = response.getValue();

	final Service service = services.get("myTestService-EE-0");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService-EE-0");
	assertThat(service.getService()).as("service name was wrong")
			.isEqualTo("myTestService-EE");
	assertThat(StringUtils.isEmpty(service.getAddress()))
			.as("service address must not be empty").isFalse();
	assertThat(service.getAddress())
			.as("service address must equals hostname from discovery properties")
			.isEqualTo(this.discoveryProperties.getHostname());

	final Service managementService = services.get("myTestService-EE-0-management");
	assertThat(managementService).as("management service was null").isNotNull();
	assertThat(managementService.getPort().intValue())
			.as("management service port was wrong").isEqualTo(4452);
	assertThat(managementService.getId()).as("management service id was wrong")
			.isEqualTo("myTestService-EE-0-management");
	assertThat(managementService.getService()).as("management service name was wrong")
			.isEqualTo("myTestService-EE-management");
	assertThat(StringUtils.isEmpty(managementService.getAddress()))
			.as("management service address must not be empty").isFalse();
	assertThat(managementService.getAddress()).as(
			"management service address must equals hostname from discovery properties")
			.isEqualTo(this.discoveryProperties.getHostname());
}
 
Example 14
Source File: ConsulAutoServiceRegistrationCustomizedPropsTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void propertiesAreCorrect() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-B");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort()).as("service port is discovery port")
			.isEqualTo(4452);
	assertThat("myTestService1-B").as("service id was wrong")
			.isEqualTo(service.getId());
	assertThat("myTestService-B").as("service name was wrong")
			.isEqualTo(service.getService());
	assertThat("myhost").as("property hostname was wrong")
			.isEqualTo(this.properties.getHostname());
	assertThat("10.0.0.1").as("property ipAddress was wrong")
			.isEqualTo(this.properties.getIpAddress());
	assertThat("myhost").as("service address was wrong")
			.isEqualTo(service.getAddress());
	assertThat(service.getEnableTagOverride())
			.as("property enableTagOverride was wrong").isTrue();
	assertThat(service.getTags()).as("property tags contains the wrong values")
			.containsExactly("mytag");
	HashMap<String, String> entries = new HashMap<>();
	entries.put("key1", "value1");
	entries.put("key2", "value2");
	entries.put("mydefaultzonemetadataname", "myzone");
	entries.put("group", "mygroup");
	entries.put("secure", "false");
	assertThat(service.getMeta()).as("property metadata contains the wrong entries")
			.containsExactlyInAnyOrderEntriesOf(entries);

	Response<List<Check>> checkResponse = this.consul.getHealthChecksForService(
			"myTestService-B", HealthChecksForServiceRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	List<Check> checks = checkResponse.getValue();
	assertThat(checks).as("checks was wrong size").hasSize(0);
}
 
Example 15
Source File: ConsulAutoServiceRegistrationCustomizedAgentAddressTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Response<Map<String, Service>> response = this.consul.getAgentServices();
	Map<String, Service> services = response.getValue();
	Service service = services.get("myTestService1-AA");
	assertThat(service).as("service was null").isNotNull();
	assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0);
	assertThat(service.getId()).as("service id was wrong")
			.isEqualTo("myTestService1-AA");
	assertThat(service.getService()).as("service name was wrong")
			.isEqualTo("myprefix-myTestService-AA");
	assertThat(StringUtils.isEmpty(service.getAddress()))
			.as("service address must be empty").isTrue();
}
 
Example 16
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public List<ServiceInstance> convert(Response<List<HealthService>> consulServices) {
    if (consulServices == null || consulServices.getValue() == null || consulServices.getValue().isEmpty()) {
        return new ArrayList<ServiceInstance>();
    } else {
        List<ServiceInstance> serviceInstances = new ArrayList<ServiceInstance>();
        for (HealthService consulService : consulServices.getValue()) {
            ServiceInstance serviceInstance = new ServiceInstance();
            serviceInstance.setIp(consulService.getService().getAddress());
            serviceInstance.setPort(consulService.getService().getPort());
            serviceInstance.setServiceName(consulService.getService().getService());
            serviceInstances.add(serviceInstance);
        }
        return serviceInstances;
    }
}
 
Example 17
Source File: HiveDriverConsul.java    From garmadon with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches healthy service nodes
 */
private List<HealthService> getHealthyEndPoints(String serviceName) {
    ConsulClient client = new ConsulClient("localhost");

    HealthServicesRequest request = HealthServicesRequest.newBuilder()
        .setPassing(true)
        .setQueryParams(QueryParams.DEFAULT)
        .build();
    Response<List<HealthService>> healthyServices = client.getHealthServices(serviceName, request);

    return healthyServices.getValue();
}
 
Example 18
Source File: ConsulPropertySource.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
public void init() {
    if (!this.context.endsWith("/")) {
        this.context = this.context + "/";
    }

    if (configProperties.isTokenEnabled() && StringUtils.isEmpty(bmsAuthClient.getToken())) {
        bmsAuthClient.getTokenFromServer(configProperties.getAuthUri());
    }

    logger.info("Try to get KV from consul for context: " + this.context);
    Response<List<GetValue>> response = this.source.getKVValues(this.context,
            this.bmsAuthClient.getToken(), new QueryParams(ConsistencyMode.STALE));

    this.initialIndex = response.getConsulIndex();

    final List<GetValue> values = response.getValue();
    Format format = this.configProperties.getFormat();
    switch (format) {
        case KEY_VALUE:
            parsePropertiesInKeyValueFormat(values);
            logger.info("Properties for context " + this.context + "is ");
            for (Map.Entry<String, Object> entry : this.properties.entrySet()) {
                logger.info(entry.getKey() + ": " + entry.getValue().toString());
            }
            break;
        case PROPERTIES:
            break;
        case YAML:
            parsePropertiesWithNonKeyValueFormat(values, format);
            break;
        default:
            break;
    }
}
 
Example 19
Source File: EventService.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
protected List<Event> readEvents(Response<List<Event>> response) {
	setLastIndex(response);
	return response.getValue();
}
 
Example 20
Source File: ConfigWatch.java    From spring-cloud-formula with Apache License 2.0 4 votes vote down vote up
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues(String context) {
    if (this.running.get()) {
        if (this.properties.getFormat() != Format.FILES && !context.endsWith("/")) {
            context = context + "/";
        }

        try {
            Long currentIndex = this.consulIndexes.get(context);
            if (currentIndex == null) {
                currentIndex = -1L;
            }

            logger.debug("watching consul for context '" + context + "' with index " + currentIndex);

            if (properties.isTokenEnabled() && StringUtils.isEmpty(bmsAuthClient.getToken())) {
                bmsAuthClient.getTokenFromServer(properties.getAuthUri());
            }

            QueryParams queryParams = QueryParams.Builder.builder()
                    .setConsistencyMode(ConsistencyMode.STALE)
                    .setIndex(currentIndex)
                    .setWaitTime(this.properties.getWatch().getWaitTime())
                    .build();
            Response<List<GetValue>> response = this.consul.getKVValues(context, bmsAuthClient.getToken(),
                    queryParams);

            // if response.value == null, response was a 404, otherwise it was a 200
            // reducing churn if there wasn't anything
            if (response.getValue() != null && !response.getValue().isEmpty()) {
                Long newIndex = response.getConsulIndex();

                if (newIndex != null && !newIndex.equals(currentIndex)) {
                    // don't publish the same index again, don't publish the first
                    // time (-1) so index can be primed
                    if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
                        logger.trace("Context " + context + " has new index " + newIndex);
                        RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
                        this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
                    } else if (logger.isTraceEnabled()) {
                        logger.trace("Event for index already published for context " + context);
                    }
                    this.consulIndexes.put(context, newIndex);
                } else if (logger.isTraceEnabled()) {
                    logger.trace("Same index for context " + context);
                }
            } else if (logger.isTraceEnabled()) {
                logger.trace("No value for context " + context);
            }

        } catch (Exception e) {
            // OperationException(statusCode=403, statusMessage='Forbidden', statusContent='ACL not found')
            if (e instanceof OperationException && ((OperationException) e).getStatusCode() == 403) {
                logger.info("Token has expired, try to get new token from server.");
                String newToken = bmsAuthClient.getTokenFromServer(this.properties.getAuthUri());
                logger.info("New Token is: " + newToken);
            }
            // only fail fast on the initial query, otherwise just log the error
            if (this.firstTime && this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from consul.");
                ReflectionUtils.rethrowRuntimeException(e);
            } else if (logger.isTraceEnabled()) {
                logger.trace("Error querying consul Key/Values for context '"
                        + context + "'", e);
            } else if (logger.isWarnEnabled()) {
                // simplified one line log message in the event of an agent failure
                logger.warn("Error querying consul Key/Values for context '"
                        + context + "'. Message: " + e.getMessage());
            }
        }
    }
    this.firstTime = false;
}