Java Code Examples for io.swagger.models.Swagger#getDefinitions()

The following examples show how to use io.swagger.models.Swagger#getDefinitions() . 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: PlantUMLCodegen.java    From swagger2puml with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param swagger
 * @return
 */
private List<ClassDiagram> processSwaggerModels(Swagger swagger) {
	LOGGER.entering(LOGGER.getName(), "processSwaggerModels");

	List<ClassDiagram> classDiagrams = new ArrayList<ClassDiagram>();
	Map<String, Model> modelsMap = swagger.getDefinitions();

	for (Map.Entry<String, Model> models : modelsMap.entrySet()) {
		String className = models.getKey();
		Model modelObject = models.getValue();

		LOGGER.info("Processing Model " + className);

		String superClass = getSuperClass(modelObject);
		List<ClassMembers> classMembers = getClassMembers(modelObject, modelsMap);

		classDiagrams.add(new ClassDiagram(className, modelObject.getDescription(), classMembers,
				getChildClasses(classMembers, superClass), isModelClass(modelObject), superClass));
	}

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

	return classDiagrams;
}
 
Example 2
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 3
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;
  }
 
Example 4
Source File: StaticHtmlGenerator.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
public void preprocessSwagger(Swagger swagger) {
    Info info = swagger.getInfo();
    info.setDescription(toHtml(info.getDescription()));
    info.setTitle(toHtml(info.getTitle()));
    Map<String, Model> models = swagger.getDefinitions();
    for (Model model : models.values()) {
        model.setDescription(toHtml(model.getDescription()));
        model.setTitle(toHtml(model.getTitle()));
    }
}
 
Example 5
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 6
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 7
Source File: SwaggerGenerator.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Replace empty definitions with their parents.
 * Sort models (ref models first)
 * @param target to work on
 */
protected void postProcessSwagger(Swagger target) {
    if(target.getDefinitions() == null || target.getDefinitions().isEmpty()) {
        log.warn("Generated swagger has no definitions");
        return;
    }
    postprocessor.accept(target);
}
 
Example 8
Source File: IoCSwaggerGenerator.java    From yang2swagger with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Replace empty definitions with their parents.
 * Sort models (ref models first)
 * @param target to work on
 */
protected void postProcessSwagger(Swagger target) {
    if(target.getDefinitions() == null || target.getDefinitions().isEmpty()) {
        log.warn("Generated swagger has no definitions");
        return;
    }
    postprocessor.accept(target);
}
 
Example 9
Source File: TypeBuilder.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public void addFromSwagger(Service.Builder serviceBuilder, Swagger swagger) {
  if (swagger.getDefinitions() == null) {
    return;
  }
  TreeSet<String> swaggerModelNames = Sets.newTreeSet(swagger.getDefinitions().keySet());
  for (String swaggerModelName : swaggerModelNames) {

    visitedTypes.clear();
    addTypeFromModel(
        serviceBuilder, swaggerModelName, swagger.getDefinitions().get(swaggerModelName));
  }
}
 
Example 10
Source File: SwaggerGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private Map<String, Model> getOrCreateDefinitionMap(Swagger swagger) {
  Map<String, Model> definitions = swagger.getDefinitions();
  if (definitions == null) {
    definitions = new LinkedHashMap<>();
    swagger.setDefinitions(definitions);
  }
  return definitions;
}
 
Example 11
Source File: SwaggerGeneratorTest.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
private void checkOrdering(Swagger expected, Swagger actual) {
  if (expected.getSecurityDefinitions() != null && actual.getSecurityDefinitions() != null) {
    assertThat(ImmutableList.of(expected.getSecurityDefinitions().keySet()))
        .isEqualTo(ImmutableList.of(actual.getSecurityDefinitions().keySet()));
  }
  if (expected.getDefinitions() != null && actual.getDefinitions() != null) {
    assertThat(ImmutableList.of(expected.getDefinitions().keySet()))
        .isEqualTo(ImmutableList.of(actual.getDefinitions().keySet()));
  }
}
 
Example 12
Source File: SwaggerInventory.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public SwaggerInventory process(Swagger swagger) {
    Iterator var2;
    if(swagger.getTags() != null) {
        var2 = swagger.getTags().iterator();

        while(var2.hasNext()) {
            Tag key = (Tag)var2.next();
            this.process(key);
        }
    }

    String key1;
    if(swagger.getPaths() != null) {
        var2 = swagger.getPaths().keySet().iterator();

        while(var2.hasNext()) {
            key1 = (String)var2.next();
            Path model = swagger.getPath(key1);
            this.process(model);
        }
    }

    if(swagger.getDefinitions() != null) {
        var2 = swagger.getDefinitions().keySet().iterator();

        while(var2.hasNext()) {
            key1 = (String)var2.next();
            Model model1 = (Model)swagger.getDefinitions().get(key1);
            this.process(model1);
        }
    }

    return this;
}
 
Example 13
Source File: Utils.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static void sortSwagger(Swagger swagger) throws GenerateException {
    if (swagger == null || swagger.getPaths() == null) {
        return;
    }

    TreeMap<String, Path> sortedMap = new TreeMap<String, Path>();
    if (swagger.getPaths() == null) {
        return;
    }
    sortedMap.putAll(swagger.getPaths());
    swagger.paths(sortedMap);

    for (Path path : swagger.getPaths().values()) {
        String methods[] = {"Get", "Delete", "Post", "Put", "Options", "Patch"};
        for (String m : methods) {
            sortResponses(path, m);
        }
    }

    //reorder definitions
    if (swagger.getDefinitions() != null) {
        TreeMap<String, Model> defs = new TreeMap<String, Model>();
        defs.putAll(swagger.getDefinitions());
        swagger.setDefinitions(defs);
    }

    // order the tags
    if (swagger.getTags() != null) {
        Collections.sort(swagger.getTags(), new Comparator<Tag>() {
            public int compare(final Tag a, final Tag b) {
                return a.toString().toLowerCase().compareTo(b.toString().toLowerCase());
            }
        });
    }

}
 
Example 14
Source File: JaxrsReaderTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void handleResponseWithInheritance() {
    Swagger result = reader.read(AnApiWithInheritance.class);
    Map<String, Model> models = result.getDefinitions();

    Map<String, Property> properties = getProperties(models, "SomeResponseWithAbstractInheritance");
    assertNotNull(properties);
    assertTrue(properties.containsKey("classProperty"));
    assertFalse(properties.containsKey("inheritedProperty"));
    assertFalse(properties.containsKey("type"));

    properties = models.get("SomeResponseBaseClass").getProperties();
    assertNotNull(properties);
    assertTrue(properties.containsKey("inheritedProperty"));
    assertTrue(properties.containsKey("type"));

    properties = getProperties(models, "SomeResponseWithInterfaceInheritance");
    assertNotNull(properties);
    assertTrue(properties.containsKey("classProperty"));
    assertFalse(properties.containsKey("inheritedProperty"));
    assertFalse(properties.containsKey("type"));

    properties = getProperties(models,"SomeResponseInterface");
    assertNotNull(properties);
    assertTrue(properties.containsKey("inheritedProperty"));
    assertTrue(properties.containsKey("type"));

    properties = getProperties(models,"SomeResponse");
    assertNotNull(properties);
    assertTrue(properties.containsKey("classProperty"));
    assertTrue(properties.containsKey("type"));

    properties = getProperties(models,"SomeOtherResponse");
    assertNotNull(properties);
    assertTrue(properties.containsKey("classProperty"));
    assertTrue(properties.containsKey("type"));
}
 
Example 15
Source File: OAS2Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method  generates Sample/Mock payloads for Swagger (2.0) definitions
 *
 * @param swaggerDef Swagger Definition
 * @return Swagger Json
 */
