Java Code Examples for io.swagger.v3.oas.models.media.Schema#getEnum()

The following examples show how to use io.swagger.v3.oas.models.media.Schema#getEnum() . 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: Swift4Codegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public String toDefaultValue(Schema p) {
    if (p.getEnum() != null && !p.getEnum().isEmpty()) {
        if (p.getDefault() != null) {
            if (ModelUtils.isStringSchema(p)) {
                return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType());
            } else {
                return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType());
            }
        }
    }
    if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + escapeText((String) p.getDefault()) + "\"";
        }
    }
    return null;
}
 
Example 2
Source File: Swift5ClientCodegen.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public String toDefaultValue(Schema p) {
    if (p.getEnum() != null && !p.getEnum().isEmpty()) {
        if (p.getDefault() != null) {
            if (ModelUtils.isStringSchema(p)) {
                return "." + toEnumVarName(escapeText((String) p.getDefault()), p.getType());
            } else {
                return "." + toEnumVarName(escapeText(p.getDefault().toString()), p.getType());
            }
        }
    }
    if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + escapeText((String) p.getDefault()) + "\"";
        }
    }
    return null;
}
 
Example 3
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private FieldSpec.Builder parseTypeBasedSchema(String fieldName, Schema innerSchema, String targetPackage,
									   TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getEnum() != null) {
		typeSpecBuilder.addType(createEnumClass(StringUtils.capitalize(fieldName), innerSchema).build());
		return createSimpleFieldSpec(null, StringUtils.capitalize(fieldName), fieldName, typeSpecBuilder);
	}
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return getStringBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleFieldSpec(JAVA_LANG_PKG, "Boolean", fieldName, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems(), targetPackage)
		);
		enrichWithGetSetList(typeSpecBuilder, listParameterizedTypeName, fieldName);
		return FieldSpec.builder(listParameterizedTypeName, fieldName, Modifier.PRIVATE);
	}
	return createSimpleFieldSpec(JAVA_LANG_PKG, "Object", fieldName, typeSpecBuilder);
}
 
Example 4
Source File: CLibcurlClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenProperty fromProperty(String name, Schema p) {
    CodegenProperty cm = super.fromProperty(name,p);
    Schema ref = ModelUtils.getReferencedSchema(openAPI, p);
    if (ref != null) {
       if (ref.getEnum() != null) {
           cm.isEnum = true;
       }
    }
    return cm;
}
 
Example 5
Source File: TypeScriptJqueryClientCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public String getSchemaType(Schema p) {
    String openAPIType = super.getSchemaType(p);
    if (ModelUtils.isStringSchema(p)) {
        if (p.getEnum() != null) {
            return openAPIType;
        }
    }
    if (isLanguagePrimitive(openAPIType) || isLanguageGenericType(openAPIType)) {
        return openAPIType;
    }
    return addModelPrefix(openAPIType);
}
 
Example 6
Source File: StringTypeValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public Set<String> validateAllowedValues(Object argument, Schema schema){
    if (argument != null && schema != null) {
        if (schema.getEnum() != null && schema.getEnum().size() > 0) {
            List<?> values = schema.getEnum();
            Set<String> allowable = new LinkedHashSet<>();
            for (Object obj : values) {
                allowable.add(obj.toString());
            }
            if (!allowable.contains(argument.toString())) {
                return allowable;
            }
        }
    }
    return  null;
}
 
Example 7
Source File: OpenApiHelpers.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
public static String getSchemaTypeAsString(Schema schema) {
    StringBuilder stringBuilder = new StringBuilder();
    if (schema instanceof ArraySchema) {
        stringBuilder.append("< ");
        Schema<?> items = ((ArraySchema) schema).getItems();
        stringBuilder.append(getSchemaType(items));
        stringBuilder.append(" > ");
        stringBuilder.append(schema.getType());
    } else {
        List enumList = schema.getEnum();
        if (enumList != null) {
            stringBuilder.append("enum (");
            for (Object value : enumList) {
                stringBuilder.append(value.toString());
                stringBuilder.append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append(')');
        } else {
            stringBuilder.append(getSchemaType(schema));
            String format = schema.getFormat();
            if (format != null) {
                stringBuilder.append(' ');
                stringBuilder.append('(');
                stringBuilder.append(format);
                stringBuilder.append(')');
            }
        }
    }
    return stringBuilder.toString();
}
 
Example 8
Source File: NumericValidator.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
public Set<String> validateEnum(Object argument, Schema schema){
    if(schema.getEnum() != null && schema.getEnum().size() > 0) {
        List<?> values = schema.getEnum();
        Set<String> allowable = new LinkedHashSet<String>();
        for(Object obj : values) {
            allowable.add(obj.toString());
        }
        if(!allowable.contains(argument.toString())) {
            return allowable;
        }
    }
    return null;
}
 
Example 9
Source File: AbstractTypeScriptClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
protected String getParameterDataType(Parameter parameter, Schema p) {
    // handle enums of various data types
    Schema inner;
    if (ModelUtils.isArraySchema(p)) {
        ArraySchema mp1 = (ArraySchema) p;
        inner = mp1.getItems();
        return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
    } else if (ModelUtils.isMapSchema(p)) {
        inner = getAdditionalProperties(p);
        return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
    } else if (ModelUtils.isStringSchema(p)) {
        // Handle string enums
        if (p.getEnum() != null) {
            return enumValuesToEnumTypeUnion(p.getEnum(), "string");
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        // Handle integer enums
        if (p.getEnum() != null) {
            return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
        }
    } else if (ModelUtils.isNumberSchema(p)) {
        // Handle double enums
        if (p.getEnum() != null) {
            return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
        }
    }
    /* TODO revise the logic below
    else if (ModelUtils.isDateSchema(p)) {
        // Handle date enums
        DateSchema sp = (DateSchema) p;
        if (sp.getEnum() != null) {
            return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
        }
    } else if (ModelUtils.isDateTimeSchema(p)) {
        // Handle datetime enums
        DateTimeSchema sp = (DateTimeSchema) p;
        if (sp.getEnum() != null) {
            return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
        }
    }*/
    return this.getTypeDeclaration(p);
}
 
Example 10
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeserializeByteString() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title: My Title\n" +
            "paths:\n" +
            "  /persons:\n" +
            "    get:\n" +
            "      description: a test\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: Successful response\n" +
            "          content:\n" +
            "            '*/*':\n" +
            "              schema:\n" +
            "                type: object\n" +
            "                properties:\n" +
            "                  bytes:\n" +
            "                    $ref: '#/components/schemas/ByteString'\n" +
            "components:\n" +
            "  schemas:\n" +
            "    ByteString:\n" +
            "      type: string\n" +
            "      format: byte\n" +
            "      default: W.T.F?\n" +
            "      enum:\n" +
            "        - VGhlIHdvcmxk\n" +
            "        - aXMgYWxs\n" +
            "        - dGhhdCBpcw==\n" +
            "        - dGhlIGNhc2U=\n" +
            "        - W.T.F?\n" +
            "";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);

    final OpenAPI resolved = new OpenAPIResolver(result.getOpenAPI(), null).resolve();

    Schema byteModel = resolved.getComponents().getSchemas().get("ByteString");
    assertTrue(byteModel instanceof ByteArraySchema);
    List<byte[]> byteValues = byteModel.getEnum();
    assertEquals(byteValues.size(), 4);
    assertEquals(new String( byteValues.get(0)), "The world");
    assertEquals(new String( byteValues.get(1)), "is all");
    assertEquals(new String( byteValues.get(2)), "that is");
    assertEquals(new String( byteValues.get(3)), "the case");

    assertEquals( byteModel.getDefault(), null);

    assertEquals(
      result.getMessages(),
      Arrays.asList(
        "attribute components.schemas.ByteString.enum=`W.T.F?` is not of type `byte`",
        "attribute components.schemas.ByteString.default=`W.T.F?` is not of type `byte`"));
}
 
