io.swagger.models.Model Java Examples

The following examples show how to use io.swagger.models.Model. 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: Swift3Codegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
    if(codegenModel.description != null) {
        codegenModel.imports.add("ApiModel");
    }
    if (allDefinitions != null) {
      String parentSchema = codegenModel.parentSchema;

      // multilevel inheritance: reconcile properties of all the parents
      while (parentSchema != null) {
        final Model parentModel = allDefinitions.get(parentSchema);
        final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions);
        codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel);

        // get the next parent
        parentSchema = parentCodegenModel.parentSchema;
      }
    }

    return codegenModel;
}
 
Example #2
Source File: JaxrsReader.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
private Parameter replaceArrayModelForOctetStream(Operation operation, Parameter parameter) {
    if (parameter instanceof BodyParameter
            && operation.getConsumes() != null
            && operation.getConsumes().contains("application/octet-stream")) {
        BodyParameter bodyParam = (BodyParameter) parameter;
        Model schema = bodyParam.getSchema();
        if (schema instanceof ArrayModel) {
            ArrayModel arrayModel = (ArrayModel) schema;
            Property items = arrayModel.getItems();
            if (items != null && items.getFormat() == "byte" && items.getType() == "string") {
                ModelImpl model = new ModelImpl();
                model.setFormat("byte");
                model.setType("string");
                bodyParam.setSchema(model);
            }
        }
    }
    return parameter;
}
 
Example #3
Source File: ComponentSchemaTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
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 #4
Source File: DocumentationDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: SwaggerHandlerImplTest.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
private void init() {
  mockMap.put("xxxx", apiListing);
  mockDoc = new Documentation("xx", "/xx", null, mockMap,
      null, Collections.emptySet(), Collections.emptySet(), null, Collections.emptySet(), Collections.emptyList());
  mockSwagger = new Swagger();
  mockSwagger.setInfo(new Info());
  Map<String, Model> defMap = new HashMap<>();
  defMap.put("xx", new ModelImpl());
  mockSwagger.setDefinitions(defMap);
  Map<String, Path> pathMap = new HashMap<>();
  pathMap.put("xx", new Path());
  mockSwagger.setPaths(pathMap);
  new Expectations() {
    {
      documentationCache.documentationByGroup(anyString);
      result = mockDoc;

      DefinitionCache.getClassNameBySchema(anyString);
      result = "app";

      mapper.mapDocumentation((Documentation) any);
      result = mockSwagger;
    }
  };
}
 
Example #6
Source File: HaskellHttpClientCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model mod, Map<String, Model> allDefinitions) {
    CodegenModel model = super.fromModel(name, mod, allDefinitions);

    while (typeNames.contains(model.classname)) {
        model.classname = generateNextName(model.classname);
    }
    typeNames.add(model.classname);
    modelTypeNames.add(model.classname);

    // From the model name, compute the prefix for the fields.
    String prefix = StringUtils.uncapitalize(model.classname);
    for (CodegenProperty prop : model.vars) {
        prop.name = toVarName(prefix, prop.name);
    }

    return model;
}
 
Example #7
Source File: DocumentationDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
private void validateDefinition(String definitionName, Model actualDefinition, Model expectedDefinition) {
    if (expectedDefinition != null && actualDefinition != null) {
        validateModel(actualDefinition, expectedDefinition, String.format("Checking model of definition '%s", definitionName));
        validateDefinitionProperties(schemaObjectResolver.resolvePropertiesFromActual(actualDefinition),
                                     schemaObjectResolver.resolvePropertiesFromExpected(expectedDefinition),
                                     definitionName);

        if (expectedDefinition instanceof ModelImpl && actualDefinition instanceof ModelImpl) {
            validateTypeDefinition(actualDefinition, expectedDefinition);
            validateDefinitionEnum(actualDefinition, expectedDefinition);
            validateDefinitionRequiredProperties(((ModelImpl) actualDefinition).getRequired(),
                                                 ((ModelImpl) expectedDefinition).getRequired(),
                                                   definitionName);
        }
    }
}
 
Example #8
Source File: DocumentationDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
private void validateDefinitions(Map<String, Model> actualDefinitions, Map<String, Model> expectedDefinitions) {
    if (MapUtils.isNotEmpty(expectedDefinitions)) {
        softAssertions.assertThat(actualDefinitions).as("Checking Definitions").isNotEmpty();
        if (MapUtils.isNotEmpty(actualDefinitions)) {
            softAssertions.assertThat(actualDefinitions.keySet()).as("Checking Definitions").hasSameElementsAs(expectedDefinitions.keySet());
            for (Map.Entry<String, Model> actualDefinitionEntry : actualDefinitions.entrySet()) {
                Model expectedDefinition = expectedDefinitions.get(actualDefinitionEntry.getKey());
                Model actualDefinition = actualDefinitionEntry.getValue();
                String definitionName = actualDefinitionEntry.getKey();
                validateDefinition(definitionName, actualDefinition, expectedDefinition);
            }
        }
    } else {
        softAssertions.assertThat(actualDefinitions).as("Checking Definitions").isNullOrEmpty();
    }
}
 
Example #9
Source File: DefinitionComponent.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    String definitionName = params.definitionName;
    String definitionTitle = determineDefinitionTitle(params);

    Model model = params.model;
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEFORE, markupDocBuilder, definitionName, model));
    markupDocBuilder.sectionTitleWithAnchorLevel(params.titleLevel, definitionTitle, definitionName);
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_BEGIN, markupDocBuilder, definitionName, model));
    String description = model.getDescription();
    if (isNotBlank(description)) {
        markupDocBuilder.paragraph(markupDescription(MarkupLanguage.valueOf(config.getSchemaMarkupLanguage().name()),
                markupDocBuilder, description));
    }
    inlineDefinitions(markupDocBuilder, typeSection(markupDocBuilder, definitionName, model), definitionName);
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_END, markupDocBuilder, definitionName, model));
    applyDefinitionsDocumentExtension(new Context(Position.DEFINITION_AFTER, markupDocBuilder, definitionName, model));

    return markupDocBuilder;
}
 
Example #10
Source File: Swift4Codegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
    if (codegenModel.description != null) {
        codegenModel.imports.add("ApiModel");
    }
    if (allDefinitions != null) {
        String parentSchema = codegenModel.parentSchema;

        // multilevel inheritance: reconcile properties of all the parents
        while (parentSchema != null) {
            final Model parentModel = allDefinitions.get(parentSchema);
            final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent,
                                                                    parentModel,
                                                                    allDefinitions);
            codegenModel = Swift4Codegen.reconcileProperties(codegenModel, parentCodegenModel);

            // get the next parent
            parentSchema = parentCodegenModel.parentSchema;
        }
    }

    return codegenModel;
}
 
Example #11
Source File: ModelModifier.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Remove property from {@link Model} for provided {@link ApiModelProperty}.
 * @param apiModelPropertyAnnotation annotation
 * @param model model with properties
 */
private void processProperty(ApiModelProperty apiModelPropertyAnnotation, Model model) {
    if (apiModelPropertyAnnotation == null) {
        return;
    }

    String apiModelPropertyAccess = apiModelPropertyAnnotation.access();
    String apiModelPropertyName = apiModelPropertyAnnotation.name();

    // If the @ApiModelProperty is not populated with both #name and #access, skip it
    if (apiModelPropertyAccess.isEmpty() || apiModelPropertyName.isEmpty()) {
        return;
    }

    // Check to see if the value of @ApiModelProperty#access is one to exclude.
    // If so, remove it from the previously-calculated model.
    if (apiModelPropertyAccessExclusions.contains(apiModelPropertyAccess)) {
        model.getProperties().remove(apiModelPropertyName);
    }
}
 
Example #12
Source File: DefaultCodegen.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
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 #13
Source File: SwaggerToWordExample.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
private List<TextRenderData> fomartSchemaModel(Model schemaModel) {
    List<TextRenderData> schema = new ArrayList<>();
    if (null == schemaModel) return schema;
    // if array
    if (schemaModel instanceof ArrayModel) {
        Property items = ((ArrayModel) schemaModel).getItems();
        schema.add(new TextRenderData("<"));
        schema.addAll(formatProperty(items));
        schema.add(new TextRenderData(">"));
        schema.add(new TextRenderData(((ArrayModel) schemaModel).getType()));
    } else
        // if ref
        if (schemaModel instanceof RefModel) {
            String ref = ((RefModel) schemaModel).get$ref().substring("#/definitions/".length());
            schema.add(new HyperLinkTextRenderData(ref, "anchor:" + ref));
        } else if (schemaModel instanceof ModelImpl) {
            schema.add(new TextRenderData(((ModelImpl) schemaModel).getType()));
        }
    // ComposedModel
    return schema;
}
 