@Override
public Map<String, Object> generateExample(String swaggerDef) {
    // create APIResourceMediationPolicy List = policyList
    SwaggerParser parser = new SwaggerParser();
    SwaggerDeserializationResult parseAttemptForV2 = parser.readWithInfo(swaggerDef);
    Swagger swagger = parseAttemptForV2.getSwagger();
    //return map
    Map<String, Object> returnMap = new HashMap<>();
    //List for APIResMedPolicyList
    List<APIResourceMediationPolicy> apiResourceMediationPolicyList = new ArrayList<>();
    for (Map.Entry<String, Path> entry : swagger.getPaths().entrySet()) {
        int responseCode = 0;
        int minResponseCode = 0;
        String path = entry.getKey();
        //initializing apiResourceMediationPolicyObject
        APIResourceMediationPolicy apiResourceMediationPolicyObject = new APIResourceMediationPolicy();
        //setting path for apiResourceMediationPolicyObject
        apiResourceMediationPolicyObject.setPath(path);
        Map<String, Model> definitions = swagger.getDefinitions();
        //operation map to get verb
        Map<HttpMethod, Operation> operationMap = entry.getValue().getOperationMap();
        List<Operation> operations = swagger.getPaths().get(path).getOperations();
        for (Operation op : operations) {
            ArrayList<Integer> responseCodes = new ArrayList<Integer>();
            //for each HTTP method get the verb
            for (Map.Entry<HttpMethod, Operation> HTTPMethodMap : operationMap.entrySet()) {
                //add verb to apiResourceMediationPolicyObject
                apiResourceMediationPolicyObject.setVerb(String.valueOf(HTTPMethodMap.getKey()));
            }
            StringBuilder genCode = new StringBuilder();
            boolean hasJsonPayload = false;
            boolean hasXmlPayload = false;
            //for setting only one initializing if condition per response code
            boolean respCodeInitialized = false;
            for (String responseEntry : op.getResponses().keySet()) {
                if (!responseEntry.equals("default")) {
                    responseCode = Integer.parseInt(responseEntry);
                    responseCodes.add(responseCode);
                    minResponseCode = Collections.min(responseCodes);
                }
                if (op.getResponses().get(responseEntry).getExamples() != null) {
                    Object applicationJson = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_JSON_MEDIA_TYPE);
                    Object applicationXml = op.getResponses().get(responseEntry).getExamples().get(APPLICATION_XML_MEDIA_TYPE);
                    if (applicationJson != null) {
                        String jsonExample = Json.pretty(applicationJson);
                        genCode.append(getGeneratedResponsePayloads(responseEntry, jsonExample, "json", false));
                        respCodeInitialized = true;
                        hasJsonPayload = true;
                    }
                    if (applicationXml != null) {
                        String xmlExample = applicationXml.toString();
                        genCode.append(getGeneratedResponsePayloads(responseEntry, xmlExample, "xml", respCodeInitialized));
                        hasXmlPayload = true;
                    }
                } else if (op.getResponses().get(responseEntry).getResponseSchema() != null) {
                    Model model = op.getResponses().get(responseEntry).getResponseSchema();
                    String schemaExample = getSchemaExample(model, definitions, new HashSet<String>());
                    genCode.append(getGeneratedResponsePayloads(responseEntry, schemaExample, "json", respCodeInitialized));
                    hasJsonPayload = true;
                } else if (op.getResponses().get(responseEntry).getExamples() == null
                        && op.getResponses().get(responseEntry).getResponseSchema() == null) {
                    setDefaultGeneratedResponse(genCode, responseEntry);
                    hasJsonPayload = true;
                    hasXmlPayload = true;
                }
            }
            //inserts minimum response code and mock payload variables to static script
            String finalGenCode = getMandatoryScriptSection(minResponseCode, genCode);
            //gets response section string depending on availability of json/xml payloads
            String responseConditions = getResponseConditionsSection(hasJsonPayload, hasXmlPayload);
            String finalScript = finalGenCode + responseConditions;
            apiResourceMediationPolicyObject.setContent(finalScript);
            apiResourceMediationPolicyList.add(apiResourceMediationPolicyObject);
            //sets script to each resource in the swagger
            op.setVendorExtension(APIConstants.SWAGGER_X_MEDIATION_SCRIPT, finalScript);
        }
        returnMap.put(APIConstants.SWAGGER, Json.pretty(swagger));
        returnMap.put(APIConstants.MOCK_GEN_POLICY_LIST, apiResourceMediationPolicyList);
    }
    return returnMap;
}