Java源码示例:io.fabric8.kubernetes.api.model.apiextensions.JSONSchemaProps
示例1
public static JSONSchemaProps readSchema(Class infoClass) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
char[] chars = infoClass.getSimpleName().toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
String urlJson = "/schema/" + new String(chars) + ".json";
String urlJS = "/schema/" + new String(chars) + ".js";
URL in = infoClass.getResource(urlJson);
if (null == in) {
// try also if .js file exists
in = infoClass.getResource(urlJS);
}
if (null == in) {
return null;
}
try {
return mapper.readValue(in, JSONSchemaProps.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
示例2
/**
* Creates the JSON schema for the particular {@TypeDef}.
* @param definition The definition.
* @return The schema.
*/
public static JSONSchemaProps from(TypeDef definition) {
JSONSchemaPropsBuilder builder = new JSONSchemaPropsBuilder();
builder.withType("object");
List<String> required = new ArrayList<>();
for (Property property : TypeUtils.allProperties(definition)) {
JSONSchemaProps schema = from(property.getTypeRef());
if (property.getAnnotations()
.stream()
.anyMatch(a -> a.getClassRef().getFullyQualifiedName().equals("javax.validation.constraints.NotNull"))) {
required.add(property.getName());
}
if (schema != null) {
builder.addToProperties(property.getName(), from(property.getTypeRef()));
}
}
builder.withRequired(required);
return builder.build();
}
示例3
public static JSONSchemaProps from(TypeRef typeRef) {
//1. Handle Collections and Arrays
if (typeRef.getDimensions() > 0 || TypeUtils.isCollection(typeRef)) {
return new JSONSchemaPropsBuilder()
.withType("array")
.withNewItems()
.withSchema(from(TypeAs.combine(TypeAs.UNWRAP_ARRAY_OF, TypeAs.UNWRAP_COLLECTION_OF).apply(typeRef)))
.and()
.build();
//2. Handle Standard Types
} else if (TYPE_MAP.containsKey(typeRef)) {
return new JSONSchemaPropsBuilder()
.withType(TYPE_MAP.get(typeRef))
.build();
//3. Handle Optionals
} else if (TypeUtils.isOptional(typeRef)) {
return from(TypeAs.UNWRAP_OPTIONAL_OF.apply(typeRef));
//4. Handle complex types
} else if (typeRef instanceof ClassRef) {
ClassRef classRef = (ClassRef) typeRef;
TypeDef def = classRef.getDefinition();
return from(def);
}
return null;
}
示例4
private void removeDefaultValues(JSONSchemaProps schema) {
if (null == schema) {
return;
}
schema.setDefault(null);
if (null != schema.getProperties()) {
for (JSONSchemaProps prop : schema.getProperties().values()) {
removeDefaultValues(prop);
}
}
}
示例5
@Test
void shouldCreateJsonSchemaFromClass() {
TypeDef person = ClassTo.TYPEDEF.apply(Person.class);
JSONSchemaProps schema = JsonSchema.from(person);
System.out.println(Serialization.asJson(schema));
assertNotNull(schema);
}
示例6
JSONSchemaProps readSchema() throws IOException {
ObjectMapper mapper = new ObjectMapper();
final URL resource = getClass().getResource("/test-crd-validation-schema.json");
final JSONSchemaProps jsonSchemaProps = mapper.readValue(resource, JSONSchemaProps.class);
return jsonSchemaProps;
}
示例7
@Test
void unmarshalCRDWithSchema() throws Exception {
final String input = readYamlToString("/test-crd-schema.yml");
final CustomResourceDefinition crd = Serialization.unmarshal(input, CustomResourceDefinition.class);
JSONSchemaProps spec = crd.getSpec()
.getValidation()
.getOpenAPIV3Schema()
.getProperties()
.get("spec");
assertEquals(spec.getRequired().size(), 3);
assertEquals(spec.getRequired().get(0), "builderName");
assertEquals(spec.getRequired().get(1), "edges");
assertEquals(spec.getRequired().get(2), "dimensions");
Map<String, JSONSchemaProps> properties = spec.getProperties();
assertNotNull(properties.get("builderName"));
assertEquals(properties.get("builderName").getExample(), new TextNode("builder-example"));
assertEquals(properties.get("hollow").getDefault(), BooleanNode.FALSE);
assertNotNull(properties.get("dimensions"));
assertNotNull(properties.get("dimensions").getProperties().get("x"));
assertEquals(properties.get("dimensions").getProperties().get("x").getDefault(), new IntNode(10));
String output = Serialization.asYaml(crd);
assertEquals(input.trim(), output.trim());
}
示例8
public CustomResourceDefinition initCrds(KubernetesClient client,
String prefix,
String entityName,
String[] shortNames,
String pluralName,
String[] additionalPrinterColumnNames,
String[] additionalPrinterColumnPaths,
String[] additionalPrinterColumnTypes,
Class<? extends EntityInfo> infoClass,
boolean isOpenshift) {
final String newPrefix = prefix.substring(0, prefix.length() - 1);
CustomResourceDefinition crdToReturn;
Serialization.jsonMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<CustomResourceDefinition> crds = client.customResourceDefinitions()
.list()
.getItems()
.stream()
.filter(p -> entityName.equals(p.getSpec().getNames().getKind()) && newPrefix.equals(p.getSpec().getGroup()))
.collect(Collectors.toList());
if (!crds.isEmpty()) {
crdToReturn = crds.get(0);
log.info("CustomResourceDefinition for {} has been found in the K8s, so we are skipping the creation.", entityName);
} else {
log.info("Creating CustomResourceDefinition for {}.", entityName);
JSONSchemaProps schema = JSONSchemaReader.readSchema(infoClass);
CustomResourceDefinitionFluent.SpecNested<CustomResourceDefinitionBuilder> builder;
if (schema != null) {
removeDefaultValues(schema);
builder = getCRDBuilder(newPrefix,
entityName,
shortNames,
pluralName)
.withNewValidation()
.withNewOpenAPIV3SchemaLike(schema)
.endOpenAPIV3Schema()
.endValidation();
} else {
builder = getCRDBuilder(newPrefix,
entityName,
shortNames,
pluralName);
}
if (additionalPrinterColumnNames != null && additionalPrinterColumnNames.length > 0) {
for (int i = 0; i < additionalPrinterColumnNames.length; i++) {
builder = builder.addNewAdditionalPrinterColumn().withName(additionalPrinterColumnNames[i]).withJSONPath(additionalPrinterColumnPaths[i]).endAdditionalPrinterColumn();
}
}
crdToReturn = builder.endSpec().build();
try {
if (schema != null) {
// https://github.com/fabric8io/kubernetes-client/issues/1486
crdToReturn.getSpec().getValidation().getOpenAPIV3Schema().setDependencies(null);
}
client.customResourceDefinitions().createOrReplace(crdToReturn);
} catch (KubernetesClientException e) {
// old version of K8s/openshift -> don't use schema validation
log.warn("Consider upgrading the {}. Your version doesn't support schema validation for custom resources."
, isOpenshift ? "OpenShift" : "Kubernetes");
crdToReturn = getCRDBuilder(newPrefix,
entityName,
shortNames,
pluralName)
.endSpec()
.build();
client.customResourceDefinitions().createOrReplace(crdToReturn);
}
}
// register the new crd for json serialization
io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName, InfoClass.class);
io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName + "List", CustomResourceList.class);
return crdToReturn;
}