Transform Swagger parameters into JSON Schema object by paramType.
483522
function parameters(spec, paramType) {
  spec = lodash.cloneDeep(spec);

  var schema = {
    type: 'object',
    properties: {},
    required: [],
  };

  spec.parameters.forEach(function(parameter) {
    // only get rules for current paramType
    if (parameter.paramType !== paramType) return;

    // create current property
    var property = schema.properties[parameter.name] = {
      type: parameter.type,
    };

    switch (parameter.type) {
    case 'integer':
      property.type = parameter.type;

      ['minimum', 'maximum'].forEach(function(key) {
        if (parameter.hasOwnProperty(key)) {
          property[key] = parseInt(parameter[key], 10);
        }
      });

      break;
    case 'number':
      property.type = parameter.type;

      break;
    case 'string':
      property.type = parameter.type;

      if (parameter.hasOwnProperty('minimum')) {
        property.minLength = parseInt(parameter.minimum, 10);
      }

      if (parameter.hasOwnProperty('maximum')) {
        property.maxLength = parseInt(parameter.maximum, 10);
      }

      if (parameter.hasOwnProperty('format')) {
        property.format = parameter.format;
      }

      break;
    case 'boolean':
      property.type = parameter.type;

      break;
    case 'array':
      property.type = parameter.type;
      property.items = parameter.items;

      if (parameter.uniqueItems) property.uniqueItems = true;

      if (parameter.hasOwnProperty('minItems')) {
        property.minItems = parameter.minItems;
      }

      if (parameter.hasOwnProperty('maxItems')) {
        property.maxItems = parameter.maxItems;
      }

      break;
    default:
      if (paramType === 'body') {
        property.$ref = parameter.type;
        lodash.keys(property).forEach(function(key) {
          if (key !== '$ref') delete property[key];
        });
      } else {
        throw new Error('unknown type: ' + parameter.type);
      }
    }

    if (Array.isArray(parameter.enum)) {
      property.enum = parameter.enum;
    }

    var hasDefault = parameter.hasOwnProperty('defaultValue');

    if (hasDefault) {
      property.default = parameter.defaultValue;
    }

    // path rules are implicitly required
    if (!hasDefault && (parameter.required || paramType === 'path')) {
      schema.required.push(parameter.name);
    }

    // convert to items if allowMultiple
    if (parameter.allowMultiple &&
        constants.allowMultiple.indexOf(parameter.paramType) >= 0) {
      var schemaProperty = schema.properties[parameter.name] = {
        type: 'array',
        items: property,
      };

      if (parameter.uniqueItems) schemaProperty.uniqueItems = true;

      if (parameter.hasOwnProperty('minItems')) {
        schemaProperty.minItems = parameter.minItems;
      }

      if (parameter.hasOwnProperty('maxItems')) {
        schemaProperty.maxItems = parameter.maxItems;
      }
    }
  });

  if (!schema.required.length) delete schema.required;

  if (lodash.isEmpty(schema.properties)) return;

  return schema;
}
750106
def from_api_repr(cls, resource):
        
        name = resource.get("name")
        instance = cls(name)
        type_resources = {}
        types = instance.struct_types
        for item in resource["parameterType"]["structTypes"]:
            types[item["name"]] = item["type"]["type"]
            type_resources[item["name"]] = item["type"]
        struct_values = resource["parameterValue"]["structValues"]
        for key, value in struct_values.items():
            type_ = types[key]
            converted = None
            if type_ == "STRUCT":
                struct_resource = {
                    "name": key,
                    "parameterType": type_resources[key],
                    "parameterValue": value,
                }
                converted = StructQueryParameter.from_api_repr(struct_resource)
            elif type_ == "ARRAY":
                struct_resource = {
                    "name": key,
                    "parameterType": type_resources[key],
                    "parameterValue": value,
                }
                converted = ArrayQueryParameter.from_api_repr(struct_resource)
            else:
                value = value["value"]
                converted = _QUERY_PARAMS_FROM_JSON[type_](value, None)
            instance.struct_values[key] = converted
        return instance
