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

org.cryptomator.frontend.webdav.WebDavServerManager Maven / Gradle / Ivy

There is a newer version: 2.0.7
Show newest version
package org.cryptomator.frontend.webdav;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

public class WebDavServerManager {

	private static final ConcurrentMap RUNNING_SERVERS = new ConcurrentHashMap<>();

	private WebDavServerManager() {
	}

	public static WebDavServerHandle getOrCreateServer(int port) throws ServerLifecycleException {
		return RUNNING_SERVERS.compute(port, (p, handle) -> {
			if (handle == null || handle.counter.getAndIncrement() == 0) {
				// if counter was 0 -> a concurrent thread is about to terminate it.
				var server = tryCreate(p);
				return new ReferenceCountingHandle(port, server, new AtomicInteger(1));
			} else {
				// handle exists. we increased the counter already.
				return handle;
			}
		});
	}

	private static WebDavServer tryCreate(int port) throws ServerLifecycleException {
		var bindAddr = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
		var server = WebDavServerFactory.createWebDavServer(bindAddr);
		server.start();
		return server;
	}

	private record ReferenceCountingHandle(int port, WebDavServer server, AtomicInteger counter) implements WebDavServerHandle {

		@Override
		public void close() throws IOException {
			if (counter.decrementAndGet() == 0) {
				RUNNING_SERVERS.remove(port, this);
				try {
					server.terminate();
				} catch (ServerLifecycleException e) {
					throw new IOException(e);
				}
			}
		}

	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy