All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.codearte.accurest.stubrunner.spring.cloud.StubRunnerDiscoveryClient Maven / Gradle / Ivy

There is a newer version: 1.1.1
Show newest version
package io.codearte.accurest.stubrunner.spring.cloud;

import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.List;

import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.noop.NoopDiscoveryClient;

import io.codearte.accurest.stubrunner.RunningStubs;
import io.codearte.accurest.stubrunner.StubFinder;
import io.codearte.accurest.stubrunner.util.StringUtils;

/**
 * Custom version of {@link DiscoveryClient} that tries to find an instance
 * in one of the started WireMock servers
 *
 * @author Marcin Grzejszczak
 */
public class StubRunnerDiscoveryClient implements DiscoveryClient {

	private final DiscoveryClient delegate;
	private final StubFinder stubFinder;
	private final StubMapperProperties stubMapperProperties;

	public StubRunnerDiscoveryClient(DiscoveryClient delegate, StubFinder stubFinder,
			StubMapperProperties stubMapperProperties, String springAppName) {
		this.delegate = delegate instanceof  StubRunnerDiscoveryClient ?
				noOpDiscoveryClient(springAppName) : delegate;
		this.stubFinder = stubFinder;
		this.stubMapperProperties = stubMapperProperties;
	}

	private NoopDiscoveryClient noOpDiscoveryClient(String springAppName) {
		return new NoopDiscoveryClient(new DefaultServiceInstance(springAppName, "localhost", 0, false));
	}

	@Override
	public String description() {
		return delegate.description();
	}

	@Override
	public ServiceInstance getLocalServiceInstance() {
		return delegate.getLocalServiceInstance();
	}

	@Override
	public List getInstances(String serviceId) {
		String ivyNotation = stubMapperProperties.fromServiceIdToIvyNotation(serviceId);
		String serviceToFind = StringUtils.hasText(ivyNotation) ? ivyNotation : serviceId;
		URL stubUrl = stubFinder.findStubUrl(serviceToFind);
		if (stubUrl == null) {
			return delegate.getInstances(serviceId);
		}
		return Collections.singletonList(
				new StubRunnerServiceInstance(serviceId, stubUrl.getHost(), stubUrl.getPort(), toUri(stubUrl))
		);
	}

	private URI toUri(URL url) {
		try {
			return url.toURI();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List getServices() {
		List services = delegate.getServices();
		RunningStubs runningStubs = stubFinder.findAllRunningStubs();
		services.addAll(runningStubs.getAllServicesNames());
		return services;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy