org.springframework.cloud.endpoint.event.RefreshEvent Java Examples

The following examples show how to use org.springframework.cloud.endpoint.event.RefreshEvent. 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: ConfigWatchTests.java    From spring-cloud-consul 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(eq(context), anyString(), any(QueryParams.class)))
			.thenReturn(response);

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

	watch.watchConfigKeyValues();
	verify(eventPublisher, times(0)).publishEvent(any(RefreshEvent.class));
}
 
Example #2
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 #3
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void watchWithExceptionAndWarnLog() {
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.WARN);
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    setupWatch(eventPublisher, "/app/", null);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #4
Source File: ConfigWatchTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void watchForFileFormatPublishesEvent() {
	ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

	this.configProperties.setFormat(FILES);
	setupWatch(eventPublisher, new GetValue(), "/config/app.yml");

	verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
 
Example #5
Source File: ConfigWatchTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void watchWithNullValueDoesNotPublishEvent() {
	ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

	setupWatch(eventPublisher, null, "/app/");

	verify(eventPublisher, never()).publishEvent(any(RefreshEvent.class));
}
 
Example #6
Source File: ConfigWatchTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void watchPublishesEvent() {
	ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

	setupWatch(eventPublisher, new GetValue(), "/app/");

	verify(eventPublisher, times(1)).publishEvent(any(RefreshEvent.class));
}
 
Example #7
Source File: ConfigWatchTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Test
public void watchPublishesEventWithAcl() {
	ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

	setupWatch(eventPublisher, new GetValue(), "/app/",
			"2ee647bd-bd69-4118-9f34-b9a6e9e60746");

	verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}
 
Example #8
Source File: ConfigWatcher.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event)
		throws Exception {
	TreeCacheEvent.Type eventType = event.getType();
	if (eventType == NODE_ADDED || eventType == NODE_REMOVED
			|| eventType == NODE_UPDATED) {
		this.publisher
				.publishEvent(new RefreshEvent(this, event, getEventDesc(event)));
	}
}
 
Example #9
Source File: NacosContextRefresher.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void registerNacosListener(final String groupKey, final String dataKey) {
	String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
	Listener listener = listenerMap.computeIfAbsent(key,
			lst -> new AbstractSharedListener() {
				@Override
				public void innerReceive(String dataId, String group,
						String configInfo) {
					refreshCountIncrement();
					nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
					// todo feature: support single refresh for listening
					applicationContext.publishEvent(
							new RefreshEvent(this, null, "Refresh Nacos config"));
					if (log.isDebugEnabled()) {
						log.debug(String.format(
								"Refresh Nacos config group=%s,dataId=%s,configInfo=%s",
								group, dataId, configInfo));
					}
				}
			});
	try {
		configService.addListener(dataKey, groupKey, listener);
	}
	catch (NacosException e) {
		log.warn(String.format(
				"register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey,
				groupKey), e);
	}
}
 
Example #10
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void watchWithExceptionAndFailFast() {
    this.configProperties.setFailFast(true);
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    setupWatch(eventPublisher, "/app/", null);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #11
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void watchWithOperationException() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    setupWatchThrowException(eventPublisher, "/app/");

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #12
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void watchPublishesEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    setupWatch(eventPublisher, "/app/");

    verify(eventPublisher, times(1)).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #13
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;
}
 
Example #14
Source File: ConfigWatch.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues() {
	if (this.running.get()) {
		for (String context : this.consulIndexes.keySet()) {

			// turn the context into a Consul folder path (unless our config format
			// are FILES)
			if (this.properties.getFormat() != FILES && !context.endsWith("/")) {
				context = context + "/";
			}

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

				log.trace("watching consul for context '" + context + "' with index "
						+ currentIndex);

				// use the consul ACL token if found
				String aclToken = this.properties.getAclToken();
				if (StringUtils.isEmpty(aclToken)) {
					aclToken = null;
				}

				Response<List<GetValue>> response = this.consul.getKVValues(context,
						aclToken,
						new QueryParams(this.properties.getWatch().getWaitTime(),
								currentIndex));

				// 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)) {
							log.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 (log.isTraceEnabled()) {
							log.trace("Event for index already published for context "
									+ context);
						}
						this.consulIndexes.put(context, newIndex);
					}
					else if (log.isTraceEnabled()) {
						log.trace("Same index for context " + context);
					}
				}
				else if (log.isTraceEnabled()) {
					log.trace("No value for context " + context);
				}

			}
			catch (Exception e) {
				// only fail fast on the initial query, otherwise just log the error
				if (this.firstTime && this.properties.isFailFast()) {
					log.error(
							"Fail fast is set and there was an error reading configuration from consul.");
					ReflectionUtils.rethrowRuntimeException(e);
				}
				else if (log.isTraceEnabled()) {
					log.trace("Error querying consul Key/Values for context '"
							+ context + "'", e);
				}
				else if (log.isWarnEnabled()) {
					// simplified one line log message in the event of an agent
					// failure
					log.warn("Error querying consul Key/Values for context '"
							+ context + "'. Message: " + e.getMessage());
				}
			}
		}
	}
	this.firstTime = false;
}
 
Example #15
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 3 votes vote down vote up
@Test
public void watchWithNullResponse() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    Response<List<GetValue>> response = null;

    setupWatch(eventPublisher, "/app/", response);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #16
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 3 votes vote down vote up
@Test
public void watchWithIllegalIndexDoesNotPublishEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    Response<List<GetValue>> response = new Response<>(Arrays.asList(new GetValue()), 0l, false, 1L);

    setupWatchWithIllegalIndex(eventPublisher, "/app/", response);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #17
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 3 votes vote down vote up
@Test
public void watchWithNullIndexDoesNotPublishEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    Response<List<GetValue>> response = new Response<>(Arrays.asList(new GetValue()), null, false, 1L);

    setupWatch(eventPublisher, "/app/", response);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #18
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 3 votes vote down vote up
@Test
public void watchForFileFormatPublishesEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    this.configProperties.setFormat(FILES);

    setupWatch(eventPublisher, "/config/app.yml");

    verify(eventPublisher, times(1)).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}
 
Example #19
Source File: ConfigWatchTests.java    From spring-cloud-formula with Apache License 2.0 3 votes vote down vote up
@Test
public void watchWithNullValueDoesNotPublishEvent() {
    ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

    Response<List<GetValue>> response = new Response<>(null, 1l, false, 1L);

    setupWatch(eventPublisher, "/app/", response);

    verify(eventPublisher, never()).publishEvent(ArgumentMatchers.any(RefreshEvent.class));
}