io.radanalytics.operator.common.CustomResourceWatcher Maven / Gradle / Ivy
package io.radanalytics.operator.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.radanalytics.operator.common.crd.InfoClass;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static io.radanalytics.operator.common.OperatorConfig.ALL_NAMESPACES;
public class CustomResourceWatcher extends AbstractWatcher {
// use via builder
private CustomResourceWatcher(String namespace,
String entityName,
KubernetesClient client,
CustomResourceDefinition crd,
BiConsumer onAdd,
BiConsumer onDelete,
BiConsumer onModify,
Function convert) {
super(true, namespace, entityName, client, crd, null, onAdd, onDelete, onModify, null, null, convert);
}
public static class Builder {
private String namespace = ALL_NAMESPACES;
private String entityName;
private KubernetesClient client;
private CustomResourceDefinition crd;
private BiConsumer onAdd;
private BiConsumer onDelete;
private BiConsumer onModify;
private Function convert;
public Builder withNamespace(String namespace) {
this.namespace = namespace;
return this;
}
public Builder withEntityName(String entityName) {
this.entityName = entityName;
return this;
}
public Builder withClient(KubernetesClient client) {
this.client = client;
return this;
}
public Builder withCrd(CustomResourceDefinition crd) {
this.crd = crd;
return this;
}
public Builder withOnAdd(BiConsumer onAdd) {
this.onAdd = onAdd;
return this;
}
public Builder withOnDelete(BiConsumer onDelete) {
this.onDelete = onDelete;
return this;
}
public Builder withOnModify(BiConsumer onModify) {
this.onModify = onModify;
return this;
}
public Builder withConvert(Function convert) {
this.convert = convert;
return this;
}
public CustomResourceWatcher build() {
return new CustomResourceWatcher(namespace, entityName, client, crd, onAdd, onDelete, onModify, convert);
}
}
public static T defaultConvert(Class clazz, InfoClass info) {
String name = info.getMetadata().getName();
String namespace = info.getMetadata().getNamespace();
ObjectMapper mapper = new ObjectMapper();
T infoSpec = mapper.convertValue(info.getSpec(), clazz);
if (infoSpec == null) { // empty spec
try {
infoSpec = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (infoSpec.getName() == null) {
infoSpec.setName(name);
}
if (infoSpec.getNamespace() == null) {
infoSpec.setNamespace(namespace);
}
return infoSpec;
}
@Override
public CompletableFuture> watch() {
return createCustomResourceWatch().thenApply(watch -> this);
}
}