Skip to content

Commit

Permalink
Check explicitly for invalid model type in Java
Browse files Browse the repository at this point in the history
Please see #510 for more details. This is a fix particularly for Java
generation.
  • Loading branch information
empwilli committed Jul 23, 2024
1 parent bd310fc commit 41badc2
Show file tree
Hide file tree
Showing 2 changed files with 584 additions and 23 deletions.
49 changes: 44 additions & 5 deletions aas_core_codegen/java/jsonization/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,9 @@ def _generate_from_method_for_class(

blocks.append(Stripped(args_init_writer.getvalue()))

if cls.serialization.with_model_type:
blocks.append(Stripped("String modelType = null;"))

# endregion

# region Switch on property name
Expand All @@ -350,7 +353,7 @@ def _generate_from_method_for_class(
json_name = naming.json_property(arg.name)

# NOTE (empwilli, 2024-01-18):
# We put ``if (keyValue.Value != null)`` here instead of the outer loop
# We put ``if (currentNode.getValue() == null)`` here instead of the outer loop
# since we want to detect the unexpected additional properties even
# though their value can be set to null.

Expand All @@ -372,12 +375,36 @@ def _generate_from_method_for_class(
return None, errors

if cls.serialization.with_model_type:
cls_name = java_naming.class_name(cls.name)
model_type = naming.json_model_type(cls.name)

cases.append(
Stripped(
"""\
case "modelType": {
continue;
}"""
f"""\
case "modelType": {{
{I}if (currentNode.getValue() == null) {{
{II}final Reporting.Error error = new Reporting.Error(
{III}"Expected a model type, but got null");
{II}return Result.failure(error);
{I}}}
{I}final Result<? extends String> modelTypeResult =
{II}DeserializeImplementation.tryStringFrom(currentNode.getValue());
{I}if (modelTypeResult.isError()) {{
{II}modelTypeResult.getError()
{III}.prependSegment(new Reporting.NameSegment("modelType"));
{II}return modelTypeResult.castTo({cls_name}.class);
{I}}}
{I}modelType = modelTypeResult.getResult();
{I}if (!modelType.equals("{model_type}")) {{
{II}final Reporting.Error error = new Reporting.Error(
{III}"Expected the model type '{model_type}', " +
{III}"but got '" + modelType + "'");
{III}error.prependSegment(new Reporting.NameSegment("modelType"));
{III}return Result.failure(error);
{I}}}
{I}break;
}}"""
)
)

Expand Down Expand Up @@ -413,6 +440,18 @@ def _generate_from_method_for_class(

# region Check required

if cls.serialization.with_model_type:
blocks.append(
Stripped(
f"""\
if (modelType == null) {{
{I}final Reporting.Error error = new Reporting.Error(
{II}"Required property \\"modelType\\" is missing");
{I}return Result.failure(error);
}}"""
)
)

required_check_writer = io.StringIO()
for i, arg in enumerate(cls.constructor.arguments):
if isinstance(arg.type_annotation, intermediate.OptionalTypeAnnotation):
Expand Down
Loading

0 comments on commit 41badc2

Please sign in to comment.