io.swagger.models.ComposedModel Java Examples
The following examples show how to use
io.swagger.models.ComposedModel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComponentSchemaTransformer.java From spring-openapi with MIT License | 6 votes |
private Model traverseAndAddProperties(ModelImpl schema, GenerationContext generationContext, Class<?> superclass, Class<?> clazz) { if (!isInPackagesToBeScanned(superclass, generationContext)) { // adding properties from parent classes is present due to swagger ui bug, after using different ui // this becomes relevant only for third party packages getClassProperties(superclass, generationContext).forEach(schema::addProperty); if (superclass.getSuperclass() != null && !"java.lang".equals(superclass.getSuperclass().getPackage().getName())) { return traverseAndAddProperties(schema, generationContext, superclass.getSuperclass(), superclass); } return schema; } else { RefModel parentClassSchema = new RefModel(); parentClassSchema.set$ref(CommonConstants.COMPONENT_REF_PREFIX + superclass.getSimpleName()); ComposedModel composedSchema = new ComposedModel(); composedSchema.setAllOf(Arrays.asList(parentClassSchema, schema)); InheritanceInfo inheritanceInfo = generationContext.getInheritanceMap().get(superclass.getName()); if (inheritanceInfo != null) { String discriminatorName = inheritanceInfo.getDiscriminatorClassMap().get(clazz.getName()); composedSchema.setVendorExtension("x-discriminator-value", discriminatorName); composedSchema.setVendorExtension("x-ms-discriminator-value", discriminatorName); } return composedSchema; } }
Example #2
Source File: DefaultCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
/** * Recursively look for a discriminator in the interface tree */ private boolean isDiscriminatorInInterfaceTree(ComposedModel model, Map<String, Model> allDefinitions) { if (model == null || allDefinitions == null) return false; Model child = model.getChild(); if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { return true; } for (RefModel _interface : model.getInterfaces()) { Model interfaceModel = allDefinitions.get(_interface.getSimpleRef()); if (interfaceModel instanceof ModelImpl && ((ModelImpl) interfaceModel).getDiscriminator() != null) { return true; } if (interfaceModel instanceof ComposedModel) { return isDiscriminatorInInterfaceTree((ComposedModel) interfaceModel, allDefinitions); } } return false; }
Example #3
Source File: DefaultCodegen.java From TypeScript-Microservices with MIT License | 6 votes |
protected void addProperties(Map<String, Property> properties, List<String> required, Model model, Map<String, Model> allDefinitions) { if (model instanceof ModelImpl) { ModelImpl mi = (ModelImpl) model; if (mi.getProperties() != null) { properties.putAll(mi.getProperties()); } if (mi.getRequired() != null) { required.addAll(mi.getRequired()); } } else if (model instanceof RefModel) { String interfaceRef = ((RefModel) model).getSimpleRef(); Model interfaceModel = allDefinitions.get(interfaceRef); addProperties(properties, required, interfaceModel, allDefinitions); } else if (model instanceof ComposedModel) { for (Model component :((ComposedModel) model).getAllOf()) { addProperties(properties, required, component, allDefinitions); } } }
Example #4
Source File: CollapseTypes.java From yang2swagger with Eclipse Public License 1.0 | 6 votes |
@Override protected Map<String, String> prepareForReplacement(Swagger swagger) { Map<String, Set<String>> sameGroups = swagger.getDefinitions().entrySet().stream() .filter(e -> e.getValue() instanceof ComposedModel) .filter(e -> referenceOnly.test((ComposedModel) e.getValue())) .map(e -> new AbstractMap.SimpleEntry<>(toSignature.apply((ComposedModel) e.getValue()), e.getKey())) .collect(groupingBy(AbstractMap.SimpleEntry::getKey, mapping(AbstractMap.SimpleEntry::getValue, toSet()))); return sameGroups.values().stream() .filter(v -> v.size() > 1) .flatMap(v -> { final String type = v.stream().min(Comparator.comparingInt(String::length)).get(); return v.stream().filter(s -> !s.equals(type)).map(s -> new AbstractMap.SimpleEntry<>(s, type)); }).collect(toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); }
Example #5
Source File: ReplaceEmptyWithParent.java From yang2swagger with Eclipse Public License 1.0 | 6 votes |
@Override protected Map<String, String> prepareForReplacement(Swagger swagger) { return swagger.getDefinitions().entrySet() .stream().filter(e -> { Model model = e.getValue(); if (model instanceof ComposedModel) { List<Model> allOf = ((ComposedModel) model).getAllOf(); return allOf.size() == 1 && allOf.get(0) instanceof RefModel; } return false; }).map(e -> { RefModel ref = (RefModel) ((ComposedModel) e.getValue()).getAllOf().get(0); return new Tuple<>(e.getKey(), ref.getSimpleRef()); }).collect(Collectors.toMap(Tuple::first, Tuple::second)); }
Example #6
Source File: SwaggerGeneratorWithOdlPathHandlerTest.java From yang2swagger with Eclipse Public License 1.0 | 6 votes |
@org.junit.Test public void testInheritenceWithAugmentation() throws Exception { SchemaContext ctx = ContextHelper.getFromClasspath(p -> p.getParent().getFileName().toString().equals("inheritence-with-augmentation")); SwaggerGenerator generator = new SwaggerGenerator(ctx, ctx.getModules()).defaultConfig() .pathHandler(new ODLPathHandlerBuilder()); swagger = generator.generate(); ComposedModel base = (ComposedModel) swagger.getDefinitions().get("base.Base"); assertEquals(1, base.getInterfaces().size()); assertEquals("base.Ident", base.getInterfaces().get(0).getSimpleRef()); RefProperty managersRef = (RefProperty) ((ArrayProperty) base.getChild().getProperties().get("managers")).getItems(); RefProperty usersRef = (RefProperty) ((ArrayProperty) base.getChild().getProperties().get("users")).getItems(); ComposedModel managers = (ComposedModel) swagger.getDefinitions().get(managersRef.getSimpleRef()); ComposedModel users = (ComposedModel) swagger.getDefinitions().get(usersRef.getSimpleRef()); assertEquals(2, managers.getAllOf().size()); assertEquals(2, managers.getInterfaces().size()); //users are augmented assertEquals(3, users.getAllOf().size()); assertEquals(2, users.getInterfaces().size()); }
Example #7
Source File: PlantUMLCodegen.java From swagger2puml with Apache License 2.0 | 6 votes |
/** * * @param modelObject * @param modelsMap * @return */ private List<ClassMembers> getClassMembers(Model modelObject, Map<String, Model> modelsMap) { LOGGER.entering(LOGGER.getName(), "getClassMembers"); List<ClassMembers> classMembers = new ArrayList<ClassMembers>(); if (modelObject instanceof ModelImpl) { classMembers = getClassMembers((ModelImpl) modelObject, modelsMap); } else if (modelObject instanceof ComposedModel) { classMembers = getClassMembers((ComposedModel) modelObject, modelsMap); } else if (modelObject instanceof ArrayModel) { classMembers = getClassMembers((ArrayModel) modelObject, modelsMap); } LOGGER.exiting(LOGGER.getName(), "getClassMembers"); return classMembers; }
Example #8
Source File: DocumentationDrivenValidator.java From assertj-swagger with Apache License 2.0 | 6 votes |
private void validateModel(Model actualDefinition, Model expectedDefinition, String message) { if (isAssertionEnabled(SwaggerAssertionType.MODELS)) { if (expectedDefinition instanceof ModelImpl) { // TODO Validate ModelImpl softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(ModelImpl.class); } else if (expectedDefinition instanceof RefModel) { // TODO Validate RefModel softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(RefModel.class); } else if (expectedDefinition instanceof ArrayModel) { ArrayModel arrayModel = (ArrayModel) expectedDefinition; // TODO Validate ArrayModel softAssertions.assertThat(actualDefinition).as(message).isExactlyInstanceOf(ArrayModel.class); } else if (expectedDefinition instanceof ComposedModel) { ComposedModel composedModel = (ComposedModel) expectedDefinition; softAssertions.assertThat(actualDefinition).as(message).isInstanceOfAny(ComposedModel.class, ModelImpl.class); } else { // TODO Validate all model types softAssertions.assertThat(actualDefinition).isExactlyInstanceOf(expectedDefinition.getClass()); } } }
Example #9
Source File: SortComplexModels.java From yang2swagger with Eclipse Public License 1.0 | 5 votes |
@Override public void accept(Swagger swagger) { swagger.getDefinitions().entrySet().stream().filter(e -> e.getValue() instanceof ComposedModel) .forEach(e -> { ComposedModel m = (ComposedModel) e.getValue(); sortModels(m); }); }
Example #10
Source File: SortComplexModels.java From yang2swagger with Eclipse Public License 1.0 | 5 votes |
private void sortModels(ComposedModel m) { m.getAllOf().sort((a,b) -> { if(a instanceof RefModel) { if(b instanceof RefModel) { return ((RefModel) a).getSimpleRef().compareTo(((RefModel) b).getSimpleRef()); } return -1; } return 1; }); }
Example #11
Source File: PlantUMLCodegen.java From swagger2puml with Apache License 2.0 | 5 votes |
/** * * @param composedModel * @param modelsMap * @return */ private List<ClassMembers> getClassMembers(ComposedModel composedModel, Map<String, Model> modelsMap) { LOGGER.entering(LOGGER.getName(), "getClassMembers-ComposedModel"); List<ClassMembers> classMembers = new ArrayList<ClassMembers>(); Map<String, Property> childProperties = new HashMap<String, Property>(); if (null != composedModel.getChild()) { childProperties = composedModel.getChild().getProperties(); } List<Model> allOf = composedModel.getAllOf(); for (Model currentModel : allOf) { if (currentModel instanceof RefModel) { RefModel refModel = (RefModel) currentModel; childProperties.putAll(modelsMap.get(refModel.getSimpleRef()).getProperties()); classMembers = convertModelPropertiesToClassMembers(childProperties, modelsMap.get(refModel.getSimpleRef()), modelsMap); } } LOGGER.exiting(LOGGER.getName(), "getClassMembers-ComposedModel"); return classMembers; }
Example #12
Source File: SundrioGenerator.java From sundrio with Apache License 2.0 | 5 votes |
public TypeDef createModel(String name, Model model, AbstractJavaCodegen config, Map<String, Model> allDefinitions) { String prefix = name.contains(DOT) ? name.substring(0, name.lastIndexOf(DOT)) : EMPTY; String packageName = prefix.isEmpty() ? config.modelPackage() : config.modelPackage() + DOT + prefix; String className = prefix.isEmpty() ? name : name.substring(name.lastIndexOf(DOT) + 1); ClassRef superClass = null; List<ClassRef> interfaces = new ArrayList<>(); List<Property> fields = new ArrayList<>(); List<Method> methods = new ArrayList<>(); if (model instanceof ComposedModel) { ComposedModel composed = (ComposedModel) model; // interfaces (intermediate models) if (composed.getInterfaces() != null) { for (RefModel _interface : composed.getInterfaces()) { Model interfaceModel = null; if (allDefinitions != null) { interfaceModel = allDefinitions.get(_interface.getSimpleRef()); } } return new TypeDefBuilder() .withKind(Kind.CLASS) .withPackageName(packageName) .withName(className) .withImplementsList(interfaces) .withExtendsList(superClass) .withProperties(fields) .withMethods(methods) .build(); } } return null; }
Example #13
Source File: SchemaObjectResolver.java From assertj-swagger with Apache License 2.0 | 5 votes |
private Map<String, Property> resolveProperties(Model definition, Swagger owningSchema, Set<String> seenRefs) { Map<String, Property> result; // if the definition does not contain any property, then the model will return null instead of an empty map final Map<String, Property> definitionProperties = definition.getProperties() != null ? definition.getProperties() : Collections.emptyMap(); if (definition instanceof RefModel) { // Don't navigate ref-def cycles infinitely final RefModel refDef = (RefModel) definition; if (seenRefs.contains(refDef.getSimpleRef())) { return Collections.emptyMap(); } else { seenRefs.add(refDef.getSimpleRef()); } result = resolveProperties(findDefinition(owningSchema.getDefinitions(), refDef), owningSchema, seenRefs); } else if (definition instanceof ComposedModel) { Map<String, Property> allProperties = new HashMap<>(); if (definitionProperties != null) { allProperties.putAll(definitionProperties); } for (final Model childDefinition : ((ComposedModel) definition).getAllOf()) { allProperties.putAll(resolveProperties(childDefinition, owningSchema, seenRefs)); } result = allProperties; } else { result = definitionProperties; } return result; }
Example #14
Source File: JaxrsReaderTest.java From swagger-maven-plugin with Apache License 2.0 | 5 votes |
private Map<String, Property> getProperties(Map<String, Model> models, String className) { assertTrue(models.containsKey(className)); Model model = models.get(className); if (model instanceof ComposedModel) { ComposedModel composedResponse = (ComposedModel) model; return composedResponse.getChild().getProperties(); } else { return model.getProperties(); } }
Example #15
Source File: TypeBuilder.java From api-compiler with Apache License 2.0 | 4 votes |
/** * Create the {@link Type} instance from model. * * <p>NOTE: If the property of the model references another model, then we recursively create the * {@link Type} corresponding to the reference model. * * <p>NOTE: {@link Type} is created only if the model is a ModelImpl (corresponds to JSON Object) * and does not contain additional properties. For other cases we cannot create a Protobuf.Type * instance (Example: ModelImpl with additional properties, array model etc). For such cases just * return the suitable predefined google.protobuf* types. */ TypeInfo addTypeFromModel(Service.Builder serviceBuilder, String typeName, Model model) { String modelRefId = TYPE_DEFINITIONS_PREFIX + typeName; TypeInfo resultTypeInfo = null; if (processedTypeNameToTypeInfo.containsKey(modelRefId)) { return processedTypeNameToTypeInfo.get(modelRefId); } else if (visitedTypes.contains(modelRefId)) { // For nodes that have already been visited but were eventually successfully resolved by our // depth-first traversal, processedTypeNameToTypeInfo will contain the resolution and we will // not hit this conditional. This allows for valid references to other nodes in the type // dependency tree that can be resolved. If, however, our traversal of the tree encounters a // node we have seen before in that same traversal and have NOT yet resolved, then we know we // have an unresolvable circular dependence. // // Note that we have a special case for 'object' types - for those, we are able to store the // generic 'message' type in the processedTypeNameToTypeInfo map before proceeding with the // traversal, so we are able to handle object types whose members reference additional // objects. diagCollector.addDiag( Diag.error( SimpleLocation.TOPLEVEL, "Invalid circular reference detected for type '%s'", typeName)); return null; } visitedTypes.add(modelRefId); if (model != null) { if (model instanceof ComposedModel) { // TODO(user): Expand this composed Model and create a Type from it. resultTypeInfo = WellKnownType.VALUE.toTypeInfo(); } if (model instanceof ArrayModel) { resultTypeInfo = getArrayModelTypeInfo(serviceBuilder, ((ArrayModel) model).getItems()); } if (model instanceof RefModel) { resultTypeInfo = getRefModelTypeInfo(serviceBuilder, (RefModel) model); } if (model instanceof ModelImpl) { ModelImpl modelImpl = (ModelImpl) model; if (isPrimitiveTypeWrapper(modelImpl)) { // Represent this as a wrapper type for the primitive type. resultTypeInfo = WellKnownType.fromString(modelImpl.getType()).toTypeInfo(); } else if (hasAdditionalProperties(modelImpl) && hasProperties(modelImpl)) { // Since both properties and additional properties are present, we cannot create a // protobuf.Type object for it. Therefore, represent this as a Struct type. resultTypeInfo = WellKnownType.STRUCT.toTypeInfo(); } else if (hasAdditionalProperties(modelImpl) && !hasProperties(modelImpl)) { // Since additional properties is present without properties, we can represent this as a // map. TypeInfo mapEntry = getMapEntryTypeInfo( ensureNamed( serviceBuilder, getTypeInfo(serviceBuilder, modelImpl.getAdditionalProperties()), "MapValue")); mapEntry = ensureNamed(serviceBuilder, mapEntry, "MapEntry"); resultTypeInfo = mapEntry.withCardinality(Cardinality.CARDINALITY_REPEATED); } else if (!hasAdditionalProperties(modelImpl)) { // Since there is no additional properties, create a protobuf.Type. String protoTypeName = NameConverter.schemaNameToMessageName(typeName); String typeUrl = WellKnownTypeUtils.TYPE_SERVICE_BASE_URL + namespacePrefix + protoTypeName; // Add to the processed list before creating the type. This will prevent from cyclic // dependency Preconditions.checkState(!processedTypeNameToTypeInfo.containsKey(modelRefId)); resultTypeInfo = TypeInfo.create(typeUrl, Kind.TYPE_MESSAGE, Cardinality.CARDINALITY_OPTIONAL); processedTypeNameToTypeInfo.put(modelRefId, resultTypeInfo); ImmutableList.Builder<Field> fieldsBuilder = createFields(serviceBuilder, modelImpl); resultTypeInfo = resultTypeInfo.withFields(fieldsBuilder.build()).withTypeUrl(""); resultTypeInfo = ensureNamed(serviceBuilder, resultTypeInfo, protoTypeName); } } } if (resultTypeInfo == null) { /* TODO(user): Make this an error once we want to start supporting json to proto * transformation for APIs imported from OpenAPI.*/ resultTypeInfo = WellKnownType.VALUE.toTypeInfo(); } processedTypeNameToTypeInfo.put(modelRefId, resultTypeInfo); return processedTypeNameToTypeInfo.get(modelRefId); }
Example #16
Source File: RJsonModelConverter.java From datacollector with Apache License 2.0 | 4 votes |
@Override public Property resolveProperty(java.lang.reflect.Type type, ModelConverterContext context, Annotation[] annotations, Iterator<ModelConverter> chain) { final JavaType jType = _mapper.constructType(type); if (jType != null) { final Class<?> cls = jType.getRawClass(); if (cls.equals(RString.class)) { return new StringProperty(); } else if (cls.equals(RChar.class)) { return new StringProperty(); } else if (cls.equals(RText.class)) { return new StringProperty(); } else if (cls.equals(RDate.class)) { return new LongProperty(); } else if (cls.equals(RDatetime.class)) { return new LongProperty(); } else if (cls.equals(RTime.class)) { return new LongProperty(); } else if (cls.equals(RLong.class)) { return new LongProperty(); } else if (cls.equals(RBoolean.class)) { return new BooleanProperty(); } else if(cls.equals(RDecimal.class)) { return new DecimalProperty(); } else if(cls.equals(RDouble.class)) { return new DoubleProperty(); } else if(cls.equals(REnum.class)) { Property property = new StringProperty(); if (jType.containedTypeCount() > 0) { _addEnumProps(jType.containedType(0).getRawClass(), property); } return property; } else if (RBean.class.isAssignableFrom(cls)) { // complex type Model innerModel = context.resolve(jType); RBEAN_INTERNAL_FIELDS.forEach(innerModel.getProperties()::remove); if (innerModel instanceof ComposedModel) { innerModel = ((ComposedModel) innerModel).getChild(); } if (innerModel instanceof ModelImpl) { ModelImpl mi = (ModelImpl) innerModel; return new RefProperty(StringUtils.isNotEmpty(mi.getReference()) ? mi.getReference() : mi.getName()); } } return chain.next().resolveProperty(type, context, annotations, chain); } else { return null; } }