Search in sources :

Example 1 with PropertyModelConverter

use of io.swagger.models.utils.PropertyModelConverter in project JCELechat by guiguilechat.

the class FetchTranslator method makeFetchRetType.

/**
 * get the existing fetch type for this response
 */
protected void makeFetchRetType() {
    Model m = response.getResponseSchema();
    if (m == null) {
        resourceStructure = RETURNTYPE.NONE;
        resourceType = resourceFlatType = cm.VOID;
        fetchRetType = cm.ref(Requested.class).narrow(resourceType);
    } else if (m.getClass() == ArrayModel.class) {
        ArrayModel am = (ArrayModel) m;
        resourceStructure = RETURNTYPE.LIST;
        resourceFlatType = bridge.getReponseClass(am.getItems());
        resourceType = resourceFlatType.boxify().array();
        fetchRetType = cm.ref(Requested.class).narrow(resourceType);
    } else if (m.getClass() == ModelImpl.class) {
        ModelImpl mi = (ModelImpl) m;
        if (mi.getAdditionalProperties() != null) {
            resourceStructure = RETURNTYPE.MAP;
            resourceFlatType = bridge.getReponseClass(mi.getAdditionalProperties());
            resourceType = cm.ref(Map.class).narrow(cm.ref(String.class), resourceFlatType.boxify());
            fetchRetType = cm.ref(Requested.class).narrow(resourceType);
        } else {
            resourceStructure = RETURNTYPE.OBJECT;
            resourceType = resourceFlatType = bridge.getReponseClass(new PropertyModelConverter().modelToProperty(response.getResponseSchema()));
            fetchRetType = cm.ref(Requested.class).narrow(resourceType);
        }
    } else {
        logger.warn("can't apply to path class " + m.getClass());
    }
}
Also used : Requested(fr.guiguilechat.jcelechat.jcesi.interfaces.Requested) PropertyModelConverter(io.swagger.models.utils.PropertyModelConverter) Model(io.swagger.models.Model) JCodeModel(com.helger.jcodemodel.JCodeModel) ArrayModel(io.swagger.models.ArrayModel) ModelImpl(io.swagger.models.ModelImpl) ArrayModel(io.swagger.models.ArrayModel)

Example 2 with PropertyModelConverter

use of io.swagger.models.utils.PropertyModelConverter in project convertigo by convertigo.

the class SwaggerUtils method parse.