Example #14
Source File: SwaggerTypeAdapter.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
static SwaggerTypeAdapter create(Object swaggerType) {
  if (swaggerType instanceof SwaggerTypeAdapter) {
    return (SwaggerTypeAdapter) swaggerType;
  }

  if (swaggerType instanceof Model) {
    return new ModelAdapter((Model) swaggerType);
  }

  if (swaggerType instanceof Property) {
    return new PropertyAdapter((Property) swaggerType);
  }

  if (swaggerType instanceof SerializableParameter) {
    return new SerializableParameterAdapter((SerializableParameter) swaggerType);
  }

  if (swaggerType instanceof BodyParameter) {
    return new BodyParameterAdapter((BodyParameter) swaggerType);
  }

  throw new IllegalStateException("not support swagger type: " + swaggerType.getClass().getName());
}
 
Example #15
Source File: ExampleGenerator.java    From TypeScript-Microservices with MIT License 6 votes vote down vote up
private Object resolveModelToExample(String name, String mediaType, Model model, Set<String> processedModels) {
    if (processedModels.contains(name)) {
        return model.getExample();
    }
    if (model instanceof ModelImpl) {
        processedModels.add(name);
        ModelImpl impl = (ModelImpl) model;
        Map<String, Object> values = new HashMap<>();

        logger.debug("Resolving model '{}' to example", name);

        if (impl.getExample() != null) {
            logger.debug("Using example from spec: {}", impl.getExample());
            return impl.getExample();
        } else if (impl.getProperties() != null) {
            logger.debug("Creating example from model values");
            for (String propertyName : impl.getProperties().keySet()) {
                Property property = impl.getProperties().get(propertyName);
                values.put(propertyName, resolvePropertyToExample(propertyName, mediaType, property, processedModels));
            }
            impl.setExample(values);
        }
        return values;
    }
    return "";
}
 
Example #16
Source File: AnnotationUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void appendDefinition(Swagger swagger, Map<String, Model> newDefinitions) {
  if (newDefinitions.isEmpty()) {
    return;
  }

  Map<String, Model> definitions = swagger.getDefinitions();
  if (definitions == null) {
    definitions = new LinkedHashMap<>();
    swagger.setDefinitions(definitions);
  }

  definitions.putAll(newDefinitions);
}
 
Example #17
Source File: DefaultResponseTypeProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public Model process(SwaggerGenerator swaggerGenerator, OperationGenerator operationGenerator,
    Type genericResponseType) {
  Type responseType = extractResponseType(swaggerGenerator, operationGenerator, genericResponseType);
  if (responseType == null || ReflectionUtils.isVoid(responseType)) {
    return null;
  }

  if (responseType instanceof Class && Part.class.isAssignableFrom((Class<?>) responseType)) {
    responseType = Part.class;
  }
  SwaggerUtils.addDefinitions(swaggerGenerator.getSwagger(), responseType);
  Property property = ModelConverters.getInstance().readAsProperty(responseType);
  return new PropertyModelConverter().propertyToModel(property);
}
 
Example #18
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param model
 * @return
 */
private String getSuperClass(Model model) {
	LOGGER.entering(LOGGER.getName(), "getSuperClass");

	String superClass = null;

	if (model instanceof ArrayModel) {
		ArrayModel arrayModel = (ArrayModel) model;
		Property propertyObject = arrayModel.getItems();

		if (propertyObject instanceof RefProperty) {
			superClass = new StringBuilder().append("ArrayList[")
					.append(((RefProperty) propertyObject).getSimpleRef()).append("]").toString();
		}
	} else if (model instanceof ModelImpl) {
		Property addProperty = ((ModelImpl) model).getAdditionalProperties();

		if (addProperty instanceof RefProperty) {
			superClass = new StringBuilder().append("Map[").append(((RefProperty) addProperty).getSimpleRef())
					.append("]").toString();
		}
	}

	LOGGER.exiting(LOGGER.getName(), "getSuperClass");

	return superClass;
}
 
Example #19
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static ModelImpl getModelImpl(Swagger swagger, BodyParameter bodyParameter) {
  Model model = bodyParameter.getSchema();
  if (model instanceof ModelImpl) {
    return (ModelImpl) model;
  }

  if (!(model instanceof RefModel)) {
    return null;
  }

  String simpleRef = ((RefModel) model).getSimpleRef();
  Model targetModel = swagger.getDefinitions().get(simpleRef);
  return targetModel instanceof ModelImpl ? (ModelImpl) targetModel : null;
}
 
Example #20
Source File: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
protected Model createResponseModel() {
  Type responseType = ParamUtils
      .getGenericParameterType(clazz, method.getDeclaringClass(), method.getGenericReturnType());
  if (ReflectionUtils.isVoid(responseType)) {
    return null;
  }

  ResponseTypeProcessor processor = findResponseTypeProcessor(responseType);
  return processor.process(swaggerGenerator, this, responseType);
}
 
Example #21
Source File: SwaggerModelConverter.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public Model resolve(Type type, ModelConverterContext context, Iterator<ModelConverter> chain) {
    if (chain.hasNext()) {
        Class c = null;
        if (type instanceof SimpleType) {
            c = ((SimpleType) type).getRawClass();
        } else if (type instanceof Class) {
            c = (Class) type;
        }

        if (c != null) {
            // Process @JsonValue annotation on field first if we have any
            Optional<Field> optField = Arrays.stream(c.getFields())
                    .filter(f -> f.getAnnotation(JsonValue.class) != null)
                    .findAny();
            if (optField.isPresent()) {
                return resolve(optField.get().getGenericType(), context, chain);
            }

            // Process @JsonValue annotation on method first if we have any
            Optional<Method> optMethod = Arrays.stream(c.getMethods())
                    .filter(m -> m.getAnnotation(JsonValue.class) != null)
                    .findAny();
            if (optMethod.isPresent()) {
                return resolve(optMethod.get().getGenericReturnType(), context, chain);
            }

            // If we can find a cache/view object for this type, then use that for documentation,
            // because we can't annotate Sponge classes with @Swagger stuff
            Optional<Type> optClass = WebAPI.getSerializeService().getViewFor(c);
            if (optClass.isPresent()) {
                return resolve(optClass.get(), context, chain);
            }
        }
        return chain.next().resolve(type, context, chain);
    } else {
        return null;
    }
}
 
Example #22
Source File: SpringInterfacesResponseEntityNoSwaggerAnnotations.java    From swagger-codegen-tooling with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    final CodegenModel cgModel = super.fromModel(name, model, allDefinitions);
    // these are imports for the swagger annotations. We don't want those.
    cgModel.imports.remove("ApiModel");
    cgModel.imports.remove("ApiModelProperty");
    return cgModel;
}
 
Example #23
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: SequenceGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void populateParametersFromOperation(Operation operation, Map<String, Model> definitions,
        Map<String, String> parameterJsonPathMapping, Map<String, String> queryParameters) {

    List<Parameter> parameters = operation.getParameters();
    for (Parameter parameter : parameters) {
        String name = parameter.getName();
        if (parameter instanceof BodyParameter) {
            Model schema = ((BodyParameter) parameter).getSchema();
            if (schema instanceof RefModel) {
                String $ref = ((RefModel) schema).get$ref();
                if (StringUtils.isNotBlank($ref)) {
                    String defName = $ref.substring("#/definitions/".length());
                    Model model = definitions.get(defName);
                    Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());

                    String jsonExample = Json.pretty(example);
                    try {
                        org.json.JSONObject json = new org.json.JSONObject(jsonExample);
                        SequenceUtils.listJson(json, parameterJsonPathMapping);
                    } catch (JSONException e) {
                        log.error("Error occurred while generating json mapping for the definition: " + defName, e);
                    }
                }
            }
        }
        if (parameter instanceof QueryParameter) {
            String type = ((QueryParameter) parameter).getType();
            queryParameters.put(name, type);
        }
    }
}
 
Example #25
Source File: SpringInterfacesNoSwaggerAnnotations.java    From swagger-codegen-tooling with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    final CodegenModel cgModel = super.fromModel(name, model, allDefinitions);
    // these are imports for the swagger annotations. We don't want those.
    cgModel.imports.remove("ApiModel");
    cgModel.imports.remove("ApiModelProperty");
    return cgModel;
}
 
Example #26
Source File: UnpackingDataObjectsBuilder.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Build Swagger model for given Yang data node
 * @param node for which we want to build model
 * @param <T> YANG node type
 * @return Swagger model
 */
public <T extends SchemaNode & DataNodeContainer> Model build(T node) {
    final ModelImpl model = new ModelImpl();
    model.description(desc(node));
    model.setProperties(structure(node));

    built.add(getName(node));

    return model;
}
 
Example #27
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param model
 * @return
 */
private List<ClassMembers> getClassMembers(ModelImpl model, Map<String, Model> modelsMap) {
	LOGGER.entering(LOGGER.getName(), "getClassMembers-ModelImpl");

	List<ClassMembers> classMembers = new ArrayList<ClassMembers>();

	Map<String, Property> modelMembers = model.getProperties();
	if (modelMembers != null && !modelMembers.isEmpty()) {
		classMembers.addAll(convertModelPropertiesToClassMembers(modelMembers, model, modelsMap));
	} else {
		Property modelAdditionalProps = model.getAdditionalProperties();

		if (modelAdditionalProps instanceof RefProperty) {
			classMembers.add(getRefClassMembers((RefProperty) modelAdditionalProps));
		}

		if (modelAdditionalProps == null) {
			List<String> enumValues = model.getEnum();

			if (enumValues != null && !enumValues.isEmpty()) {
				classMembers.addAll(getEnum(enumValues));
			}
		}
	}

	LOGGER.exiting(LOGGER.getName(), "getClassMembers-ModelImpl");

	return classMembers;
}
 
Example #28
Source File: TestRBeanSwaggerModel.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllTypes() {
  Map<String, Model> modelMap = ModelConverters.getInstance()
      .read(TypeToken.of(RAllTypes.class).getType());

  Model rAllTypes = modelMap.get(RAllTypes.class.getSimpleName());
  Assert.assertNotNull(rAllTypes);

  Map<String, Class<? extends Property>> expectedProperties = ImmutableMap.<String, Class<? extends Property>>builder()
      .put("id", StringProperty.class)
      .put("rChar", StringProperty.class)
      .put("rDate", LongProperty.class)
      .put("rTime", LongProperty.class)
      .put("rDatetime", LongProperty.class)
      .put("rLong", LongProperty.class)
      .put("rDouble", DoubleProperty.class)
      .put("rDecimal", DecimalProperty.class)
      .put("rEnum", StringProperty.class)
      .put("rSubBean", RefProperty.class)
      .put("rSubBeanList", ArrayProperty.class)
      .build();

  Assert.assertEquals(expectedProperties.size(), rAllTypes.getProperties().size());
  expectedProperties.forEach(
      (k, v) -> Assert.assertEquals(v, rAllTypes.getProperties().get(k).getClass())
  );
  StringProperty rEnumProperty = ((StringProperty)rAllTypes.getProperties().get("rEnum"));
  Assert.assertTrue(
      new HashSet<>(rEnumProperty.getEnum())
          .containsAll(Arrays.stream(Alphabet.values()).map(Enum::name).collect(Collectors.toSet()))
  );

  RefProperty refProperty = (RefProperty) rAllTypes.getProperties().get("rSubBean");
  Assert.assertEquals(refProperty.getSimpleRef(), RSubBean.class.getSimpleName());

  ArrayProperty arrayProperty = (ArrayProperty) rAllTypes.getProperties().get("rSubBeanList");
  Assert.assertEquals(((RefProperty)arrayProperty.getItems()).getSimpleRef(), RSubBean.class.getSimpleName());
}
 
Example #29
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void addDefinitions(Swagger swagger, Type paramType) {
  Map<String, Model> models = ModelConverters.getInstance().readAll(paramType);
  for (Entry<String, Model> entry : models.entrySet()) {
    if (null != swagger.getDefinitions()) {
      Model tempModel = swagger.getDefinitions().get(entry.getKey());
      if (null != tempModel && !tempModel.equals(entry.getValue())) {
        LOGGER.warn("duplicate param model: " + entry.getKey());
        throw new IllegalArgumentException("duplicate param model: " + entry.getKey());
      }
    }
    swagger.addDefinition(entry.getKey(), entry.getValue());
  }
}
 
Example #30
Source File: TemplateTest.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> readSwaggerModelInfo(String swaggerYamlFile, CodegenConfig config) throws IOException {

    Map<String, Object> templateData = new HashMap<>();
    String swaggerString = readResourceInClasspath(swaggerYamlFile);
    Swagger swagger = new SwaggerParser().parse(swaggerString);

    ParseOptions options = new ParseOptions();
    options.setResolve(true);
    options.setFlatten(true);
    SwaggerParseResult result = new OpenAPIParser().readContents(swaggerString, null, options);
    OpenAPI openAPI = result.getOpenAPI();

    Components components = openAPI.getComponents();

    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions == null) {
      return templateData;
    }
    List<Map<String, String>> imports = new ArrayList<Map<String, String>>();
    for (String key : components.getSchemas().keySet()) {
      Schema mm = components.getSchemas().get(key);
      CodegenModel cm = config.fromModel(key, mm);
      Map<String, String> item = new HashMap<String, String>();
      item.put("import", config.toModelImport(cm.classname));
      imports.add(item);
    }
    templateData.put("imports", imports);
    return templateData;
  }