Skip to content

Generate correct names for SubmodelElementCollections #586

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,13 @@ private List<Reference> updateGlobalReferenceWithSeeReferences( final SubmodelEl

@Override
public Environment visitAspect( final Aspect aspect, final Context context ) {
Context usedContext = context;
if ( usedContext == null ) {
final Context usedContext = Optional.ofNullable( context ).orElseGet( () -> {
final Submodel submodel = new DefaultSubmodel.Builder().build();
final Environment environment = new DefaultEnvironment.Builder().submodels( Collections.singletonList( submodel ) ).build();
usedContext = new Context( environment, submodel );
usedContext.setEnvironment( environment );
}
final Context result = new Context( environment, submodel );
result.setEnvironment( environment );
return result;
} );

final String submodelId = aspect.getAspectModelUrn().get().getUrn().toString() + "/submodel";

Expand Down Expand Up @@ -238,11 +238,11 @@ public Environment visitAspect( final Aspect aspect, final Context context ) {

private List<SubmodelElement> visitOperations(
final List<org.eclipse.esmf.metamodel.Operation> elements, final Context context ) {
return elements.stream().map( i -> mapText( i, context ) ).collect( Collectors.toList() );
return elements.stream().map( element -> mapText( element, context ) ).collect( Collectors.toList() );
}

private List<SubmodelElement> visitProperties( final List<Property> elements, final Context context ) {
return elements.stream().map( i -> mapText( i, context ) )
return elements.stream().map( element -> mapText( element, context ) )
.filter( Optional::isPresent )
.map( Optional::get )
.collect( Collectors.toList() );
Expand All @@ -251,7 +251,7 @@ private List<SubmodelElement> visitProperties( final List<Property> elements, fi
private Optional<SubmodelElement> mapText( final Property property, final Context context ) {
final Optional<SubmodelElement> defaultResultForProperty = context.getSubmodel()
.getSubmodelElements().stream()
.filter( i -> i.getIdShort().equals( property.getName() ) )
.filter( submodelElement -> submodelElement.getIdShort().equals( property.getName() ) )
.findFirst();
if ( recursiveProperty.contains( property ) ) {
// The guard checks for recursion in properties. If a recursion happens, the respective
Expand Down Expand Up @@ -299,20 +299,18 @@ private SubmodelElement decideOnMapping( final Property property, final Context
}

private SubmodelElement decideOnMapping( final Type type, final Property property, final Context context ) {
if ( type instanceof Entity ) {
return mapToAasSubModelElementCollection( (Entity) type, context );
} else {
return findPropertyMapper( property ).mapToAasProperty( type, property, context );
}
return type instanceof Entity
? mapToAasSubModelElementCollection( (Entity) type, property, context )
: findPropertyMapper( property ).mapToAasProperty( type, property, context );
}

private SubmodelElementCollection mapToAasSubModelElementCollection( final Entity entity, final Context context ) {
final List<SubmodelElement> submodelElements =
visitProperties( entity.getAllProperties(), context );
private SubmodelElementCollection mapToAasSubModelElementCollection( final Entity entity, final Property property,
final Context context ) {
final List<SubmodelElement> submodelElements = visitProperties( entity.getAllProperties(), context );
return new DefaultSubmodelElementCollection.Builder()
.idShort( entity.getName() )
.displayName( LangStringMapper.NAME.map( entity.getPreferredNames() ) )
.description( LangStringMapper.TEXT.map( entity.getDescriptions() ) )
.idShort( property.getName() )
.displayName( LangStringMapper.NAME.map( property.getPreferredNames() ) )
.description( LangStringMapper.TEXT.map( property.getDescriptions() ) )
.value( submodelElements )
.supplementalSemanticIds( buildGlobalReferenceForSeeReferences( entity ) )
.build();
Expand All @@ -326,10 +324,10 @@ private Operation mapText( final org.eclipse.esmf.metamodel.Operation operation,
.semanticId( buildReferenceToOperation( operation ) )
.idShort( operation.getName() )
.inputVariables( operation.getInput().stream()
.map( i -> mapOperationVariable( i, context ) )
.map( input -> mapOperationVariable( input, context ) )
.collect( Collectors.toList() ) )
.outputVariables( operation.getOutput().stream()
.map( i -> mapOperationVariable( i, context ) )
.map( output -> mapOperationVariable( output, context ) )
.collect( Collectors.toList() ) )
.supplementalSemanticIds( buildGlobalReferenceForSeeReferences( operation ) )
.build();
Expand Down Expand Up @@ -527,7 +525,7 @@ private void createSubmodelElement( final SubmodelElementBuilder op, final Conte

@Override
public Environment visitCharacteristic( final Characteristic characteristic, final Context context ) {
createSubmodelElement( ( property ) -> decideOnMapping( property, context ), context );
createSubmodelElement( property -> decideOnMapping( property, context ), context );
return context.getEnvironment();
}

Expand All @@ -554,7 +552,7 @@ public Environment visitSortedSet( final SortedSet sortedSet, final Context cont

private <T extends Collection> Environment visitCollectionProperty( final T collection, final Context context ) {
final SubmodelElementBuilder builder = property -> {
DefaultSubmodelElementList.Builder submodelBuilder = new DefaultSubmodelElementList.Builder()
final DefaultSubmodelElementList.Builder submodelBuilder = new DefaultSubmodelElementList.Builder()
.idShort( property.getName() )
.typeValueListElement( AasSubmodelElements.DATA_ELEMENT )
.displayName( LangStringMapper.NAME.map( property.getPreferredNames() ) )
Expand Down Expand Up @@ -605,7 +603,7 @@ private <T extends Collection> List<SubmodelElement> getValues( final T collecti
.getBytes( StandardCharsets.UTF_8 ) ).build() );
} else {
final List<SubmodelElement> values = StreamSupport.stream( arrayNode.spliterator(), false )
.map( n -> {
.map( node -> {
context.iterate( property );
return decideOnMapping( property, context );
} )
Expand Down Expand Up @@ -682,7 +680,7 @@ private Property createProperty( final KnownVersion modelVersion, final String p

@Override
public Environment visitQuantifiable( final Quantifiable quantifiable, final Context context ) {
createSubmodelElement( ( property ) -> decideOnMapping( property, context ), context );
createSubmodelElement( property -> decideOnMapping( property, context ), context );

if ( quantifiable.getUnit().isPresent() ) {
final ConceptDescription conceptDescription =
Expand Down Expand Up @@ -712,7 +710,7 @@ public Environment visitDuration( final Duration duration, final Context context

@Override
public Environment visitEnumeration( final Enumeration enumeration, final Context context ) {
createSubmodelElement( ( property ) -> decideOnMapping( property, context ), context );
createSubmodelElement( property -> decideOnMapping( property, context ), context );

final ConceptDescription conceptDescription =
context.getConceptDescription( DEFAULT_MAPPER.determineIdentifierFor( context.getProperty() ) );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,7 @@ public String getPropertyShortId() {
* @return the property value at the current property path
*/
public String getPropertyValue( final String defaultValue ) {
return getRawPropertyValue().map( valueNode -> valueNode.asText( defaultValue ) )
.orElse( defaultValue );
return getRawPropertyValue().flatMap( valueNode -> Optional.ofNullable( valueNode.asText() ) ).orElse( defaultValue );
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.eclipse.esmf.test.TestResources;

import com.fasterxml.jackson.databind.JsonNode;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.eclipse.digitaltwin.aas4j.v3.dataformat.core.DeserializationException;
import org.eclipse.digitaltwin.aas4j.v3.dataformat.xml.XmlDeserializer;
import org.eclipse.digitaltwin.aas4j.v3.model.AasSubmodelElements;
Expand Down Expand Up @@ -77,7 +78,7 @@ void generateAasxWithAspectDataForMultilanguageText() throws DeserializationExce
.satisfies( property ->
assertThat( property ).asInstanceOf( type( MultiLanguageProperty.class ) )
.extracting( MultiLanguageProperty::getValue )
.asList()
.asInstanceOf( InstanceOfAssertFactories.LIST )
.hasSize( 2 )
.allSatisfy( langString ->
assertThat( List.of( "en", "de" ) ).contains( ((AbstractLangString) langString).getLanguage() ) ) ) );
Expand All @@ -92,11 +93,11 @@ void generateAasxWithAspectDataForEitherWithEntity() throws DeserializationExcep
.anySatisfy( sme ->
assertThat( sme ).asInstanceOf( type( SubmodelElementList.class ) )
.extracting( SubmodelElementList::getValue )
.asList()
.asInstanceOf( InstanceOfAssertFactories.LIST )
.anySatisfy( entity ->
assertThat( entity ).asInstanceOf( type( SubmodelElementCollection.class ) )
.extracting( SubmodelElementCollection::getValue )
.asList()
.asInstanceOf( InstanceOfAssertFactories.LIST )
.singleElement( type( Property.class ) )
.extracting( Property::getValue )
.isEqualTo( "The result" ) ) ) );
Expand All @@ -111,11 +112,11 @@ void generateAasxWithAspectDataForNestedEntityLists() throws DeserializationExce
.anySatisfy( sme ->
assertThat( sme ).asInstanceOf( type( SubmodelElementList.class ) )
.extracting( SubmodelElementList::getValue )
.asList()
.asInstanceOf( InstanceOfAssertFactories.LIST )
.anySatisfy( entity ->
assertThat( entity ).asInstanceOf( type( SubmodelElementCollection.class ) )
.extracting( SubmodelElementCollection::getValue )
.asList()
.asInstanceOf( InstanceOfAssertFactories.LIST )
.anySatisfy( property ->
assertThat( property ).asInstanceOf( type( Property.class ) )
.extracting( Property::getValue )
Expand Down Expand Up @@ -143,6 +144,8 @@ void testGenerateAasxFromAspectModelWithEntity() throws DeserializationException
assertThat( env.getSubmodels().get( 0 ).getSubmodelElements() ).hasSize( 1 );
final Submodel submodel = env.getSubmodels().get( 0 );
assertThat( submodel.getSubmodelElements().get( 0 ) ).isInstanceOfSatisfying( SubmodelElementCollection.class, collection -> {
assertThat( collection.getIdShort() ).isEqualTo( "testProperty" );

final SubmodelElement property = collection.getValue().stream().findFirst().get();
assertThat( property.getIdShort() ).isEqualTo( "entityProperty" );
assertThat( submodel.getSupplementalSemanticIds() ).anySatisfy( ref -> {
Expand Down Expand Up @@ -223,8 +226,8 @@ void testGenerateAasxFromAspectModelWithEitherWithComplexTypes() throws Deserial
final Environment env = getAssetAdministrationShellFromAspect( TestAspect.ASPECT_WITH_EITHER_WITH_COMPLEX_TYPES );
assertThat( env.getSubmodels() ).hasSize( 1 );
assertThat( env.getSubmodels().get( 0 ).getSubmodelElements() ).hasSize( 1 );
final SubmodelElementList elementCollection = ( (SubmodelElementList) env.getSubmodels().get( 0 ).getSubmodelElements().get( 0 ) );
final Set<String> testValues = Set.of( "RightEntity", "LeftEntity" );
final SubmodelElementList elementCollection = ((SubmodelElementList) env.getSubmodels().get( 0 ).getSubmodelElements().get( 0 ));
final Set<String> testValues = Set.of( "testProperty", "result" );
assertThat( elementCollection.getValue() ).as( "Neither left nor right entity contained." )
.anyMatch( x -> testValues.contains( x.getIdShort() ) );

Expand All @@ -246,7 +249,7 @@ void testGenerateAasxFromAspectModelWithQuantifiable() throws DeserializationExc
final DataSpecificationContent dataSpecificationContent = getDataSpecificationIec61360(
"urn:samm:org.eclipse.esmf.test:1.0.0#testProperty", env );

assertThat( ( (DataSpecificationIec61360) dataSpecificationContent ).getUnit() ).isEqualTo( "percent" );
assertThat( ((DataSpecificationIec61360) dataSpecificationContent).getUnit() ).isEqualTo( "percent" );
}

@Test
Expand Down Expand Up @@ -381,14 +384,13 @@ void testGeneratedAasxFromAspectModelSemanticIdsAreGlobalReferences() throws Des
}

private void checkDataSpecificationIec61360( final Set<String> semanticIds, final Environment env ) {
semanticIds.forEach( x -> getDataSpecificationIec61360( x, env ) );
semanticIds.forEach( semanticId -> getDataSpecificationIec61360( semanticId, env ) );
}

private DataSpecificationContent getDataSpecificationIec61360( final String semanticId, final Environment env ) {
final List<ConceptDescription> conceptDescriptions = env.getConceptDescriptions();
final List<ConceptDescription> filteredConceptDescriptions =
conceptDescriptions.stream()
.filter( x -> x.getId().equals( semanticId ) )
env.getConceptDescriptions().stream()
.filter( conceptDescription -> conceptDescription.getId().equals( semanticId ) )
.toList();
assertThat( filteredConceptDescriptions ).hasSize( 1 );

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private void generateComponentsMessageAndSchemaEvent( final ObjectNode messagesN
messageNode.put( "name", event.getName() );
messageNode.put( TITLE_FIELD, event.getPreferredName( locale ) );
messageNode.put( "summary", event.getDescription( locale ) );
messageNode.put( "content-type", APPLICATION_JSON );
messageNode.put( "contentType", APPLICATION_JSON );

final ObjectNode payloadNode = FACTORY.objectNode();
payloadNode.put( "$ref", generateRef( COMPONENTS_SCHEMAS_PATH, event.getName() ) );
Expand Down Expand Up @@ -136,7 +136,7 @@ private void generateComponentsMessageAndSchemaOperation( final ObjectNode messa
messageNode.put( "name", property.getName() );
messageNode.put( TITLE_FIELD, property.getPreferredName( locale ) );
messageNode.put( "summary", property.getDescription( locale ) );
messageNode.put( "content-type", APPLICATION_JSON );
messageNode.put( "contentType", APPLICATION_JSON );

final ObjectNode payloadNode = FACTORY.objectNode();
payloadNode.put( "$ref", generateRef( COMPONENTS_SCHEMAS_PATH, property.getName() ) );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ public JsonNode getContent() {
return content;
}

/**
* Returns the AsyncAPI schema a single YAML string
*
* @return the AsyncAPI schema
*/
public String getContentAsYaml() {
return jsonToYaml( getContent() );
}

@Override
public Map<Path, JsonNode> getContentWithSeparateSchemasAsJson() {
return getContentWithSeparateSchemasAsJson( Optional.of( "aai" ) );
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"asyncapi": "${AsyncApiVer}",
"id": "",
"info": {
"title": "MQTT API",
"version" : "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
import org.eclipse.esmf.test.TestAspect;
import org.eclipse.esmf.test.TestResources;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

Expand Down Expand Up @@ -75,6 +77,22 @@ void testAsyncApiGeneratorEmptyAspect( final KnownVersion metaModelVersion ) thr
assertThat( json ).isEqualTo( expectedJson );
}

@Test
void testAsyncApiGeneratorWithoutApplicationIdDoesNotAddEmptyId() throws JsonProcessingException {
final Aspect aspect = loadAspect( TestAspect.ASPECT_WITH_EVENT, KnownVersion.getLatest() );
final AsyncApiSchemaGenerationConfig config = AsyncApiSchemaGenerationConfigBuilder.builder()
.useSemanticVersion( false )
.channelAddress( CHANNEL_ADDRESS )
.locale( Locale.ENGLISH )
.build();

final AsyncApiSchemaArtifact asyncSpec = asyncApiGenerator.apply( aspect, config );
final JsonNode json = asyncSpec.getContent();
final String result = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString( json );
assertThat( result ).doesNotContain( "\"id\" : \"\"" );
assertThat( asyncSpec.getContentAsYaml() ).doesNotContain( "id: \"\"" );
}

@ParameterizedTest
@MethodSource( value = "versionsStartingWith2_0_0" )
void testAsyncApiGeneratorAspectWithEvent( final KnownVersion metaModelVersion ) throws IOException {
Expand Down Expand Up @@ -114,7 +132,7 @@ void testAsyncApiGeneratorAspectWithEvent( final KnownVersion metaModelVersion )
"name": "SomeEvent",
"title": "Some Event",
"summary": "This is some event",
"content-type": "application/json",
"contentType": "application/json",
"payload": {
"$ref": "#/components/schemas/SomeEvent"
}
Expand Down Expand Up @@ -184,7 +202,7 @@ void testAsyncApiGeneratorAspectWithOperation( final KnownVersion metaModelVersi
"name": "input",
"title": "input",
"summary": null,
"content-type": "application/json",
"contentType": "application/json",
"payload": {
"$ref": "#/components/schemas/input"
}
Expand All @@ -197,7 +215,7 @@ void testAsyncApiGeneratorAspectWithOperation( final KnownVersion metaModelVersi
"name": "output",
"title": "output",
"summary": null,
"content-type": "application/json",
"contentType": "application/json",
"payload": {
"$ref": "#/components/schemas/output"
}
Expand Down
Loading
Loading