org.zodiac.monitor.console.model.Endpoints Maven / Gradle / Ivy
package org.zodiac.monitor.console.model;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.actuate.endpoint.web.Link;
import org.springframework.lang.Nullable;
import org.zodiac.sdk.toolkit.collection.UnmodifiableIterator;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
/**
* @author zodiac
*/
public class Endpoints implements Iterable, Serializable {
private static final long serialVersionUID = 1967026657960719764L;
private static final Endpoints EMPTY = new Endpoints(Collections.emptyList());
private final Map endpoints;
private Endpoints(Collection endpoints) {
if (endpoints.isEmpty()) {
this.endpoints = Collections.emptyMap();
} else {
this.endpoints = endpoints.stream().collect(Collectors.toMap(Endpoint::getId, Function.identity()));
}
}
public Endpoints(Map links) {
if (links.isEmpty()) {
this.endpoints = Collections.emptyMap();
} else {
this.endpoints = CollUtil.map();
links.forEach((k, v) -> {
Endpoint endpoint = new Endpoint(k, v.getHref());
this.endpoints.put(k, endpoint);
});
}
}
public Optional get(String id) {
return Optional.ofNullable(this.endpoints.get(id));
}
public boolean isPresent(String id) {
return this.endpoints.containsKey(id);
}
@Override
public Iterator iterator() {
return new UnmodifiableIterator<>(this.endpoints.values().iterator());
}
public static Endpoints empty() {
return EMPTY;
}
public static Endpoints single(String id, String url) {
return new Endpoints(Collections.singletonList(Endpoint.of(id, url)));
}
public static Endpoints of(@Nullable Collection endpoints) {
if (endpoints == null || endpoints.isEmpty()) {
return empty();
}
return new Endpoints(endpoints);
}
public Endpoints withEndpoint(String id, String url) {
Endpoint endpoint = Endpoint.of(id, url);
Map newEndpoints = CollUtil.map(this.endpoints);
newEndpoints.put(endpoint.getId(), endpoint);
return new Endpoints(newEndpoints.values());
}
public Stream stream() {
return this.endpoints.values().stream();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((endpoints == null) ? 0 : endpoints.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Endpoints other = (Endpoints)obj;
if (endpoints == null) {
if (other.endpoints != null)
return false;
} else if (!endpoints.equals(other.endpoints))
return false;
return true;
}
@Override
public String toString() {
return "Endpoints [endpoints=" + endpoints + "]";
}
}