com.ecwid.consul.v1.QueryParams Java Examples

The following examples show how to use com.ecwid.consul.v1.QueryParams. 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: SessionConsulClient.java    From consul-api with Apache License 2.0 6 votes vote down vote up
@Override
public Response<Session> renewSession(String session, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/session/renew/" + session, "", queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		List<Session> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Session>>() {
		}.getType());

		if (value.size() == 1) {
			return new Response<Session>(value.get(0), httpResponse);
		} else {
			throw new ConsulException("Strange response (list size=" + value.size() + ")");
		}
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #2
Source File: TtlScheduler.java    From saluki with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    Set<String> sessionIds = Sets.newHashSet();
    for (ConsulSession session : sessions) {
        try {
            String sessionId = session.getSessionId();
            if (!sessionIds.contains(sessionId)) {
                client.renewSession(sessionId, QueryParams.DEFAULT);
                sessionIds.add(sessionId);
            }
            log.debug("Sending consul heartbeat for: " + sessionId);
        } catch (Throwable e) {
            failedsessions.addAll(sessions);
            sessions.clear();
            log.error(e.getMessage(), e);
        }
    }
}
 
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: ConsulEndpoint.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@ReadOperation
public ConsulData invoke() {
	ConsulData data = new ConsulData();
	// data.setKeyValues(kvClient.getKeyValueRecurse());
	Response<Map<String, Service>> agentServices = this.consul.getAgentServices();
	data.setAgentServices(agentServices.getValue());

	Response<Map<String, List<String>>> catalogServices = this.consul
			.getCatalogServices(CatalogServicesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());

	for (String serviceId : catalogServices.getValue().keySet()) {
		Response<List<CatalogService>> response = this.consul
				.getCatalogService(serviceId, CatalogServiceRequest.newBuilder()
						.setQueryParams(QueryParams.DEFAULT).build());
		data.getCatalogServices().put(serviceId, response.getValue());
	}

	Response<List<Node>> catalogNodes = this.consul
			.getCatalogNodes(CatalogNodesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	data.setCatalogNodes(catalogNodes.getValue());

	return data;
}
 
Example #5
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void firstCallDoesNotPublishEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
    this.configProperties.setFormat(FILES);

    GetValue getValue = new GetValue();
    String context = "/config/app.yml";
    ConsulClient consul = mock(ConsulClient.class);
    List<GetValue> getValues = Collections.singletonList(getValue);

    Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
    when(consul.getKVValues(ArgumentMatchers.eq(context), ArgumentMatchers.anyString(),
            ArgumentMatchers.any(QueryParams.class)))
            .thenReturn(response);

    ConfigWatch watch = new ConfigWatch(this.configProperties, consul, bmsAuthClient,
            new LinkedHashMap<String, Long>());
    watch.setApplicationEventPublisher(eventPublisher);

    watch.watchConfigKeyValues(context);
    verify(eventPublisher, times(0)).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #6
Source File: ConsulServiceRegistry.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
@Override
public Object getStatus(ConsulRegistration registration) {
	String serviceId = registration.getServiceId();
	Response<List<Check>> response = this.client.getHealthChecksForService(serviceId,
			HealthChecksForServiceRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	List<Check> checks = response.getValue();

	for (Check check : checks) {
		if (check.getServiceId().equals(registration.getInstanceId())) {
			if (check.getName().equalsIgnoreCase("Service Maintenance Mode")) {
				return OUT_OF_SERVICE.getCode();
			}
		}
	}

	return UP.getCode();
}
 
Example #7
Source File: ConsulDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
		QueryParams queryParams) {

	HealthServicesRequest request = HealthServicesRequest.newBuilder()
			.setTag(this.properties.getDefaultQueryTag())
			.setPassing(this.properties.isQueryPassing()).setQueryParams(queryParams)
			.setToken(this.properties.getAclToken()).build();
	Response<List<HealthService>> services = this.client.getHealthServices(serviceId,
			request);

	for (HealthService service : services.getValue()) {
		String host = findHost(service);

		Map<String, String> metadata = service.getService().getMeta();
		if (metadata == null) {
			metadata = new LinkedHashMap<>();
		}
		boolean secure = false;
		if (metadata.containsKey("secure")) {
			secure = Boolean.parseBoolean(metadata.get("secure"));
		}
		instances.add(new DefaultServiceInstance(service.getService().getId(),
				serviceId, host, service.getService().getPort(), secure, metadata));
	}
}
 
Example #8
Source File: ConsulSendingHandler.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleMessageInternal(Message<?> message) {
	if (this.logger.isTraceEnabled()) {
		this.logger.trace("Publishing message" + message);
	}

	Object payload = message.getPayload();
	// TODO: support headers
	// TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter
	Response<Event> event = this.consul.eventFire(this.eventName, (String) payload,
			new EventParams(), QueryParams.DEFAULT);
	// TODO: return event?
	// return null;
}
 
Example #9
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public Response<List<HealthService>> lookupHealthService(String serviceName, long lastConsulIndex) {
    QueryParams queryParams = new QueryParams(
            ConsulConstants.CONSUL_BLOCK_TIME_SECONDS, lastConsulIndex);
    HealthServicesRequest request = HealthServicesRequest.newBuilder()
            .setTag(ConsulConstants.CONSUL_SERVICE_TAG)
            .setQueryParams(queryParams)
            .setPassing(true)
            .build();
    return client.getHealthServices(serviceName, request);
}
 
Example #10
Source File: EventConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Event>> eventList(String event, QueryParams queryParams) {
	EventListRequest request = EventListRequest.newBuilder()
			.setName(event)
			.setQueryParams(queryParams)
			.build();

	return eventList(request);
}
 
Example #11
Source File: CoordinateConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Node>> getNodes(QueryParams queryParams) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/coordinate/nodes", queryParams);

	if (httpResponse.getStatusCode() == 200) {
		List<Node> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Node>>() {
		}.getType());
		return new Response<List<Node>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #12
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void setupWatchWithIllegalIndex(ApplicationEventPublisher eventPublisher, String context,
                                        Response<List<GetValue>> response) {
    ConsulClient consul = mock(ConsulClient.class);

    when(consul.getKVValues(ArgumentMatchers.eq(context), nullable(String.class),
            ArgumentMatchers.any(QueryParams.class))).thenReturn(response);

    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put(context, -1L);
    startWatch(eventPublisher, consul, initialIndexes);
}
 
Example #13
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void setupWatchThrowException(ApplicationEventPublisher eventPublisher, String context) {
    ConsulClient consul = mock(ConsulClient.class);
    OperationException operationException = new OperationException(403, null, null);
    when(consul.getKVValues(ArgumentMatchers.eq(context), nullable(String.class),
            ArgumentMatchers.any(QueryParams.class))).thenThrow(operationException);

    LinkedHashMap<String, Long> initialIndexes = new LinkedHashMap<>();
    initialIndexes.put(context, 0L);
    startWatch(eventPublisher, consul, initialIndexes);
}
 
Example #14
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 #15
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<String> sessionCreate(NewSession newSession, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;

	String json = GsonFactory.getGson().toJson(newSession);
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/session/create", json, queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		Map<String, String> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<Map<String, String>>() {
		}.getType());
		return new Response<String>(value.get("ID"), httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #16
Source File: TxleConsulClient.java    From txle with Apache License 2.0 5 votes vote down vote up
public void destroyCurrentSession() {
    try {
        Response<Session> session = consulClient.getSessionInfo(consulSessionId, QueryParams.DEFAULT);
        if (session != null) {
            consulClient.sessionDestroy(session.getValue().getId(), QueryParams.DEFAULT);
        }
    } catch (Exception e) {
        log.error("Failed to destroy current session from Consul.", e);
    }
}
 
Example #17
Source File: ConsulReactiveDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<String> getServices() {
	return Flux.defer(() -> {
		CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
				.setToken(properties.getAclToken())
				.setQueryParams(QueryParams.DEFAULT).build();
		Response<Map<String, List<String>>> services = client
				.getCatalogServices(request);
		return services == null ? Flux.empty()
				: Flux.fromIterable(services.getValue().keySet());
	}).onErrorResume(exception -> {
		logger.error("Error getting services from Consul.", exception);
		return Flux.empty();
	}).subscribeOn(Schedulers.boundedElastic());
}
 
Example #18
Source File: ConsulHealthIndicator.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	final Response<String> leaderStatus = this.consul.getStatusLeader();
	final Response<Map<String, List<String>>> services = this.consul
			.getCatalogServices(CatalogServicesRequest.newBuilder()
					.setQueryParams(QueryParams.DEFAULT).build());
	builder.up().withDetail("leader", leaderStatus.getValue()).withDetail("services",
			services.getValue());
}
 
Example #19
Source File: TtlSchedulerRemoveTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
private Check getCheckForService(String serviceId) {
	Response<List<Check>> checkResponse = this.consul
			.getHealthChecksForService(serviceId, HealthChecksForServiceRequest
					.newBuilder().setQueryParams(QueryParams.DEFAULT).build());
	if (checkResponse.getValue().size() > 0) {
		return checkResponse.getValue().get(0);
	}
	return null;
}
 
Example #20
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<Void> sessionDestroy(String session, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
	HttpResponse httpResponse = rawClient.makePutRequest("/v1/session/destroy/" + session, "", queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		return new Response<Void>(null, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #21
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 #22
Source File: ConsulDiscoveryClientTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void getInstancesForServiceRespectsQueryParams() {
	Response<List<String>> catalogDatacenters = this.consulClient
			.getCatalogDatacenters();

	List<String> dataCenterList = catalogDatacenters.getValue();
	assertThat(dataCenterList.isEmpty()).as("no data centers found").isFalse();
	List<ServiceInstance> instances = this.discoveryClient.getInstances(
			"testConsulDiscovery", new QueryParams(dataCenterList.get(0)));
	assertThat(instances.isEmpty()).as("instances was empty").isFalse();

	ServiceInstance instance = instances.get(0);
	assertIpAddress(instance);
}
 
Example #23
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Session>> getSessionNode(String node, QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/session/node/" + node, queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		List<Session> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Session>>() {
		}.getType());
		return new Response<List<Session>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #24
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Check>> getHealthChecksForNode(String nodeName, QueryParams queryParams) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/health/node/" + nodeName, queryParams);

	if (httpResponse.getStatusCode() == 200) {
		List<Check> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Check>>() {
		}.getType());
		return new Response<List<Check>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #25
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<Session>> getSessionList(QueryParams queryParams, String token) {
	UrlParameters tokenParam = token != null ? new SingleUrlParameters("token", token) : null;
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/session/list", queryParams, tokenParam);

	if (httpResponse.getStatusCode() == 200) {
		List<Session> value = GsonFactory.getGson().fromJson(httpResponse.getContent(), new TypeToken<List<Session>>() {
		}.getType());
		return new Response<List<Session>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example #26
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 4 votes vote down vote up
@Override
public Response<List<com.ecwid.consul.v1.health.model.HealthService>> getHealthServices(String serviceName, String tag, boolean onlyPassing, QueryParams queryParams) {
	return getHealthServices(serviceName, tag, onlyPassing, queryParams, null);
}
 
Example #27
Source File: CatalogServiceRequest.java    From consul-api with Apache License 2.0 4 votes vote down vote up
public QueryParams getQueryParams() {
	return queryParams;
}
 
Example #28
Source File: SessionConsulClient.java    From consul-api with Apache License 2.0 4 votes vote down vote up
@Override
public Response<String> sessionCreate(NewSession newSession, QueryParams queryParams) {
	return sessionCreate(newSession, queryParams, null);
}
 
Example #29
Source File: HealthConsulClient.java    From consul-api with Apache License 2.0 4 votes vote down vote up
@Override
public Response<List<com.ecwid.consul.v1.health.model.HealthService>> getHealthServices(String serviceName, boolean onlyPassing, QueryParams queryParams, String token) {
	return getHealthServices(serviceName, (String) null, onlyPassing, queryParams, token);
}
 
Example #30
Source File: CatalogServiceRequest.java    From consul-api with Apache License 2.0 4 votes vote down vote up
public Builder setQueryParams(QueryParams queryParams) {
	this.queryParams = queryParams;
	return this;
}