io.swagger.models.properties.ArrayProperty Java Examples

The following examples show how to use io.swagger.models.properties.ArrayProperty. 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: SwaggerToWordExample.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
private Object valueOfProperty(Map<String, Model> definitions, Property prop, Set<String> keyCache) {
    Object value;
    if (prop instanceof RefProperty) {
        String ref = ((RefProperty) prop).get$ref().substring("#/definitions/".length());
        if (keyCache.contains(ref)) value = ((RefProperty) prop).get$ref();
        else value = valueOfModel(definitions, definitions.get(ref), keyCache);
    } else if (prop instanceof ArrayProperty) {
        List<Object> list = new ArrayList<>();
        Property insideItems = ((ArrayProperty) prop).getItems();
        list.add(valueOfProperty(definitions, insideItems, keyCache));
        value = list;
    } else if (prop instanceof AbstractNumericProperty) {
        value = 0;
    } else if (prop instanceof BooleanProperty) {
        value = false;
    } else {
        value = prop.getType();
    }
    return value;
}
 
Example #3
Source File: SwaggerToWordExample.java    From poi-tl with Apache License 2.0 6 votes vote down vote up
private List<TextRenderData> formatProperty(Property items) {
    List<TextRenderData> schema = new ArrayList<>();
    if (null != items) {
        if (items instanceof RefProperty) {
            String ref = ((RefProperty) items).get$ref().substring("#/definitions/".length());
            schema.add(new HyperLinkTextRenderData(ref, "anchor:" + ref));
        } else if (items instanceof ArrayProperty) {
            Property insideItems = ((ArrayProperty) items).getItems();
            schema.add(new TextRenderData("<"));
            schema.addAll(formatProperty(insideItems));
            schema.add(new TextRenderData(">"));
            schema.add(new TextRenderData(items.getType()));
        } else {
            schema.add(new TextRenderData(items.getType()));
        }
    }
    return schema;
}
 
Example #4
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param modelObject
 * @param models
 * @param variablName
 * @param classMemberObject
 * @param propObject
 */
private ClassMembers getClassMember(ArrayProperty property, Model modelObject, Map<String, Model> models,
		String variablName) {
	LOGGER.entering(LOGGER.getName(), "getClassMember-ArrayProperty");

	ClassMembers classMemberObject = new ClassMembers();
	Property propObject = property.getItems();

	if (propObject instanceof RefProperty) {
		classMemberObject = getClassMember((RefProperty) propObject, models, modelObject, variablName);
	} else if (propObject instanceof StringProperty) {
		classMemberObject = getClassMember((StringProperty) propObject, variablName);
	}

	LOGGER.exiting(LOGGER.getName(), "getClassMember-ArrayProperty");
	return classMemberObject;
}
 
Example #5
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
public void process(Property property) {
    this.properties.add(property);
    if(property instanceof ArrayProperty) {
        ArrayProperty p = (ArrayProperty)property;
        Property ap = p.getItems();
        this.process(ap);
    } else if(property instanceof MapProperty) {
        MapProperty p1 = (MapProperty)property;
    } else if(property instanceof ObjectProperty) {
        ObjectProperty p2 = (ObjectProperty)property;
        if(p2.getProperties() != null) {
            Iterator ap1 = p2.getProperties().keySet().iterator();

            while(ap1.hasNext()) {
                String name = (String)ap1.next();
                Property ip = (Property)p2.getProperties().get(name);
                this.process(ip);
            }
        }
    }

}
 
Example #6
Source File: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
private io.swagger.models.parameters.Parameter createNswagRequestBody(ParameterNamePair requestBodyParameter, Property property) {
	CustomBodyParameter requestBody = new CustomBodyParameter();

	if (property instanceof RefProperty) {
		CustomSchema customSchema = new CustomSchema();
		customSchema.setRef(((RefProperty) property).get$ref());
		requestBody.setSchema(customSchema);
	} else if (property instanceof ArrayProperty) {
		requestBody.setType("array");
		requestBody.setItems(((ArrayProperty) property).getItems());
	}

	requestBody.setRequired(true);
	requestBody.setName(resolveRequestBodyName(property, requestBodyParameter.getName()));
	requestBody.setDescription(requestBody.getName());

	return requestBody;
}
 