Example 11
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeserializeDateTimeString() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title: My Title\n" +
            "paths:\n" +
            "  /persons:\n" +
            "    get:\n" +
            "      description: a test\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: Successful response\n" +
            "          content:\n" +
            "            '*/*':\n" +
            "              schema:\n" +
            "                type: object\n" +
            "                properties:\n" +
            "                  dateTime:\n" +
            "                    $ref: '#/components/schemas/DateTimeString'\n" +
            "components:\n" +
            "  schemas:\n" +
            "    DateTimeString:\n" +
            "      type: string\n" +
            "      format: date-time\n" +
            "      default: 2019-01-01T00:00:00Z\n" +
            "      enum:\n" +
            "        - null\n" +
            "        - Nunh uh\n" +
            "        - 2019-01-01T00:00:00Z\n" +
            "        - 2018-02-02T23:59:59.999-05:00\n" +
            "        - 2017-03-03T11:22:33+06:00\n" +
            "        - 2016-04-04T22:33:44.555Z\n" +
            "";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);

    final OpenAPI resolved = new OpenAPIResolver(result.getOpenAPI(), null).resolve();

    Schema dateTimeModel = resolved.getComponents().getSchemas().get("DateTimeString");
    assertTrue(dateTimeModel instanceof DateTimeSchema);
    List<OffsetDateTime> dateTimeValues = dateTimeModel.getEnum();
    assertEquals(dateTimeValues.size(), 5);
    assertEquals(
      dateTimeValues.get(0),
      null);
    assertEquals(
        dateTimeValues.get(1),
        OffsetDateTime.of(2019,1,1,0,0,0,0, ZoneOffset.UTC));

    assertEquals(
        dateTimeValues.get(2),
        OffsetDateTime.of(2018,2,2,23,59,59,999000000, ZoneOffset.ofHours(-5)));

    assertEquals(
        dateTimeValues.get(3),
        OffsetDateTime.of(2017,3,3,11,22,33,0, ZoneOffset.ofHours(6)));

    assertEquals(
        dateTimeValues.get(4),
        OffsetDateTime.of(2016,4,4,22,33,44,555000000, ZoneOffset.UTC));

    assertEquals(
            dateTimeModel.getDefault(),
            OffsetDateTime.of(2019,1,1,0,0,0,0, ZoneOffset.UTC));

    assertEquals(
      result.getMessages(),
      Arrays.asList( "attribute components.schemas.DateTimeString.enum=`Nunh uh` is not of type `date-time`"));
}
 
Example 12
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeserializeDateString() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title: My Title\n" +
            "paths:\n" +
            "  /persons:\n" +
            "    get:\n" +
            "      description: a test\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: Successful response\n" +
            "          content:\n" +
            "            '*/*':\n" +
            "              schema:\n" +
            "                type: object\n" +
            "                properties:\n" +
            "                  date:\n" +
            "                    $ref: '#/components/schemas/DateString'\n" +
            "components:\n" +
            "  schemas:\n" +
            "    DateString:\n" +
            "      type: string\n" +
            "      format: date\n" +
            "      default: 2019-01-01\n" +
            "      enum:\n" +
            "        - 2019-01-01\n" +
            "        - Nope\n" +
            "        - 2018-02-02\n" +
            "        - 2017-03-03\n" +
            "        - null\n" +
            "";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);

    final OpenAPI resolved = new OpenAPIResolver(result.getOpenAPI(), null).resolve();

    Schema dateModel = resolved.getComponents().getSchemas().get("DateString");
    assertTrue(dateModel instanceof DateSchema);
    List<Date> dateValues = dateModel.getEnum();
    assertEquals(dateValues.size(), 4);
    assertEquals(
      dateValues.get(0),
      new Calendar.Builder().setDate( 2019, 0, 1).build().getTime());
    assertEquals(
      dateValues.get(1),
      new Calendar.Builder().setDate( 2018, 1, 2).build().getTime());
    assertEquals(
      dateValues.get(2),
      new Calendar.Builder().setDate( 2017, 2, 3).build().getTime());
    assertEquals(
      dateValues.get(3),
      null);

    assertEquals(
      dateModel.getDefault(),
      new Calendar.Builder().setDate( 2019, 0, 1).build().getTime());

    assertEquals(
      result.getMessages(),
      Arrays.asList( "attribute components.schemas.DateString.enum=`Nope` is not of type `date`"));
}
 
Example 13
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeserializeEnum() {
    String yaml = "openapi: 3.0.0\n" +
            "servers: []\n" +
            "info:\n" +
            "  version: 0.0.0\n" +
            "  title: your title\n" +
            "paths:\n" +
            "  /persons:\n" +
            "    get:\n" +
            "      description: a test\n" +
            "      responses:\n" +
            "        '200':\n" +
            "          description: Successful response\n" +
            "          content:\n" +
            "            '*/*':\n" +
            "              schema:\n" +
            "                type: object\n" +
            "                properties:\n" +
            "                  se:\n" +
            "                    $ref: '#/components/schemas/StringEnum'\n" +
            "                  ie:\n" +
            "                    $ref: '#/components/schemas/IntegerEnum'\n" +
            "                  ne:\n" +
            "                    $ref: '#/components/schemas/NumberEnum'\n" +
            "                  be:\n" +
            "                    $ref: '#/components/schemas/BooleanEnum'\n" +
            "components:\n" +
            "  schemas:\n" +
            "    StringEnum:\n" +
            "      type: string\n" +
            "      default: foo\n" +
            "      enum:\n" +
            "        - First\n" +
            "        - Second\n" +
            "    BooleanEnum:\n" +
            "      enum:\n" +
            "        - true \n" +
            "        - false \n" +
            "    IntegerEnum:\n" +
            "      type: integer\n" +
            "      default: 1\n" +
            "      enum:\n" +
            "        - -1\n" +
            "        - 0\n" +
            "        - 1\n" +
            "    NumberEnum:\n" +
            "      type: number\n" +
            "      default: 3.14\n" +
            "      enum:\n" +
            "        - -1.151\n" +
            "        - 0\n" +
            "        - 1.6161\n" +
            "        - 3.14";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);

    final OpenAPI resolved = new OpenAPIResolver(result.getOpenAPI(), null).resolve();

    Schema stringModel = resolved.getComponents().getSchemas().get("StringEnum");
    assertTrue(stringModel instanceof Schema);
    Schema stringImpl = stringModel;
    List<String> stringValues = stringImpl.getEnum();
    assertEquals(2, stringValues.size());
    assertEquals("First", stringValues.get(0));
    assertEquals("Second", stringValues.get(1));

    Schema integerModel = resolved.getComponents().getSchemas().get("IntegerEnum");
    assertTrue(integerModel instanceof Schema);
    Schema integerImpl =  integerModel;
    List<String> integerValues = integerImpl.getEnum();
    assertEquals(3, integerValues.size());
    assertEquals(-1, integerValues.get(0));
    assertEquals(0, integerValues.get(1));
    assertEquals(1, integerValues.get(2));
    assertEquals(integerImpl.getDefault(), 1);

    Schema numberModel = resolved.getComponents().getSchemas().get("NumberEnum");
    assertTrue(numberModel instanceof Schema);
    Schema numberImpl =  numberModel;
    List<String> numberValues = numberImpl.getEnum();
    assertEquals(4, numberValues.size());
    assertEquals(new BigDecimal("-1.151"), numberValues.get(0));
    assertEquals(new BigDecimal("0"), numberValues.get(1));
    assertEquals(new BigDecimal("1.6161"), numberValues.get(2));
    assertEquals(new BigDecimal("3.14"), numberValues.get(3));
    assertEquals(numberImpl.getDefault(), new BigDecimal("3.14"));
    
    Schema booleanModel = resolved.getComponents().getSchemas().get("BooleanEnum");
    assertEquals("boolean", booleanModel.getType());
    List<Object> booleanValues = booleanModel.getEnum();
    assertEquals(2, booleanValues.size());
    assertEquals(Boolean.TRUE, booleanValues.get(0));
    assertEquals(Boolean.FALSE, booleanValues.get(1));
}
 
