io.improbable.keanu.vertices.VertexLabel Maven / Gradle / Ivy
package io.improbable.keanu.vertices;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class VertexLabel {
private static final char NAMESPACE_SEPARATOR = '.';
private final List namespace;
private final String name;
public VertexLabel(String name) {
this.namespace = Collections.emptyList();
this.name = name;
}
public VertexLabel(String outer, String... inner) {
this.namespace = ImmutableList.builder()
.add(outer)
.add(Arrays.copyOf(inner, inner.length - 1))
.build();
this.name = inner[inner.length - 1];
}
public VertexLabel(List namespace, String name) {
this.namespace = ImmutableList.copyOf(namespace);
this.name = name;
}
public boolean isInNamespace(String... namespace) {
if (namespace.length > this.namespace.size()) {
return false;
}
for (int i = 0; i < namespace.length; i++) {
if (!this.namespace.get(i).equals(namespace[i])) {
return false;
}
}
return true;
}
public VertexLabel withExtraNamespace(String topLevelNamespace) {
List newNamespace = ImmutableList.builder().add(topLevelNamespace).addAll(namespace).build();
return new VertexLabel(newNamespace, this.name);
}
public VertexLabel withoutOuterNamespace() {
List reducedNamespace = namespace.subList(1, namespace.size());
return new VertexLabel(reducedNamespace, this.name);
}
public Optional getOuterNamespace() {
return namespace.stream().findFirst();
}
public String getUnqualifiedName() {
return name;
}
public String getQualifiedName() {
ImmutableList names = ImmutableList.builder().addAll(namespace).add(name).build();
return Joiner.on(NAMESPACE_SEPARATOR).join(names);
}
@Override
public String toString() {
return getQualifiedName();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VertexLabel that = (VertexLabel) o;
return Objects.equals(name, that.name) &&
Objects.equals(namespace, that.namespace);
}
@Override
public int hashCode() {
return Objects.hash(namespace, name);
}
public static VertexLabel parseLabel(String label) {
List namespaces = Arrays.asList(label.split("\\."));
if (namespaces.size() == 0) {
return new VertexLabel(label);
}
if (namespaces.size() == 1) {
return new VertexLabel(namespaces.get(0));
}
return new VertexLabel(namespaces.subList(0, namespaces.size() - 1), namespaces.get(namespaces.size() - 1));
}
}