752242
def _extract_models(cls, apis):
        ''''''
        # TODO: This would probably be much better if the info would be
        # extracted from the classes, rather than from the swagger
        # representation...
        models = set()
        for api in apis:
            for op in api.get('operations', []):
                models.add(op['type'])
                for param in op.get('parameters', []):
                    models.add(param.get('type', 'void'))
                for msg in op['responseMessages']:
                    models.add(msg.get('responseModel', 'void'))
        # Convert from swagger name representation to classes
        models = map(lambda m: Model.name_to_cls[m], models)
        ret = {}
        for model in models:
            if model.native_type:
                continue
            obj = model.schema.copy()
            obj['id'] = model.name
            ret[model.name] = obj
        return ret
93833
def schema_from_context(context):
    """"""
    item_class = context.get('class')
    return (
        serializer_mapping[item_class] if item_class else BaseSchema,
        context.get('many', False)
    )
961850
function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) {
  if (jsonSchemaType === "array") {
    if (graphQLObjectTypes[schemaName]) {
      return new GraphQLList(graphQLObjectTypes[schemaName]);
    } else {
      const translated = {
        pilots: "people",
        characters: "people",
        residents: "people"
      }[schemaName];

      if (! translated) {
        throw new Error(`no type ${schemaName}`);
      }

      const type = graphQLObjectTypes[translated];

      if (! type) {
        throw new Error(`no GraphQL type ${schemaName}`);
      }

      return new GraphQLList(type);
    }
  }

  return {
    string: GraphQLString,
    date: GraphQLString,
    integer: GraphQLInt,
  }[jsonSchemaType];
}
404042
def schema():
        """"""
        return Schema({
            'script': And(Or(type(' '), type(u' ')), len),
            Optional('title', default=''): str,
            Optional('model', default={}): {Optional(And(str, len)): object},
            Optional('env', default={}): {Optional(And(str, len)): And(str, len)},
            Optional('item', default=None): object,
            Optional('dry_run', default=False): bool,
            Optional('debug', default=False): bool,
            Optional('strict', default=False): bool,
            Optional('variables', default={}): {
                Optional(And(Or(type(' '), type(u' ')), len, Regex(r'([a-zA-Z][_a-zA-Z]*)'))):
                    Or(type(' '), type(u' '))
            },
            Optional('temporary_scripts_path', default=''): Or(type(''), type(u'')),
            Optional('internal', default=False): bool
        })
300205
def _generate_openapi_object(document):
    
    parsed_url = urlparse.urlparse(document.url)

    swagger = OrderedDict()

    swagger['swagger'] = '2.0'
    swagger['info'] = OrderedDict()
    swagger['info']['title'] = document.title
    swagger['info']['description'] = document.description
    swagger['info']['version'] = document.version

    if parsed_url.netloc:
        swagger['host'] = parsed_url.netloc
    if parsed_url.scheme:
        swagger['schemes'] = [parsed_url.scheme]

    swagger['paths'] = _get_paths_object(document)

    return swagger
1069061
def _parse_method_data(self, method_name, method_data):
        '''
        
        '''
        method_params = {}
        method_models = {}
        if 'parameters' in method_data:
            for param in method_data['parameters']:
                p = _Swagger.SwaggerParameter(param)
                if p.name:
                    method_params[p.name] = True
                if p.schema:
                    method_models['application/json'] = p.schema

        request_templates = _Swagger.REQUEST_OPTION_TEMPLATE if method_name == 'options' else _Swagger.REQUEST_TEMPLATE
        integration_type = "MOCK" if method_name == 'options' else "AWS"

        return {'params': method_params,
                'models': method_models,
                'request_templates': request_templates,
                'integration_type': integration_type}
431923
def to_json(value, **kwargs):
        """"""
        if isinstance(value, HasProperties):
            return value.serialize(**kwargs)
        try:
            return json.loads(json.dumps(value))
        except TypeError:
            raise TypeError(
                "Cannot convert type {} to JSON without calling 'serialize' "
                "on an instance of Instance Property and registering a custom "
                "serializer".format(value.__class__.__name__)
            )
844464
def map_parameters(cls, params):
        """"""

        d = {}
        for k, v in six.iteritems(params):
            d[cls.FIELD_MAP.get(k.lower(), k)] = v
        return d
1177133
function JSONSchema () {
  var self = this;

  self.klass = JSONSchema;
  self.klass.super_.apply(self, arguments);

  self.engine = require('json-schema');
}
118228
def data2schemacls(_data, **kwargs):
    
    content = {}

    for key in list(kwargs):  # fill kwargs
        kwargs[key] = data2schema(kwargs[key])

    if isinstance(_data, dict):
        datacontent = iteritems(_data)

    else:
        datacontent = getmembers(_data)

    for name, value in datacontent:

        if name[0] == '_':
            continue

        if isinstance(value, dict):
            schema = data2schemacls(value)()

        else:
            schema = data2schema(value)

        content[name] = schema

    content.update(kwargs)  # update content

    result = type('GeneratedSchema', (Schema,), content)

    return result
444341
function processModels(swagger, options) {
  var name, model, i, property;
  var models = {};
  for (name in swagger.definitions) {
    model = swagger.definitions[name];
    var parent = null;
    var properties = null;
    var requiredProperties = null;
    var additionalPropertiesType = false;
    var example = model.example || null;
    var enumValues = null;
    var elementType = null;
    var simpleType = null;
    if (model.allOf != null && model.allOf.length > 0) {
      parent = simpleRef((model.allOf[0] || {}).$ref);
      properties = (model.allOf[1] || {}).properties || {};
      requiredProperties = (model.allOf[1] || {}).required || [];
    } else if (model.type === 'string') {
      enumValues = model.enum || [];
      if (enumValues.length == 0) {
        simpleType = 'string';
        enumValues = null;
      } else {
        for (i = 0; i < enumValues.length; i++) {
          var enumValue = enumValues[i];
          var enumDescriptor = {
            enumName: toEnumName(enumValue),
            enumValue: enumValue,
            enumIsLast: i === enumValues.length - 1,
          };
          enumValues[i] = enumDescriptor;
        }
      }
    } else if (model.type === 'array') {
      elementType = propertyType(model);
    } else if (!model.type && (model.anyOf || model.oneOf)) {
      let of = model.anyOf || model.oneOf;
      let variants = of.map(propertyType);
      simpleType = {
        allTypes: mergeTypes(...variants),
        toString: () => variants.join(' |\n  ')
      };
    } else if (model.type === 'object' || model.type === undefined) {
      properties = model.properties || {};
      requiredProperties = model.required || [];
      additionalPropertiesType = model.additionalProperties &&
          (typeof model.additionalProperties === 'object' ? propertyType(model.additionalProperties) : 'any');
    } else {
      simpleType = propertyType(model);
    }
    var modelClass = toClassName(name);
    var descriptor = {
      modelName: name,
      modelClass: modelClass,
      modelFile: toFileName(modelClass),
      modelComments: toComments(model.description),
      modelParent: parent,
      modelIsObject: properties != null,
      modelIsEnum: enumValues != null,
      modelIsArray: elementType != null,
      modelIsSimple: simpleType != null,
      modelSimpleType: simpleType,
      properties: properties == null ? null :
        processProperties(swagger, properties, requiredProperties),
      modelExample: example,
      modelAdditionalPropertiesType: additionalPropertiesType,
      modelExampleFile: toExampleFileName(name),
      modelEnumValues: enumValues,
      modelElementType: elementType,
      modelSubclasses: [],
    };

    if (descriptor.properties != null) {
      descriptor.modelProperties = [];
      for (var propertyName in descriptor.properties) {
        property = descriptor.properties[propertyName];
        descriptor.modelProperties.push(property);
      }
      descriptor.modelProperties.sort((a, b) => {
        return a.modelName < b.modelName ? -1 :
          a.modelName > b.modelName ? 1 : 0;
      });
      if (descriptor.modelProperties.length > 0) {
        descriptor.modelProperties[
          descriptor.modelProperties.length - 1
        ].propertyIsLast = true;
      }
    }

    models[name] = descriptor;
    models[descriptor.modelClass] = descriptor;
  }

  // Now that we know all models, process the hierarchies
  for (name in models) {
    model = models[name];
    if (!model.modelIsObject) {
      // Only objects can have hierarchies
      continue;
    }

    // Process the hierarchy
    var parentName = model.modelParent;
    if (parentName) {
      // Make the parent be the actual model, not the name
      model.modelParent = models[parentName];

      // Append this model on the parent's subclasses
      model.modelParent.modelSubclasses.push(model);
    }
  }

  // Now that the model hierarchy is ok, resolve the dependencies
  var addToDependencies = t => {
    if (Array.isArray(t.allTypes)) {
      t.allTypes.forEach(it => dependencies.add(it));
    }
    else dependencies.add(t);
  };
  for (name in models) {
    model = models[name];
    if (model.modelIsEnum || model.modelIsSimple && !model.modelSimpleType.allTypes) {
      // Enums or simple types have no dependencies
      continue;
    }
    var dependencies = new DependenciesResolver(models, model.modelName);

    // The parent is a dependency
    if (model.modelParent) {
      dependencies.add(model.modelParent.modelName);
    }

    // Each property may add a dependency
    if (model.modelProperties) {
      for (i = 0; i < model.modelProperties.length; i++) {
        property = model.modelProperties[i];
        addToDependencies(property.propertyType);
      }
    }

    // If an array, the element type is a dependency
    if (model.modelElementType) addToDependencies(model.modelElementType);

    if (model.modelSimpleType) addToDependencies(model.modelSimpleType);

    if (model.modelAdditionalPropertiesType) addToDependencies(model.modelAdditionalPropertiesType);

    model.modelDependencies = dependencies.get();
  }

  return models;
}
1041924
function GENERATE_PARAMS(spec) {
  return _.map(spec, function(paramSpec, paramName) {
    return paramName + ': ' + paramSpec.type;
  }).join(', ');
}
407591
def path_param(name, ns):
    
    if ns.identifier_type == "uuid":
        param_type = "string"
        param_format = "uuid"
    else:
        param_type = "string"
        param_format = None

    kwargs = {
        "name": name,
        "in": "path",
        "required": True,
        "type": param_type,
    }
    if param_format:
        kwargs["format"] = param_format
    return swagger.PathParameterSubSchema(**kwargs)
367756
def build_swagger(graph, ns, operations):
    
    base_path = graph.build_route_path(ns.path, ns.prefix)
    schema = swagger.Swagger(
        swagger="2.0",
        info=swagger.Info(
            title=graph.metadata.name,
            version=ns.version,
        ),
        consumes=swagger.MediaTypeList([
            swagger.MimeType("application/json"),
        ]),
        produces=swagger.MediaTypeList([
            swagger.MimeType("application/json"),
        ]),
        basePath=base_path,
        paths=swagger.Paths(),
        definitions=swagger.Definitions(),
    )
    add_paths(schema.paths, base_path, operations)
    add_definitions(schema.definitions, operations)
    try:
        schema.validate()
    except Exception:
        logger.exception("Swagger definition did not validate against swagger schema")
        raise

    return schema
777341
def dict_jsonp(param):
    """"""
    if not isinstance(param, dict):
        param = dict(param)
    return jsonp(param)