Example 14
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Schema mergeSchema(Schema thisSchema, Schema thatSchema) {
  if (thatSchema == null) {
    return thisSchema;
  }
  // Overwriting `implementation` is explicitly disallowed
  // Overwriting `not` is explicitly disallowed
  // Overwriting `oneOf` is explicitly disallowed
  // Overwriting `anyOf` is explicitly disallowed
  // Overwriting `allOf` is explicitly disallowed
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getTitle() != null) {
    thisSchema.setTitle(thatSchema.getTitle());
  }
  // Overwriting `multipleOf` is explicitly disallowed
  if (thatSchema.getMaximum() != null) {
    thisSchema.setMaximum(thatSchema.getMaximum());
  }
  if (thatSchema.getExclusiveMaximum() != null) {
    thisSchema.setExclusiveMaximum(thatSchema.getExclusiveMaximum());
  }

  if (thatSchema.getMinimum() != null) {
    thisSchema.setMinimum(thatSchema.getMinimum());
  }
  if (thatSchema.getExclusiveMinimum() != null) {
    thisSchema.setExclusiveMinimum(thatSchema.getExclusiveMinimum());
  }
  if (thatSchema.getMaxLength() != null) {
    thisSchema.setMaxLength(thatSchema.getMaxLength());
  }
  if (thatSchema.getMinLength() != null) {
    thisSchema.setMinLength(thatSchema.getMinLength());
  }
  if (thatSchema.getPattern() != null) {
    thisSchema.setPattern(thatSchema.getPattern());
  }
  if (thatSchema.getMaxProperties() != null) {
    thisSchema.setMaxProperties(thatSchema.getMaxProperties());
  }
  if (thatSchema.getMinProperties() != null) {
    thisSchema.setMinProperties(thatSchema.getMinProperties());
  }
  // RequiredProperties
  if (thatSchema.getRequired() != null) {
    thisSchema.setRequired(thatSchema.getRequired());
  }
  // Overwriting `name` is explicitly disallowed
  if (thatSchema.getDescription() != null) {
    thisSchema.setDescription(thatSchema.getDescription());
  }
  if (thatSchema.getFormat() != null) {
    thisSchema.setFormat(thatSchema.getFormat());
  }
  // Overwriting `ref` is explicitly disallowed
  if (thatSchema.getNullable() != null) {
    thisSchema.setNullable(thatSchema.getNullable());
  }
  // Overwriting `AccessMode` is explicitly disallowed
  if (thatSchema.getExample() != null) {
    thisSchema.setExample(thatSchema.getExample());
  }
  if (thatSchema.getExternalDocs() != null) {
    thisSchema.setExternalDocs(thatSchema.getExternalDocs());
  }
  if (thatSchema.getDeprecated() != null) {
    thisSchema.setDeprecated(thatSchema.getDeprecated());
  }
  if (thatSchema.getType() != null) {
    thisSchema.setType(thatSchema.getType());
  }
  if (thatSchema.getEnum() != null) {
    thisSchema.setEnum(thatSchema.getEnum());
  }
  if (thatSchema.getDefault() != null) {
    thisSchema.setDefault(thatSchema.getDefault());
  }
  // Overwriting `discriminator` is explicitly disallowed
  // Overwriting `hidden` is explicitly disallowed
  // Overwriting `subTypes` is explicitly disallowed
  if (thatSchema.getExtensions() != null) {
    thisSchema.setExtensions(thatSchema.getExtensions());
  }
  return thisSchema;
}
 
Example 15
Source File: AbstractFSharpCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Return the default value of the property
 *
 * @param p OpenAPI property object
 * @return string presentation of the default value of the property
 */
@Override
public String toDefaultValue(Schema p) {
    if (ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isDateSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + p.getDefault().toString() + "\"";
        }
    } else if (ModelUtils.isDateTimeSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + p.getDefault().toString() + "\"";
        }
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getDefault() != null) {
            if (ModelUtils.isFloatSchema(p)) { // float
                return p.getDefault().toString() + "F";
            } else if (ModelUtils.isDoubleSchema(p)) { // double
                return p.getDefault().toString() + "D";
            } else {    // decimal
                return p.getDefault().toString() + "M";
            }
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            String _default = (String) p.getDefault();
            if (p.getEnum() == null) {
                return "\"" + _default + "\"";
            } else {
                // convert to enum var name later in postProcessModels
                return _default;
            }
        }
    }

    return null;
}
 
Example 16
Source File: AbstractCSharpCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Return the default value of the property
 * @param p OpenAPI property object
 * @return string presentation of the default value of the property
 */
@Override
public String toDefaultValue(Schema p) {
    if (ModelUtils.isBooleanSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isDateSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + p.getDefault().toString() + "\"";
        }
    } else if (ModelUtils.isDateTimeSchema(p)) {
        if (p.getDefault() != null) {
            return "\"" + p.getDefault().toString() + "\"";
        }
    } else if (ModelUtils.isNumberSchema(p)) {
        if (p.getDefault() != null) {
            if (ModelUtils.isFloatSchema(p)) { // float
                return p.getDefault().toString() + "F";
            } else if (ModelUtils.isDoubleSchema(p)) { // double
                return p.getDefault().toString() + "D";
            } else {    // decimal
                return p.getDefault().toString() + "M";
            }
        }
    } else if (ModelUtils.isIntegerSchema(p)) {
        if (p.getDefault() != null) {
            return p.getDefault().toString();
        }
    } else if (ModelUtils.isStringSchema(p)) {
        if (p.getDefault() != null) {
            String _default = (String) p.getDefault();
            if (p.getEnum() == null) {
                return "\"" + _default + "\"";
            } else {
                // convert to enum var name later in postProcessModels
                return _default;
            }
        }
    }

    return null;
}
 
Example 17
Source File: AbstractApexCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
public String toExampleValue(Schema p) {
    if (p == null) {
        return "";
    }

    Object obj = p.getExample();
    String example = obj == null ? "" : obj.toString();

    if (ModelUtils.isArraySchema(p)) {
        example = "new " + getTypeDeclaration(p) + "{" + toExampleValue(
                ((ArraySchema) p).getItems()) + "}";
    } else if (ModelUtils.isBooleanSchema(p)) {
        example = String.valueOf(!"false".equals(example));
    } else if (ModelUtils.isByteArraySchema(p)) {
        if (example.isEmpty()) {
            example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
        }
        p.setExample(example);
        example = "EncodingUtil.base64Decode('" + example + "')";
    } else if (ModelUtils.isDateSchema(p)) {
        if (example.matches("^\\d{4}(-\\d{2}){2}")) {
            example = example.substring(0, 10).replaceAll("-0?", ", ");
        } else if (example.isEmpty()) {
            example = "2000, 1, 23";
        } else {
            LOGGER.warn(String.format(Locale.ROOT, "The example provided for property '%s' is not a valid RFC3339 date. Defaulting to '2000-01-23'. [%s]", p
                    .getName(), example));
            example = "2000, 1, 23";
        }
        example = "Date.newInstance(" + example + ")";
    } else if (ModelUtils.isDateTimeSchema(p)) {
        if (example.matches("^\\d{4}([-T:]\\d{2}){5}.+")) {
            example = example.substring(0, 19).replaceAll("[-T:]0?", ", ");
        } else if (example.isEmpty()) {
            example = "2000, 1, 23, 4, 56, 7";
        } else {
            LOGGER.warn(String.format(Locale.ROOT, "The example provided for property '%s' is not a valid RFC3339 datetime. Defaulting to '2000-01-23T04-56-07Z'. [%s]", p
                    .getName(), example));
            example = "2000, 1, 23, 4, 56, 7";
        }
        example = "Datetime.newInstanceGmt(" + example + ")";
    } else if (ModelUtils.isNumberSchema(p)) {
        example = example.replaceAll("[^-0-9.]", "");
        example = example.isEmpty() ? "1.3579" : example;
    } else if (ModelUtils.isFileSchema(p)) {
        if (example.isEmpty()) {
            example = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu";
            p.setExample(example);
        }
        example = "EncodingUtil.base64Decode(" + example + ")";
    } else if (ModelUtils.isEmailSchema(p)) {
        if (example.isEmpty()) {
            example = "[email protected]";
            p.setExample(example);
        }
        example = "'" + example + "'";
    } else if (ModelUtils.isLongSchema(p)) {
        example = example.isEmpty() ? "123456789L" : example + "L";
    } else if (ModelUtils.isMapSchema(p)) {
        example = "new " + getTypeDeclaration(p) + "{'key'=>" + toExampleValue(getAdditionalProperties(p)) + "}";

    } else if (ModelUtils.isPasswordSchema(p)) {
        example = example.isEmpty() ? "password123" : escapeText(example);
        p.setExample(example);
        example = "'" + example + "'";
    } else if (ModelUtils.isStringSchema(p)) {
        List<String> enums = p.getEnum();
        if (enums != null && example.isEmpty()) {
            example = enums.get(0);
            p.setExample(example);
        } else if (example.isEmpty()) {
            example = "";
        } else {
            example = escapeText(example);
            p.setExample(example);
        }
        example = "'" + example + "'";
    } else if (ModelUtils.isUUIDSchema(p)) {
        example = example.isEmpty()
                ? "'046b6c7f-0b8a-43b9-b35d-6489e6daee91'"
                : "'" + escapeText(example) + "'";
    } else if (ModelUtils.isIntegerSchema(p)) {
        example = example.matches("^-?\\d+$") ? example : "0";
    } else if (ModelUtils.isObjectSchema(p)) {
        example = example.isEmpty() ? "null" : example;
    } else {
        example = getTypeDeclaration(p) + ".getExample()";
    }
    return example;
}
 