Example #7
Source File: WSDLSOAPOperationExtractorImplTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSwaggerModelForCompositeComplexType() throws Exception {
    APIMWSDLReader wsdlReader = new APIMWSDLReader(
            Thread.currentThread().getContextClassLoader().getResource("wsdls/sample-service.wsdl")
                    .toExternalForm());
    byte[] wsdlContent = wsdlReader.getWSDL();
    WSDL11SOAPOperationExtractor processor = SOAPOperationBindingUtils.getWSDL11SOAPOperationExtractor(wsdlContent,
            wsdlReader);
    Map<String, ModelImpl> parameterModelMap = processor.getWsdlInfo().getParameterModelMap();
    Assert.assertNotNull(parameterModelMap);
    Assert.assertTrue("wsdl complex types has not been properly parsed",
            parameterModelMap.size() == 12);
    //composite complex type
    Assert.assertNotNull(parameterModelMap.get("ItemSearchRequest"));
    Assert.assertEquals(7, parameterModelMap.get("ItemSearchRequest").getProperties().size());
    Assert.assertNotNull(parameterModelMap.get("ItemSearchRequest").getProperties().get("Tracks"));
    Assert.assertNotNull(parameterModelMap.get("ItemSearchRequest").getProperties().get("Tracks"));
    Assert.assertEquals(ArrayProperty.TYPE,
            parameterModelMap.get("ItemSearchRequest").getProperties().get("Tracks").getType());
    Assert.assertNotNull(((ArrayProperty) parameterModelMap.get("ItemSearchRequest").getProperties().get("Tracks"))
            .getItems());
}
 
Example #8
Source File: AbstractOktaJavaClientCodegen.java    From okta-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public String getTypeDeclaration(Property p) {

    if ("password".equals(p.getFormat())) {
        return "char[]";
    }

    if (p instanceof ArrayProperty) {
        ArrayProperty ap = (ArrayProperty) p;
        Property inner = ap.getItems();
        if (inner == null) {
            // mimic super behavior
            log.warn("{} (array property) does not have a proper inner type defined", ap.getName());
            return null;
        }

        String type = super.getTypeDeclaration(inner);
        if (!languageSpecificPrimitives.contains(type) && topLevelResources.contains(type)) {
            return type + "List";
        }
    }
    return super.getTypeDeclaration(p);
}
 
Example #9
Source File: PropertyAdapter.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
/**
 * Return example display string for the given {@code property}.
 *
 * @param generateMissingExamples specifies if missing examples should be generated
 * @param markupDocBuilder        doc builder
 * @return property example display string
 */
public Optional<Object> getExample(boolean generateMissingExamples, MarkupDocBuilder markupDocBuilder) {
    if (property.getExample() != null) {
        return Optional.ofNullable(property.getExample());
    } else if (property instanceof MapProperty) {
        Property additionalProperty = ((MapProperty) property).getAdditionalProperties();
        if (additionalProperty.getExample() != null) {
            return Optional.ofNullable(additionalProperty.getExample());
        } else if (generateMissingExamples) {
            Map<String, Object> exampleMap = new HashMap<>();
            exampleMap.put("string", generateExample(additionalProperty, markupDocBuilder));
            return Optional.of(exampleMap);
        }
    } else if (property instanceof ArrayProperty) {
        if (generateMissingExamples) {
            Property itemProperty = ((ArrayProperty) property).getItems();
            List<Object> exampleArray = new ArrayList<>();
            exampleArray.add(generateExample(itemProperty, markupDocBuilder));
            return Optional.of(exampleArray);
        }
    } else if (generateMissingExamples) {
        return Optional.of(generateExample(property, markupDocBuilder));
    }

    return Optional.empty();
}
 