public static Swagger parse(String requestUrl, UrlMapper urlMapper) {
    Project project = urlMapper.getProject();
    String projectName = project.getName();
    String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
    Swagger swagger = parseCommon(requestUrl, project);
    List<Tag> tags = new ArrayList<Tag>();
    Tag tag = new Tag();
    tag.setName(urlMapper.getProject().getName());
    tag.setDescription(urlMapper.getProject().getComment());
    tags.add(tag);
    swagger.setTags(tags);
    // Security
    Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
    for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
        if (AuthenticationType.Basic.equals(authentication.getType())) {
            if (securityDefinitions == null || !securityDefinitions.containsKey("basicAuth")) {
                BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
                swagger.addSecurityDefinition("basicAuth", basicAuthDefinition);
                SecurityRequirement securityRequirement = new SecurityRequirement();
                securityRequirement.requirement("basicAuth", new ArrayList<String>());
                swagger.addSecurity(securityRequirement);
            }
        }
    }
    // Models and Schemas
    Map<String, Model> swagger_models = new HashMap<String, Model>();
    try {
        String models = getModels(oasDirUrl, urlMapper);
        if (!models.isEmpty()) {
            ObjectMapper mapper = Json.mapper();
            JsonNode definitionNode = mapper.readTree(models);
            for (Iterator<Entry<String, JsonNode>> it = GenericUtils.cast(definitionNode.fields()); it.hasNext(); ) {
                Entry<String, JsonNode> entry = it.next();
                swagger_models.put(entry.getKey().toString(), mapper.convertValue(entry.getValue(), Model.class));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.warn("Unexpected exception while reading UrlMapper defined models", e);
    }
    swagger.setDefinitions(swagger_models);
    // Mappings
    Map<String, Path> swagger_paths = new HashMap<String, Path>();
    try {
        for (UrlMapping urlMapping : urlMapper.getMappingList()) {
            Path swagger_path = new Path();
            for (UrlMappingOperation umo : urlMapping.getOperationList()) {
                Operation s_operation = new Operation();
                s_operation.setOperationId(umo.getQName());
                s_operation.setDescription(umo.getComment());
                s_operation.setSummary(umo.getComment());
                // Operation produces
                if (umo instanceof AbstractRestOperation) {
                    DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
                    if (dataOutput.equals(DataContent.toJson)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value()));
                    } else if (dataOutput.equals(DataContent.toXml)) {
                        s_operation.setProduces(Arrays.asList(MimeType.Xml.value()));
                    } else {
                        s_operation.setProduces(Arrays.asList(MimeType.Json.value(), MimeType.Xml.value()));
                    }
                }
                // Operation tags
                List<String> list = Arrays.asList("" + project.getName());
                s_operation.setTags(list);
                // Operation consumes
                List<String> consumes = new ArrayList<String>();
                // Operation parameters
                List<Parameter> s_parameters = new ArrayList<Parameter>();
                // 1 - add path parameters
                for (String pathVarName : urlMapping.getPathVariableNames()) {
                    PathParameter s_parameter = new PathParameter();
                    s_parameter.setName(pathVarName);
                    s_parameter.setRequired(true);
                    s_parameter.setType("string");
                    // retrieve parameter description from bean
                    UrlMappingParameter ump = null;
                    try {
                        ump = umo.getParameterByName(pathVarName);
                    } catch (Exception e) {
                    }
                    if (ump != null && ump.getType() == Type.Path) {
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setType(ump.getInputType().toLowerCase());
                        Object value = ump.getValueOrNull();
                        if (value != null) {
                            s_parameter.setDefaultValue(String.valueOf(value));
                        }
                    }
                    s_parameters.add(s_parameter);
                }
                // 2 - add other parameters
                for (UrlMappingParameter ump : umo.getParameterList()) {
                    Parameter s_parameter = null;
                    if (ump.getType() == Type.Query) {
                        s_parameter = new QueryParameter();
                    } else if (ump.getType() == Type.Form) {
                        s_parameter = new FormParameter();
                    } else if (ump.getType() == Type.Body) {
                        s_parameter = new BodyParameter();
                        if (ump instanceof IMappingRefModel) {
                            String modelReference = ((IMappingRefModel) ump).getModelReference();
                            if (!modelReference.isEmpty()) {
                                if (modelReference.indexOf(".jsonschema") != -1) {
                                    modelReference = oasDirUrl + modelReference;
                                }
                                RefModel refModel = new RefModel(modelReference);
                                ((BodyParameter) s_parameter).setSchema(refModel);
                            }
                        }
                    } else if (ump.getType() == Type.Header) {
                        s_parameter = new HeaderParameter();
                    } else if (ump.getType() == Type.Path) {
                    // ignore : should have been treated before
                    }
                    if (s_parameter != null) {
                        s_parameter.setName(ump.getName());
                        s_parameter.setDescription(ump.getComment());
                        s_parameter.setRequired(ump.isRequired());
                        if (s_parameter instanceof SerializableParameter) {
                            boolean isArray = ump.isMultiValued() || ump.isArray();
                            String _type = isArray ? "array" : ump.getDataType().name().toLowerCase();
                            String _collectionFormat = ump.isMultiValued() ? "multi" : (isArray ? "csv" : null);
                            Property _items = isArray ? getItems(ump.getDataType()) : null;
                            ((SerializableParameter) s_parameter).setType(_type);
                            ((SerializableParameter) s_parameter).setCollectionFormat(_collectionFormat);
                            ((SerializableParameter) s_parameter).setItems(_items);
                            Object value = ump.getValueOrNull();
                            if (value != null) {
                                String collection = ((SerializableParameter) s_parameter).getCollectionFormat();
                                if (collection != null && collection.equals("multi")) {
                                    Property items = new StringProperty();
                                    // items.setDefault(String.valueOf(value));
                                    ((SerializableParameter) s_parameter).setItems(items);
                                // ((SerializableParameter) s_parameter).setEnumValue(Arrays.asList("val1","val2","val3"));
                                } else {
                                    ((AbstractSerializableParameter<?>) s_parameter).setDefaultValue(String.valueOf(value));
                                }
                            }
                        }
                        DataContent dataInput = ump.getInputContent();
                        if (dataInput.equals(DataContent.toJson)) {
                            if (!consumes.contains(MimeType.Json.value())) {
                                consumes.add(MimeType.Json.value());
                            }
                        } else if (dataInput.equals(DataContent.toXml)) {
                            if (!consumes.contains(MimeType.Xml.value())) {
                                consumes.add(MimeType.Xml.value());
                            }
                        }
                        // swagger-ui workaround for invalid request content-type for POST
                        if (ump.getType() == Type.Form) {
                            if (!DataType.File.equals(ump.getDataType())) {
                                if (!consumes.contains(MimeType.WwwForm.value())) {
                                    consumes.add(MimeType.WwwForm.value());
                                }
                            } else {
                                if (!consumes.contains("multipart/form-data")) {
                                    consumes.add("multipart/form-data");
                                }
                            }
                        }
                        // add parameter
                        if (ump.isExposed()) {
                            s_parameters.add(s_parameter);
                        }
                    }
                }
                s_operation.setParameters(s_parameters);
                if (!consumes.isEmpty()) {
                    s_operation.setConsumes(consumes);
                }
                // Set operation responses
                Map<String, Response> responses = new HashMap<String, Response>();
                for (UrlMappingResponse umr : umo.getResponseList()) {
                    String statusCode = umr.getStatusCode();
                    if (!statusCode.isEmpty()) {
                        if (!responses.containsKey(statusCode)) {
                            Response response = new Response();
                            // response.setDescription(umr.getComment());
                            response.setDescription(umr.getStatusText());
                            if (umr instanceof IMappingRefModel) {
                                String modelReference = ((IMappingRefModel) umr).getModelReference();
                                if (!modelReference.isEmpty()) {
                                    if (modelReference.indexOf(".jsonschema") != -1) {
                                        modelReference = oasDirUrl + modelReference;
                                    }
                                    RefProperty refProperty = new RefProperty(modelReference);
                                    response.setResponseSchema(new PropertyModelConverter().propertyToModel(refProperty));
                                }
                            }
                            responses.put(statusCode, response);
                        }
                    }
                }
                if (responses.isEmpty()) {
                    Response resp200 = new Response();
                    resp200.description("successful operation");
                    responses.put("200", resp200);
                }
                s_operation.setResponses(responses);
                // Add operation to path
                String s_method = umo.getMethod().toLowerCase();
                swagger_path.set(s_method, s_operation);
            }
            swagger_paths.put(urlMapping.getPathWithPrefix(), swagger_path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
    }
    swagger.setPaths(swagger_paths);
    return swagger;
}
Also used : UrlMapping(com.twinsoft.convertigo.beans.core.UrlMapping) SerializableParameter(io.swagger.models.parameters.SerializableParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) PropertyModelConverter(io.swagger.models.utils.PropertyModelConverter) DataContent(com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Project(com.twinsoft.convertigo.beans.core.Project) JSONObject(org.codehaus.jettison.json.JSONObject) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) QueryParameter(io.swagger.models.parameters.QueryParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) AbstractRestOperation(com.twinsoft.convertigo.beans.rest.AbstractRestOperation) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) FormParameter(io.swagger.models.parameters.FormParameter) RefProperty(io.swagger.models.properties.RefProperty) Entry(java.util.Map.Entry) Swagger(io.swagger.models.Swagger) HeaderParameter(io.swagger.models.parameters.HeaderParameter) StringProperty(io.swagger.models.properties.StringProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) Path(io.swagger.models.Path) UrlMappingOperation(com.twinsoft.convertigo.beans.core.UrlMappingOperation) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) BasicAuthDefinition(io.swagger.models.auth.BasicAuthDefinition) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Response(io.swagger.models.Response) UrlMappingResponse(com.twinsoft.convertigo.beans.core.UrlMappingResponse) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) IMappingRefModel(com.twinsoft.convertigo.beans.core.IMappingRefModel) SerializableParameter(io.swagger.models.parameters.SerializableParameter) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) AbstractSerializableParameter(io.swagger.models.parameters.AbstractSerializableParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) UrlMappingParameter(com.twinsoft.convertigo.beans.core.UrlMappingParameter) Tag(io.swagger.models.Tag) UrlAuthentication(com.twinsoft.convertigo.beans.core.UrlAuthentication) SecurityRequirement(io.swagger.models.SecurityRequirement)

Aggregations

Model (io.swagger.models.Model)2 PropertyModelConverter (io.swagger.models.utils.PropertyModelConverter)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JCodeModel (com.helger.jcodemodel.JCodeModel)1 IMappingRefModel (com.twinsoft.convertigo.beans.core.IMappingRefModel)1 Project (com.twinsoft.convertigo.beans.core.Project)1 UrlAuthentication (com.twinsoft.convertigo.beans.core.UrlAuthentication)1 UrlMapping (com.twinsoft.convertigo.beans.core.UrlMapping)1 UrlMappingOperation (com.twinsoft.convertigo.beans.core.UrlMappingOperation)1 UrlMappingParameter (com.twinsoft.convertigo.beans.core.UrlMappingParameter)1 DataContent (com.twinsoft.convertigo.beans.core.UrlMappingParameter.DataContent)1 UrlMappingResponse (com.twinsoft.convertigo.beans.core.UrlMappingResponse)1 AbstractRestOperation (com.twinsoft.convertigo.beans.rest.AbstractRestOperation)1 Requested (fr.guiguilechat.jcelechat.jcesi.interfaces.Requested)1 ArrayModel (io.swagger.models.ArrayModel)1 ModelImpl (io.swagger.models.ModelImpl)1 Operation (io.swagger.models.Operation)1 Path (io.swagger.models.Path)1