Example 18
Source File: CLibcurlClientCodegen.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
@Override
    public String toExampleValue(Schema schema) {
        String example = super.toExampleValue(schema);

        if (ModelUtils.isNullType(schema) && null != example) {
            // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x,
            // though this tooling supports it.
            return "NULL";
        }
        // correct "&#39;"s into "'"s after toString()
        if (ModelUtils.isStringSchema(schema) && schema.getDefault() != null) {
            example = (String) schema.getDefault();
        }
        if (StringUtils.isNotBlank(example) && !"null".equals(example)) {
            if (ModelUtils.isStringSchema(schema)) {
                example = "\"" + example + "\"";
            }
            return example;
        }

        if (schema.getEnum() != null && !schema.getEnum().isEmpty()) {
        // Enum case:
            example = schema.getEnum().get(0).toString();
/*            if (ModelUtils.isStringSchema(schema)) {
                example = "'" + escapeText(example) + "'";
            }*/
            if (null == example)
                LOGGER.warn("Empty enum. Cannot built an example!");

            return example;
        } else if (null != schema.get$ref()) {
        // $ref case:
            Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
            String ref = ModelUtils.getSimpleRef(schema.get$ref());
            if (allDefinitions != null) {
                Schema refSchema = allDefinitions.get(ref);
                if (null == refSchema) {
                    return "None";
                } else {
                    String refTitle = refSchema.getTitle();
                    if (StringUtils.isBlank(refTitle) || "null".equals(refTitle)) {
                        refSchema.setTitle(ref);
                    }
                    return toExampleValue(refSchema);
                }
            } else {
                LOGGER.warn("allDefinitions not defined in toExampleValue!\n");
            }
        }
        if (ModelUtils.isDateSchema(schema)) {
            example = "\"2013-10-20\"";
            return example;
        } else if (ModelUtils.isDateTimeSchema(schema)) {
            example = "\"2013-10-20T19:20:30+01:00\"";
            return example;
        } else if (ModelUtils.isBinarySchema(schema)) {
            example = "instantiate_binary_t(\"blah\", 5)";
            return example;
        } else if (ModelUtils.isByteArraySchema(schema)) {
            example = "YQ==";
        } else if (ModelUtils.isStringSchema(schema)) {
            // a BigDecimal:
            if ("Number".equalsIgnoreCase(schema.getFormat())) {return "1";}
            if (StringUtils.isNotBlank(schema.getPattern())) return "\"a\""; // I cheat here, since it would be too complicated to generate a string from a regexp
            int len = 0;
            if (null != schema.getMinLength()) len = schema.getMinLength().intValue();
            if (len < 1) len = 1;
            example = "";
            for (int i=0;i<len;i++) example += i;
        } else if (ModelUtils.isIntegerSchema(schema)) {
            if (schema.getMinimum() != null)
                example = schema.getMinimum().toString();
            else
                example = "56";
        } else if (ModelUtils.isNumberSchema(schema)) {
            if (schema.getMinimum() != null)
                example = schema.getMinimum().toString();
            else
                example = "1.337";
        } else if (ModelUtils.isBooleanSchema(schema)) {
            example = "1";
        } else if (ModelUtils.isArraySchema(schema)) {
            example = "list_create()";
        } else if (ModelUtils.isMapSchema(schema)) {
            example = "list_create()";
        } else if (ModelUtils.isObjectSchema(schema)) {
            return null; // models are managed at moustache level
        } else {
            LOGGER.warn("Type " + schema.getType() + " not handled properly in toExampleValue");
        }

        if (ModelUtils.isStringSchema(schema)) {
            example = "\"" + escapeText(example) + "\"";
        }

        return example;
    }