io.swagger.models.ArrayModel Java Examples

The following examples show how to use io.swagger.models.ArrayModel. 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: ConverterMgr.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private static void initConverters() {
  // inner converters
  for (Class<? extends Property> propertyCls : PROPERTY_MAP.keySet()) {
    addInnerConverter(propertyCls);
  }

  converterMap.put(RefProperty.class, new RefPropertyConverter());
  converterMap.put(ArrayProperty.class, new ArrayPropertyConverter());
  converterMap.put(MapProperty.class, new MapPropertyConverter());
  converterMap.put(StringProperty.class, new StringPropertyConverter());
  converterMap.put(ObjectProperty.class, new ObjectPropertyConverter());

  converterMap.put(ModelImpl.class, new ModelImplConverter());
  converterMap.put(RefModel.class, new RefModelConverter());
  converterMap.put(ArrayModel.class, new ArrayModelConverter());
}
 
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: 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 #4
Source File: MappingConverterImplTest.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testMtoModel() {
    Model model = converter.mToModel(list(mapping(
            field("id", $(intv()).desc("id").$$),
            field("name", $(text(required())).desc("name").$$)
    )));
    assertTrue(model instanceof ArrayModel);
    ArrayModel m = (ArrayModel) model;

    assertTrue(m.getItems() instanceof ObjectProperty);
    ObjectProperty p = (ObjectProperty) m.getItems();

    assertTrue(p.getProperties() != null);
    assertEquals(p.getProperties().size(), 2);
    assertTrue(p.getProperties().get("id") instanceof IntegerProperty);
    assertTrue(p.getProperties().get("name") instanceof StringProperty);

    IntegerProperty p1 = (IntegerProperty) p.getProperties().get("id");
    assertEquals(p1.getRequired(), false);
    assertEquals(p1.getFormat(), "int32");
    assertEquals(p1.getDescription(), "id");

    StringProperty p2 = (StringProperty) p.getProperties().get("name");
    assertEquals(p2.getRequired(), true);
    assertEquals(p2.getDescription(), "name");
}
 
Example #5
Source File: DataProviders.java    From binder-swagger-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected DataProvider collectRefProperty(Swagger swagger, RefProperty schema, boolean clean) {
    Model model = swagger.getDefinitions() != null ? swagger.getDefinitions().get(schema.getSimpleRef()) : null;
    if (model == null) throw new IllegalArgumentException("CAN'T find model for " + schema.getSimpleRef());

    if (model instanceof ArrayModel) {
        DataProvider itemProvider = collect(swagger, ((ArrayModel) model).getItems(), clean);
        return new ListDataProvider(itemProvider, schema.getSimpleRef());
    } else if (model instanceof ModelImpl) {
        Map<String, DataProvider> fields =
            (model.getProperties() != null ? model.getProperties() : Collections.<String, Property>emptyMap()).entrySet().stream()
                .map(e -> entry(e.getKey(), collect(swagger, e.getValue(), clean)))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        return new ObjectDataProvider(fields, schema.getSimpleRef());
    }

    throw new IllegalArgumentException("Unsupported model type: " + model.getClass());
}
 
Example #6
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 #7
Source File: ConsumerDrivenValidator.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 {
            // TODO Validate all model types
            softAssertions.assertThat(actualDefinition).isExactlyInstanceOf(expectedDefinition.getClass());
        }
    }
}
 
Example #8
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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 #9
Source File: BodyParameterExtractor.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public Object extract(String name, Parameter parameter, RoutingContext context) {
    BodyParameter bodyParam = (BodyParameter) parameter;
    if ("".equals(context.getBodyAsString())) {
        if (bodyParam.getRequired())
            throw new IllegalArgumentException("Missing required parameter: " + name);
        else
            return null;
    }

    try {
        if(bodyParam.getSchema() instanceof ArrayModel) {
            return context.getBodyAsJsonArray();
        } else {
            return context.getBodyAsJson();
        }
    } catch (DecodeException e) {
        return context.getBodyAsString();  
    }
}
 
Example #10
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param arrayModel
 * @param modelsMap
 * @return
 */
private List<ClassMembers> getClassMembers(ArrayModel arrayModel, Map<String, Model> modelsMap) {
	LOGGER.entering(LOGGER.getName(), "getClassMembers-ArrayModel");

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

	Property propertyObject = arrayModel.getItems();

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

	LOGGER.exiting(LOGGER.getName(), "getClassMembers-ArrayModel");
	return classMembers;
}
 
Example #11
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void handleOctetStreamAndByteArray() {
    Swagger result = reader.read(AnApiWithOctetStream.class);
    io.swagger.models.Path path = result.getPaths().get("/apath/add");
    assertNotNull(path, "Expecting to find a path ..");
    assertNotNull(path.getPost(), ".. with post opertion ..");
    assertNotNull(path.getPost().getConsumes().contains("application/octet-stream"), ".. and with octect-stream consumer.");
    assertTrue(path.getPost().getParameters().get(0) instanceof BodyParameter, "The parameter is a body parameter ..");
    assertFalse(((BodyParameter) path.getPost().getParameters().get(0)).getSchema() instanceof ArrayModel, " .. and the schema is NOT an ArrayModel");
}
 
Example #12
Source File: ModelDiff.java    From swagger-diff with Apache License 2.0 5 votes vote down vote up
private Model findReferenceModel(Model model, Map<String, Model> modelMap) {
    String modelName = null;
    if (model instanceof RefModel) {
        modelName = ((RefModel) model).getSimpleRef();
    } else if (model instanceof ArrayModel) {
        Property arrayType = ((ArrayModel) model).getItems();
        if (arrayType instanceof RefProperty) {
            modelName = ((RefProperty) arrayType).getSimpleRef();
        }
    }
    return modelName == null ? null : modelMap.get(modelName);
}
 
Example #13
Source File: JavascriptClientCodegen.java    From TypeScript-Microservices with MIT License 5 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 (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) {
        final Model parentModel = allDefinitions.get(codegenModel.parentSchema);
        final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel, allDefinitions);
        codegenModel = JavascriptClientCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel);
    }
    if (model instanceof ArrayModel) {
        ArrayModel am = (ArrayModel) model;
        if (am.getItems() != null) {
            codegenModel.vendorExtensions.put("x-isArray", true);
            codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(am.getItems()));
        }
    } else if (model instanceof ModelImpl) {
        ModelImpl mm = (ModelImpl)model;
        if (mm.getAdditionalProperties() != null) {
            codegenModel.vendorExtensions.put("x-isMap", true);
            codegenModel.vendorExtensions.put("x-itemType", getSwaggerType(mm.getAdditionalProperties()));
        } else {
            String type = mm.getType();
            if (isPrimitiveType(type)){
                codegenModel.vendorExtensions.put("x-isPrimitive", true);
            }
        }
    }

    return codegenModel;
}
 
Example #14
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 #15
Source File: ModelAdapter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public Property getArrayItem() {
  if (model instanceof ArrayModel) {
    return ((ArrayModel) model).getItems();
  }

  return null;
}
 
Example #16
Source File: BodyParameterAdapter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public Property getArrayItem() {
  if (model instanceof ArrayModel) {
    return ((ArrayModel) model).getItems();
  }

  return null;
}
 
Example #17
Source File: ArrayModelConverter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public JavaType doConvert(Swagger swagger, Object model) {
  ArrayModel arrayModel = (ArrayModel) model;

  if (arrayModel.getItems() != null) {
    return ArrayPropertyConverter.findJavaType(swagger, arrayModel.getItems(), false);
  }

  // don't know when will this happen.
  throw new IllegalStateException("not support null array model items.");
}
 
Example #18
Source File: ElmClientCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    CodegenModel m = super.fromModel(name, model, allDefinitions);

    if (model instanceof ArrayModel) {
        ArrayModel am = (ArrayModel) model;
        ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
        CodegenProperty codegenProperty = fromProperty(name, arrayProperty);
        m.vendorExtensions.putAll(codegenProperty.vendorExtensions);
    }

    return m;
}
 
Example #19
Source File: ModelDiff.java    From swagger-diff with Apache License 2.0 4 votes vote down vote up
private boolean isModelReference(Model model) {
    return model instanceof RefModel || model instanceof ArrayModel;
}
 
Example #20
Source File: TypeBuilder.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #21
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param operation
 * @return
 */
private String getMethodParameters(Operation operation) {
	String methodParameter = "";
	List<Parameter> parameters = operation.getParameters();

	for (Parameter parameter : parameters) {
		if (StringUtils.isNotEmpty(methodParameter)) {
			methodParameter = new StringBuilder().append(methodParameter).append(",").toString();
		}

		if (parameter instanceof PathParameter) {
			methodParameter = new StringBuilder().append(methodParameter)
					.append(toTitleCase(((PathParameter) parameter).getType())).append(" ")
					.append(((PathParameter) parameter).getName()).toString();
		} else if (parameter instanceof QueryParameter) {
			Property queryParameterProperty = ((QueryParameter) parameter).getItems();

			if (queryParameterProperty instanceof RefProperty) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((RefProperty) queryParameterProperty).getSimpleRef())).append("[] ")
						.append(((BodyParameter) parameter).getName()).toString();
			} else if (queryParameterProperty instanceof StringProperty) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((StringProperty) queryParameterProperty).getType())).append("[] ")
						.append(((QueryParameter) parameter).getName()).toString();
			} else {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((QueryParameter) parameter).getType())).append(" ")
						.append(((QueryParameter) parameter).getName()).toString();
			}
		} else if (parameter instanceof BodyParameter) {
			Model bodyParameter = ((BodyParameter) parameter).getSchema();

			if (bodyParameter instanceof RefModel) {
				methodParameter = new StringBuilder().append(methodParameter)
						.append(toTitleCase(((RefModel) bodyParameter).getSimpleRef())).append(" ")
						.append(((BodyParameter) parameter).getName()).toString();
			} else if (bodyParameter instanceof ArrayModel) {
				Property propertyObject = ((ArrayModel) bodyParameter).getItems();

				if (propertyObject instanceof RefProperty) {
					methodParameter = new StringBuilder().append(methodParameter)
							.append(toTitleCase(((RefProperty) propertyObject).getSimpleRef())).append("[] ")
							.append(((BodyParameter) parameter).getName()).toString();
				}
			}
		} else if (parameter instanceof FormParameter) {
			methodParameter = new StringBuilder().append(methodParameter)
					.append(toTitleCase(((FormParameter) parameter).getType())).append(" ")
					.append(((FormParameter) parameter).getName()).toString();
		}
	}

	return methodParameter;
}
 
Example #22
Source File: TestApiOperation.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private void testList(Path path) {
  Operation operation = path.getPost();
  Model result200 = operation.getResponses().get("200").getResponseSchema();
  Assert.assertEquals(ArrayModel.class, result200.getClass());
  Assert.assertEquals(null, ((ArrayModel) result200).getUniqueItems());
}
 
Example #23
Source File: TestApiOperation.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
private void testSet(Path path) {
  Operation operation = path.getPost();
  Model result200 = operation.getResponses().get("200").getResponseSchema();
  Assert.assertEquals(ArrayModel.class, result200.getClass());
  Assert.assertEquals(true, ((ArrayModel) result200).getUniqueItems());
}