use of io.swagger.models.parameters.BodyParameter in project java-chassis by ServiceComb.
the class PojoOperationGenerator method wrapParametersToBody.
private void wrapParametersToBody(List<ParameterGenerator> bodyFields) {
String simpleRef = MethodUtils.findSwaggerMethodName(method) + "Body";
bodyModel = new ModelImpl();
bodyModel.setType(ModelImpl.OBJECT);
for (ParameterGenerator parameterGenerator : bodyFields) {
// to collect all information by swagger mechanism
// must have a parameter type
// but all these parameters will be wrap to be one body parameter, their parameter type must be null
// so we first set to be BODY, after collected, set back to be null
parameterGenerator.setHttpParameterType(HttpParameterType.BODY);
scanMethodParameter(parameterGenerator);
Property property = ModelConverters.getInstance().readAsProperty(parameterGenerator.getGenericType());
property.setDescription(parameterGenerator.getGeneratedParameter().getDescription());
bodyModel.addProperty(parameterGenerator.getParameterName(), property);
parameterGenerator.setHttpParameterType(null);
}
swagger.addDefinition(simpleRef, bodyModel);
SwaggerGeneratorFeature feature = swaggerGenerator.getSwaggerGeneratorFeature();
// if not care for this, then can just delete all logic about EXT_JAVA_CLASS/EXT_JAVA_INTF
if (feature.isExtJavaClassInVendor() && bodyFields.size() > 1 && StringUtils.isNotEmpty(feature.getPackageName())) {
bodyModel.getVendorExtensions().put(SwaggerConst.EXT_JAVA_CLASS, feature.getPackageName() + "." + simpleRef);
}
RefModel refModel = new RefModel();
refModel.setReference("#/definitions/" + simpleRef);
bodyParameter = new BodyParameter();
bodyParameter.name(simpleRef);
bodyParameter.setSchema(refModel);
bodyParameter.setName(parameterGenerators.size() == 1 ? parameterGenerators.get(0).getParameterName() : simpleRef);
List<ParameterGenerator> newParameterGenerators = new ArrayList<>();
newParameterGenerators.add(new ParameterGenerator(bodyParameter.getName(), Collections.emptyList(), null, HttpParameterType.BODY, bodyParameter));
parameterGenerators.stream().filter(p -> p.getHttpParameterType() != null).forEach(p -> newParameterGenerators.add(p));
parameterGenerators = newParameterGenerators;
}
use of io.swagger.models.parameters.BodyParameter in project java-chassis by ServiceComb.
the class BodyProcessorCreator method create.
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
Model model = ((BodyParameter) parameter).getSchema();
JavaType swaggerType = null;
if (model instanceof ModelImpl) {
swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat());
}
boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class);
JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
boolean rawJson = SwaggerUtils.isRawJsonType(parameter);
if (rawJson) {
return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions().get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
}
return new BodyProcessor(targetType, (String) parameter.getVendorExtensions().get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
}
use of io.swagger.models.parameters.BodyParameter in project carbon-apimgt by wso2.
the class SequenceGenerator method generateSequencesFromSwagger.
/**
* Generates in/out sequences from the swagger given
*
* @param swaggerStr swagger string
* @throws APIManagementException
*/
public static List<SOAPToRestSequence> generateSequencesFromSwagger(String swaggerStr) throws APIManagementException {
List<SOAPToRestSequence> sequences = new ArrayList<SOAPToRestSequence>();
Swagger swagger = new SwaggerParser().parse(swaggerStr);
Map<String, Model> definitions = swagger.getDefinitions();
// Configure serializers
SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
Json.mapper().registerModule(simpleModule);
Yaml.mapper().registerModule(simpleModule);
Map<String, Path> paths = swagger.getPaths();
for (String pathName : paths.keySet()) {
Path path = paths.get(pathName);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
for (HttpMethod httpMethod : operationMap.keySet()) {
boolean isResourceFromWSDL = false;
Map<String, String> parameterJsonPathMapping = new HashMap<>();
Map<String, String> queryParameters = new HashMap<>();
Operation operation = operationMap.get(httpMethod);
String operationId = operation.getOperationId();
// get vendor extensions
Map<String, Object> vendorExtensions = operation.getVendorExtensions();
Object vendorExtensionObj = vendorExtensions.get("x-wso2-soap");
String soapAction = SOAPToRESTConstants.EMPTY_STRING;
String namespace = SOAPToRESTConstants.EMPTY_STRING;
String soapVersion = SOAPToRESTConstants.EMPTY_STRING;
if (vendorExtensionObj != null) {
soapAction = (String) ((LinkedHashMap) vendorExtensionObj).get("soap-action");
namespace = (String) ((LinkedHashMap) vendorExtensionObj).get("namespace");
soapVersion = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_VERSION);
soapMessageType = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_MESSAGE_TYPE);
soapStyle = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_STYLE);
isResourceFromWSDL = true;
}
String soapNamespace = SOAPToRESTConstants.SOAP12_NAMSPACE;
if (StringUtils.isNotBlank(soapVersion) && SOAPToRESTConstants.SOAP_VERSION_11.equals(soapVersion)) {
soapNamespace = SOAPToRESTConstants.SOAP11_NAMESPACE;
}
List<Parameter> parameters = operation.getParameters();
for (Parameter parameter : parameters) {
String name = parameter.getName();
if (parameter instanceof BodyParameter) {
Model schema = ((BodyParameter) parameter).getSchema();
if (schema instanceof RefModel) {
String $ref = ((RefModel) schema).get$ref();
if (StringUtils.isNotBlank($ref)) {
String defName = $ref.substring("#/definitions/".length());
Model model = definitions.get(defName);
Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());
replaceNullWithStringExample(example);
String jsonExample = Json.pretty(example);
try {
org.json.JSONObject json = new org.json.JSONObject(jsonExample);
SequenceUtils.listJson(json, parameterJsonPathMapping);
} catch (JSONException e) {
log.error("Error occurred while generating json mapping for the definition", e);
}
}
}
}
if (parameter instanceof QueryParameter) {
String type = ((QueryParameter) parameter).getType();
queryParameters.put(name, type);
}
}
// populates body parameter json paths and query parameters to generate api sequence parameters
populateParametersFromOperation(operation, definitions, parameterJsonPathMapping, queryParameters);
Map<String, String> payloadSequence = createPayloadFacXMLForOperation(parameterJsonPathMapping, queryParameters, namespace, SOAPToRESTConstants.EMPTY_STRING, operationId, definitions);
try {
String[] propAndArgElements = getPropertyAndArgElementsForSequence(parameterJsonPathMapping, queryParameters);
if (log.isDebugEnabled()) {
log.debug("properties string for the generated sequence: " + propAndArgElements[0]);
log.debug("arguments string for the generated sequence: " + propAndArgElements[1]);
}
org.json.simple.JSONArray arraySequenceElements = new org.json.simple.JSONArray();
// gets array elements for the sequence to be used
getArraySequenceElements(arraySequenceElements, parameterJsonPathMapping);
Map<String, String> sequenceMap = new HashMap<>();
sequenceMap.put("args", propAndArgElements[0]);
sequenceMap.put("properties", propAndArgElements[1]);
sequenceMap.put("sequence", payloadSequence.get(operationId));
RESTToSOAPMsgTemplate template = new RESTToSOAPMsgTemplate();
String inSequence = template.getMappingInSequence(sequenceMap, operationId, soapAction, namespace, soapNamespace, arraySequenceElements);
String outSequence = template.getMappingOutSequence();
if (isResourceFromWSDL) {
SOAPToRestSequence inSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, inSequence, Direction.IN);
sequences.add(inSeq);
SOAPToRestSequence outSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, outSequence, Direction.OUT);
sequences.add(outSeq);
}
} catch (APIManagementException e) {
handleException("Error when generating sequence property and arg elements for soap operation: " + operationId, e);
}
}
}
return sequences;
}
use of io.swagger.models.parameters.BodyParameter in project swagger-parser by swagger-api.
the class SwaggerConverter method convertParameterToRequestBody.
private RequestBody convertParameterToRequestBody(io.swagger.models.parameters.Parameter param, List<String> consumes) {
RequestBody body = new RequestBody();
BodyParameter bp = (BodyParameter) param;
List<String> mediaTypes = new ArrayList<>(globalConsumes);
if (consumes != null && consumes.size() > 0) {
mediaTypes.clear();
mediaTypes.addAll(consumes);
}
if (mediaTypes.size() == 0) {
mediaTypes.add("*/*");
}
if (StringUtils.isNotBlank(param.getDescription())) {
body.description(param.getDescription());
}
body.required(param.getRequired());
Content content = new Content();
for (String type : mediaTypes) {
content.addMediaType(type, new MediaType().schema(convert(bp.getSchema())));
if (StringUtils.isNotBlank(bp.getDescription())) {
body.setDescription(bp.getDescription());
}
}
convertExamples(((BodyParameter) param).getExamples(), content);
body.content(content);
return body;
}
use of io.swagger.models.parameters.BodyParameter in project swagger-core by swagger-api.
the class ParameterProcessor method applyAnnotations.
public static Parameter applyAnnotations(Swagger swagger, Parameter parameter, Type type, List<Annotation> annotations) {
final AnnotationsHelper helper = new AnnotationsHelper(annotations, type);
if (helper.isContext()) {
return null;
}
final ParamWrapper<?> param = helper.getApiParam();
if (param.isHidden()) {
return null;
}
final String defaultValue = helper.getDefaultValue();
if (parameter instanceof AbstractSerializableParameter) {
final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
if (param.isRequired()) {
p.setRequired(true);
}
if (param.getReadOnly()) {
p.readOnly(param.getReadOnly());
}
if (param.getAllowEmptyValue()) {
p.allowEmptyValue(param.getAllowEmptyValue());
}
if (StringUtils.isNotEmpty(param.getName())) {
p.setName(param.getName());
}
if (StringUtils.isNotEmpty(param.getDescription())) {
p.setDescription(param.getDescription());
}
if (StringUtils.isNotEmpty(param.getExample())) {
p.setExample(param.getExample());
}
if (StringUtils.isNotEmpty(param.getAccess())) {
p.setAccess(param.getAccess());
}
if (StringUtils.isNoneEmpty(param.getCollectionFormat())) {
p.setCollectionFormat(param.getCollectionFormat());
}
if (StringUtils.isNotEmpty(param.getDataType())) {
if ("java.io.File".equalsIgnoreCase(param.getDataType())) {
p.setProperty(new FileProperty());
} else if ("long".equalsIgnoreCase(param.getDataType())) {
p.setProperty(new LongProperty());
} else {
p.setType(param.getDataType());
}
}
if (helper.getMin() != null) {
p.setMinimum(helper.getMin());
if (helper.isMinExclusive()) {
p.setExclusiveMinimum(true);
}
}
if (helper.getMax() != null) {
p.setMaximum(helper.getMax());
if (helper.isMaxExclusive()) {
p.setExclusiveMaximum(true);
}
}
if (helper.getMinItems() != null) {
p.setMinItems(helper.getMinItems());
}
if (helper.getMaxItems() != null) {
p.setMaxItems(helper.getMaxItems());
}
if (helper.getMinLength() != null) {
p.setMinLength(helper.getMinLength());
}
if (helper.getMaxLength() != null) {
p.setMaxLength(helper.getMaxLength());
}
if (helper.getPattern() != null) {
p.setPattern(helper.getPattern());
}
if (helper.isRequired() != null) {
p.setRequired(true);
}
if (helper.getType() != null) {
p.setType(helper.getType());
}
if (helper.getFormat() != null) {
p.setFormat(helper.getFormat());
}
AllowableValues allowableValues = AllowableValuesUtils.create(param.getAllowableValues());
if (p.getItems() != null || param.isAllowMultiple()) {
if (p.getItems() == null) {
// Convert to array
final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(PropertyBuilder.PropertyId.class);
args.put(PropertyBuilder.PropertyId.DEFAULT, p.getDefaultValue());
p.setDefaultValue(null);
args.put(PropertyBuilder.PropertyId.ENUM, p.getEnum());
p.setEnum(null);
args.put(PropertyBuilder.PropertyId.MINIMUM, p.getMinimum());
p.setMinimum(null);
args.put(PropertyBuilder.PropertyId.EXCLUSIVE_MINIMUM, p.isExclusiveMinimum());
p.setExclusiveMinimum(null);
args.put(PropertyBuilder.PropertyId.MAXIMUM, p.getMaximum());
p.setMaximum(null);
args.put(PropertyBuilder.PropertyId.EXCLUSIVE_MAXIMUM, p.isExclusiveMaximum());
args.put(PropertyBuilder.PropertyId.MIN_LENGTH, p.getMinLength());
p.setMinLength(null);
args.put(PropertyBuilder.PropertyId.MAX_LENGTH, p.getMaxLength());
p.setMaxLength(null);
args.put(PropertyBuilder.PropertyId.PATTERN, p.getPattern());
p.setPattern(null);
args.put(PropertyBuilder.PropertyId.EXAMPLE, p.getExample());
p.setExclusiveMaximum(null);
Property items = PropertyBuilder.build(p.getType(), p.getFormat(), args);
p.type(ArrayProperty.TYPE).format(null).items(items);
}
final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(PropertyBuilder.PropertyId.class);
if (StringUtils.isNotEmpty(defaultValue)) {
args.put(PropertyBuilder.PropertyId.DEFAULT, defaultValue);
}
if (helper.getMin() != null) {
args.put(PropertyBuilder.PropertyId.MINIMUM, helper.getMin());
if (helper.isMinExclusive()) {
args.put(PropertyBuilder.PropertyId.EXCLUSIVE_MINIMUM, true);
}
}
if (helper.getMax() != null) {
args.put(PropertyBuilder.PropertyId.MAXIMUM, helper.getMax());
if (helper.isMaxExclusive()) {
args.put(PropertyBuilder.PropertyId.EXCLUSIVE_MAXIMUM, true);
}
}
if (helper.getMinLength() != null) {
args.put(PropertyBuilder.PropertyId.MIN_LENGTH, helper.getMinLength());
}
if (helper.getMaxLength() != null) {
args.put(PropertyBuilder.PropertyId.MAX_LENGTH, helper.getMaxLength());
}
if (helper.getPattern() != null) {
args.put(PropertyBuilder.PropertyId.PATTERN, helper.getPattern());
}
//Overwrite Bean validation values with allowable values if present
if (allowableValues != null) {
args.putAll(allowableValues.asPropertyArguments());
}
PropertyBuilder.merge(p.getItems(), args);
} else {
if (StringUtils.isNotEmpty(defaultValue)) {
p.setDefaultValue(defaultValue);
}
//Overwrite Bean validation values with allowable values if present
if (allowableValues != null) {
processAllowedValues(allowableValues, p);
}
// else {
// processJsr303Annotations(helper, p);
// }
}
} else {
// must be a body param
BodyParameter bp = new BodyParameter();
if (helper.getApiParam() != null) {
ParamWrapper<?> pw = helper.getApiParam();
if (pw instanceof ApiParamWrapper) {
ApiParamWrapper apiParam = (ApiParamWrapper) pw;
Example example = apiParam.getExamples();
if (example != null && example.value() != null) {
for (ExampleProperty ex : example.value()) {
String mediaType = ex.mediaType();
String value = ex.value();
if (!mediaType.isEmpty() && !value.isEmpty()) {
bp.example(mediaType.trim(), value.trim());
}
}
}
} else if (pw instanceof ApiImplicitParamWrapper) {
ApiImplicitParamWrapper apiParam = (ApiImplicitParamWrapper) pw;
Example example = apiParam.getExamples();
if (example != null && example.value() != null) {
for (ExampleProperty ex : example.value()) {
String mediaType = ex.mediaType();
String value = ex.value();
if (!mediaType.isEmpty() && !value.isEmpty()) {
bp.example(mediaType.trim(), value.trim());
}
}
}
}
}
bp.setRequired(param.isRequired());
bp.setName(StringUtils.isNotEmpty(param.getName()) ? param.getName() : "body");
if (StringUtils.isNotEmpty(param.getDescription())) {
bp.setDescription(param.getDescription());
}
if (StringUtils.isNotEmpty(param.getAccess())) {
bp.setAccess(param.getAccess());
}
final Property property = ModelConverters.getInstance().readAsProperty(type);
if (property != null) {
final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(PropertyBuilder.PropertyId.class);
if (StringUtils.isNotEmpty(defaultValue)) {
args.put(PropertyBuilder.PropertyId.DEFAULT, defaultValue);
}
bp.setSchema(PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
for (Map.Entry<String, Model> entry : ModelConverters.getInstance().readAll(type).entrySet()) {
swagger.addDefinition(entry.getKey(), entry.getValue());
}
}
parameter = bp;
}
return parameter;
}
Aggregations