org.ehoffman.test.aspects.RequiresServerAvailabilityAdvice Maven / Gradle / Ivy
package org.ehoffman.test.aspects;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.ehoffman.resources.NetworkUtils;
import org.ehoffman.test.RequiresServerAvailable;
/**
* Used on a method marked with {@link RequiresServerAvailable}.
* Advice requires access to a set of servers (by {@link URL} that must return input streams).
* If the access fails a {@link SkipException} will be thrown.
*
* Your test will automatically become non-deterministic when you user remote resources.
* Non-deterministic tests kill kittens... one of these kittens
*
*
*
* @author rex
*/
public class RequiresServerAvailabilityAdvice implements MethodInterceptor {
private final Map isServerAvailable = new ConcurrentHashMap<>();
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final RequiresServerAvailable requiredServer = invocation.getMethod().getAnnotation(RequiresServerAvailable.class);
for (String serverUrl : requiredServer.serversUrls()) {
if (isServerAvailable.get(serverUrl) == null) {
try {
isServerAvailable.put(serverUrl, NetworkUtils.verifyAccess(new URL(serverUrl)));
} catch (final MalformedURLException e) {
isServerAvailable.put(serverUrl, false);
}
}
if (!isServerAvailable.get(serverUrl)) {
throw new SkipException(this);
}
}
return invocation.proceed();
}
}