Example #10
Source File: JerseyServerCodegen.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public CodegenProperty fromProperty(String name, Property p) {
    CodegenProperty property = super.fromProperty(name, p);
    if(p instanceof ArrayProperty) {
        p = ((ArrayProperty) p).getItems();
    }
    //add annotations for vendor extensions
    Map<String, String> extensions = p.getVendorExtensions().entrySet().stream()
            .filter(entry -> annotationGenerators.containsKey(entry.getKey()))
            .flatMap(entry -> {
                Set<GeneratorRecord> generatorRecords = annotationGenerators.get(entry.getKey());
                return generatorRecords.stream()
                        .map(x -> new SimpleEntry<>(x.getKey(), x.getValue().apply((String) entry.getValue())));
            }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    property.vendorExtensions.putAll(extensions);
    return property;
}
 
Example #11
Source File: SwaggerGeneratorAugmentationsTestIt.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
@org.junit.Test
public void testInheritenceWithAugmentation() {
    swaggerFor(p -> p.getParent().getFileName().toString().equals("inheritence-with-augmentation"));


    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 #12
Source File: SwaggerGeneratorWithOdlPathHandlerTest.java    From yang2swagger with Eclipse Public License 1.0 6 votes vote down vote up
@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 #13
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static boolean isFileParameter(Parameter parameter) {
  if (!(parameter instanceof FormParameter)) {
    return false;
  }

  FormParameter formParameter = (FormParameter) parameter;
  if (FileProperty.isType(formParameter.getType(), formParameter.getFormat())) {
    return true;
  }

  Property property = formParameter.getItems();
  if (!ArrayProperty.isType(formParameter.getType()) || property == null) {
    return false;
  }

  return FileProperty.isType(property.getType(), property.getFormat());
}
 
Example #14
Source File: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param operation
 * @return
 */
private String getInterfaceReturnType(Operation operation) {
	String returnType = "void";

	Map<String, Response> responses = operation.getResponses();
	for (Map.Entry<String, Response> responsesEntry : responses.entrySet()) {
		String responseCode = responsesEntry.getKey();

		if (!(responseCode.equalsIgnoreCase("default") || Integer.parseInt(responseCode) >= 300)) {
			Property responseProperty = responsesEntry.getValue().getSchema();

			if (responseProperty instanceof RefProperty) {
				returnType = ((RefProperty) responseProperty).getSimpleRef();
			} else if (responseProperty instanceof ArrayProperty) {
				Property arrayResponseProperty = ((ArrayProperty) responseProperty).getItems();
				if (arrayResponseProperty instanceof RefProperty) {
					returnType = new StringBuilder().append(((RefProperty) arrayResponseProperty).getSimpleRef())
							.append("[]").toString();
				}
			} else if (responseProperty instanceof ObjectProperty) {
				returnType = new StringBuilder().append(toTitleCase(operation.getOperationId())).append("Generated")
						.toString();
			}
		}
	}

	return returnType;
}
 
Example #15
Source File: ModelDiff.java    From swagger-diff with Apache License 2.0 5 votes vote down vote up
private Model findModel(Property property, Map<String, Model> modelMap) {
    String modelName = null;
    if (property instanceof RefProperty) {
        modelName = ((RefProperty) property).getSimpleRef();
    } else if (property instanceof ArrayProperty) {
        Property arrayType = ((ArrayProperty) property).getItems();
        if (arrayType instanceof RefProperty) {
            modelName = ((RefProperty) arrayType).getSimpleRef();
        }
    }
    return modelName == null ? null : modelMap.get(modelName);
}
 
Example #16
Source File: TypeBuilder.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/** Returns the {@link TypeInfo} corresponding to the property. */
public TypeInfo getTypeInfo(Service.Builder serviceBuilder, Property prop) {
  if (prop == null) {
    // TODO(user): How do we handle such cases. May be schema validation at the beginning is
    // the solution.
    return null;
  }
  Property arrayItems = prop instanceof ArrayProperty ? ((ArrayProperty) prop).getItems() : null;
  return getTypeInfo(serviceBuilder, prop.getType(), prop.getFormat(), prop, arrayItems);
}
 
Example #17
Source File: PropertyAdapter.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a default example value for property.
 *
 * @param property         property
 * @param markupDocBuilder doc builder
 * @return a generated example for the property
 */
public static Object generateExample(Property property, MarkupDocBuilder markupDocBuilder) {

    if (property.getType() == null) {
        return "untyped";
    }

    switch (property.getType()) {
        case "integer":
            return ExamplesUtil.generateIntegerExample(property instanceof IntegerProperty ? ((IntegerProperty) property).getEnum() : null);
        case "number":
            return 0.0;
        case "boolean":
            return true;
        case "string":
            return ExamplesUtil.generateStringExample(property.getFormat(), property instanceof StringProperty ? ((StringProperty) property).getEnum() : null);
        case "ref":
            if (property instanceof RefProperty) {
                if (logger.isDebugEnabled()) logger.debug("generateExample RefProperty for " + property.getName());
                return markupDocBuilder.copy(false).crossReference(((RefProperty) property).getSimpleRef()).toString();
            } else {
                if (logger.isDebugEnabled()) logger.debug("generateExample for ref not RefProperty");
            }
        case "array":
            if (property instanceof ArrayProperty) {
                return generateArrayExample((ArrayProperty) property, markupDocBuilder);
            }
        default:
            return property.getType();
    }
}
 
Example #18
Source File: PropertyAdapter.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Generate example for an ArrayProperty
 *
 * @param property ArrayProperty to generate example for
 * @param markupDocBuilder MarkupDocBuilder containing all associated settings
 * @return String example
 */
private static Object generateArrayExample(ArrayProperty property, MarkupDocBuilder markupDocBuilder) {
    Property itemProperty = property.getItems();
    List<Object> exampleArray = new ArrayList<>();

    exampleArray.add(generateExample(itemProperty, markupDocBuilder));
    return exampleArray;
}
 
Example #19
Source File: ResponseContainerConverter.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
Property withResponseContainer(String responseContainer, Property property) {
    if ("list".equalsIgnoreCase(responseContainer)) {
        return new ArrayProperty(property);
    }
    if ("set".equalsIgnoreCase(responseContainer)) {
        return new ArrayProperty(property).uniqueItems();
    }
    if ("map".equalsIgnoreCase(responseContainer)) {
        return new MapProperty(property);
    }
    return property;
}
 
Example #20
Source File: JaxRs2Extension.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Property enforcePrimitive(final Property in, final int level) {
    if (in instanceof RefProperty) {
        return new StringProperty();
    }
    if (in instanceof ArrayProperty) {
        if (level == 0) {
            final ArrayProperty array = (ArrayProperty) in;
            array.setItems(enforcePrimitive(array.getItems(), level + 1));
        } else {
            return new StringProperty();
        }
    }
    return in;
}
 
Example #21
Source File: PropertyAdapter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public Property getArrayItem() {
  if (property instanceof ArrayProperty) {
    return ((ArrayProperty) property).getItems();
  }

  return null;
}
 
Example #22
Source File: TestFormProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private FormProcessor createProcessor(String name, Type type, String defaultValue, boolean required) {
  JavaType javaType = TypeFactory.defaultInstance().constructType(type);

  FormParameter formParameter = new FormParameter();
  formParameter.name(name)
      .required(required)
      .setDefaultValue(defaultValue);

  if (javaType.isContainerType()) {
    formParameter.type(ArrayProperty.TYPE);
  }
  return new FormProcessor(formParameter, javaType);
}
 
Example #23
Source File: TestQueryProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private ParamValueProcessor createProcessor(String name, Class<?> type, String defaultValue, boolean required,
    String collectionFormat) {
  JavaType javaType = TypeFactory.defaultInstance().constructType(type);

  QueryParameter queryParameter = new QueryParameter();
  queryParameter.name(name)
      .required(required)
      .collectionFormat(collectionFormat)
      .setDefaultValue(defaultValue);

  if (javaType.isContainerType()) {
    queryParameter.type(ArrayProperty.TYPE);
  }
  return new QueryProcessor(queryParameter, javaType);
}
 
Example #24
Source File: TestHeaderProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private HeaderProcessor createProcessor(String name, Type type, String defaultValue, boolean required) {
  JavaType javaType = TypeFactory.defaultInstance().constructType(type);

  HeaderParameter headerParameter = new HeaderParameter();
  headerParameter.name(name)
      .required(required)
      .setDefaultValue(defaultValue);

  if (javaType.isContainerType()) {
    headerParameter.type(ArrayProperty.TYPE);
  }
  return new HeaderProcessor(headerParameter, javaType);
}
 
Example #25
Source File: FormProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
PartProcessor(FormParameter formParameter, Type genericParamType) {
  super(formParameter.getName(), null, formParameter.getDefaultValue(), formParameter.getRequired());

  this.genericParamType = genericParamType;
  this.repeatedType = ArrayProperty.isType(formParameter.getType());
  initConverter(genericParamType);
}
 
Example #26
Source File: QueryProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public QueryProcessor(QueryParameter queryParameter, JavaType targetType) {
  super(queryParameter.getName(), targetType, queryParameter.getDefaultValue(), queryParameter.getRequired());

  this.repeatedType = ArrayProperty.isType(queryParameter.getType());
  if (StringUtils.isNotEmpty(queryParameter.getCollectionFormat())) {
    this.collectionFormat = SwaggerParamCollectionFormat
        .valueOf(queryParameter.getCollectionFormat().toUpperCase());
  }
}
 
Example #27
Source File: OpenApiTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
protected void applyArrayAnnotationDetails(ArrayProperty schema, Annotation annotation) {
	if (annotation instanceof Size) {
		schema.setMinItems(((Size) annotation).min());
		schema.setMaxItems(((Size) annotation).max());
	} else if (annotation instanceof Deprecated) {
		schema.setVendorExtension("x-deprecated", true);
	}
}
 
Example #28
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static boolean isComplexProperty(Property property) {
  if (property instanceof RefProperty || property instanceof ObjectProperty || property instanceof MapProperty) {
    return true;
  }

  if (ArrayProperty.class.isInstance(property)) {
    return isComplexProperty(((ArrayProperty) property).getItems());
  }

  return false;
}
 
Example #29
Source File: SwaggerReader.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
public List<Parameter> extractParameters(Annotation[] annotations, Type type)
{
    String defaultValue = null;

    List<Parameter> parameters = new ArrayList<>();
    Parameter parameter = null;

    for (Annotation annotation : annotations) {
        if (annotation instanceof ApiParam) {
            FormParameter qp = new FormParameter()
                    .name(((ApiParam) annotation).value());
            qp.setDefaultValue(defaultValue);
            Property schema = modelConverters.readAsProperty(type);
            if (schema != null) {
                qp.setProperty(schema);
                if (schema instanceof ArrayProperty) {
                    qp.setItems(((ArrayProperty) schema).getItems());
                }
            }
            parameter = qp;
        }
    }
    if (parameter != null) {
        parameters.add(parameter);
    }

    return parameters;
}
 
Example #30
Source File: SwaggerRefHelper.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
public static Stream<String> toUses(Property p) {
    if(p instanceof RefProperty) return Stream.of(((RefProperty)p).getSimpleRef());
    if(p instanceof ArrayProperty) return toUses(((ArrayProperty)p).getItems());

    if(p instanceof ObjectProperty) {
        return ((ObjectProperty)p).getProperties().values().stream()
                .flatMap(SwaggerRefHelper::toUses);
    }

    return Stream.empty();
}