io.swagger.util.PrimitiveType Java Examples

The following examples show how to use io.swagger.util.PrimitiveType. 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: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private Parameter readParam(Swagger swagger, Type type, Class<?> cls, ApiParam param) {
    PrimitiveType fromType = PrimitiveType.fromType(type);
    final Parameter para = null == fromType ? new BodyParameter() : new QueryParameter();
    Parameter parameter = ParameterProcessor.applyAnnotations(swagger, para, type,
        null == param ? new ArrayList<Annotation>()
            : Collections.<Annotation> singletonList(param));
    if (parameter instanceof AbstractSerializableParameter) {
        final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
        if (p.getType() == null) {
            p.setType(null == fromType ? "string" : fromType.getCommonName());
        }
        p.setRequired(p.getRequired() || cls.isPrimitive());
    } else {
        //hack: Get the from data model paramter from BodyParameter
        BodyParameter bp = (BodyParameter) parameter;
        bp.setIn("body");
        Property property = ModelConverters.getInstance().readAsProperty(type);
        final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(
            PropertyBuilder.PropertyId.class);
        bp.setSchema(PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
    }
    return parameter;
}
 
Example #2
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 6 votes vote down vote up
private Parameter readParam(Swagger swagger, Type type,Class<?> cls, ApiParam param) {
	PrimitiveType fromType = PrimitiveType.fromType(type);
	final Parameter para = null == fromType ? new BodyParameter() : new QueryParameter();
	Parameter parameter = ParameterProcessor.applyAnnotations(swagger, para,
			type == null ? String.class : type, null == param ? new ArrayList<Annotation>()
					: Collections.<Annotation> singletonList(param));
	if (parameter instanceof AbstractSerializableParameter) {
		final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
		if (p.getType() == null) p.setType(null == fromType ? "string" : fromType.getCommonName());
		p.setRequired(p.getRequired() == true ? true : cls.isPrimitive());
	}else{
	    //hack: Get the from data model paramter from BodyParameter
	    BodyParameter bp = (BodyParameter)parameter;
	    bp.setIn("formData");
	}
	return parameter;
}
 
Example #3
Source File: SwaggerReader.java    From netty-rest with Apache License 2.0 6 votes vote down vote up
public SwaggerReader(Swagger swagger, ObjectMapper mapper, BiConsumer<Method, Operation> swaggerOperationConsumer, Map<Class, PrimitiveType> externalTypes)
{
    this.swagger = swagger;
    modelConverters = new ModelConverters(mapper);
    this.swaggerOperationConsumer = swaggerOperationConsumer;
    modelConverters.addConverter(new ModelResolver(mapper));
    if (externalTypes != null) {
        setExternalTypes(externalTypes);
    }
    mapper.registerModule(
            new SimpleModule("swagger", Version.unknownVersion()) {
                @Override
                public void setupModule(SetupContext context) {
                    context.insertAnnotationIntrospector(new SwaggerJacksonAnnotationIntrospector());
                }
            });
    errorProperty = modelConverters.readAsProperty(HttpServer.ErrorMessage.class);
    swagger.addDefinition("ErrorMessage", modelConverters.read(HttpServer.ErrorMessage.class).entrySet().iterator().next().getValue());
}
 
Example #4
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParam(Swagger swagger, ApiImplicitParam param) {
    PrimitiveType fromType = PrimitiveType.fromName(param.paramType());
    final Parameter p = null == fromType ? new FormParameter() : new QueryParameter();
    final Type type = ReflectionUtils.typeFromString(param.dataType());
    return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
        Collections.<Annotation> singletonList(param));
}
 
Example #5
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParam(Swagger swagger, ApiImplicitParam param) {
	PrimitiveType fromType = PrimitiveType.fromName(param.paramType());
	final Parameter p = null == fromType ? new FormParameter() : new QueryParameter();
	final Type type = ReflectionUtils.typeFromString(param.dataType());
	return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
			Collections.<Annotation> singletonList(param));
}
 
Example #6
Source File: ResourceReaderExtension.java    From mdw with Apache License 2.0 5 votes vote down vote up
private Type typeFromString(String type) {
    if (type == null || type.isEmpty()) {
        return null;
    }
    final PrimitiveType primitive = PrimitiveType.fromName(type);
    if (primitive != null) {
        return primitive.getKeyClass();
    }
    try {
        return Class.forName(type);
    }
    catch (ClassNotFoundException cnfe) {
        // use package classloader
        int lastDot = type.lastIndexOf('.');
        if (lastDot > 0) {
            String pkgName = type.substring(0, lastDot);
            Package pkg = PackageCache.getPackage(pkgName);
            if (pkg != null) {
                try {
                    logger.debug("Loading type: " + type + " using " + pkg.getName() + "'s ClassLoader");
                    return pkg.getClassLoader().loadClass(type);
                }
                catch (ClassNotFoundException cnfe2) {
                    logger.error(String.format("Failed to resolve '%s' into class", type), cnfe);
                }
            }
        }
    }
    return null;
}
 
Example #7
Source File: SwaggerWorkflowReader.java    From mdw with Apache License 2.0 5 votes vote down vote up
private Type typeFromString(String type) {
    if (type == null || type.isEmpty()) {
        return null;
    }
    final PrimitiveType primitive = PrimitiveType.fromName(type);
    if (primitive != null) {
        return primitive.getKeyClass();
    }
    try {
        return Class.forName(type);
    }
    catch (ClassNotFoundException cnfe) {
        // use package classloader
        int lastDot = type.lastIndexOf('.');
        if (lastDot > 0) {
            String pkgName = type.substring(0, lastDot);
            Package pkg = PackageCache.getPackage(pkgName);
            if (pkg != null) {
                try {
                    logger.debug("Loading type: " + type + " using " + pkg.getName() + "'s ClassLoader");
                    return pkg.getClassLoader().loadClass(type);
                }
                catch (ClassNotFoundException cnfe2) {
                    logger.error(String.format("Failed to resolve '%s' into class", type), cnfe);
                }
            }
        }
    }
    return null;
}
 
Example #8
Source File: HttpServer.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
HttpServer(Set<HttpService> httpServicePlugins,
            Set<WebSocketService> websocketServices,
            Swagger swagger, EventLoopGroup eventLoopGroup,
            List<PreprocessorEntry> preProcessors,
            ImmutableList<PostProcessorEntry> postProcessors,
            ObjectMapper mapper,
            Map<Class, PrimitiveType> overriddenMappings,
            HttpServerBuilder.ExceptionHandler exceptionHandler,
            Map<String, IRequestParameterFactory> customParameters,
            BiConsumer<Method, Operation> swaggerOperationConsumer,
            boolean useEpoll,
            boolean proxyProtocol,
            long maximumBodySize,
            boolean debugMode)
    {
        this.routeMatcher = new RouteMatcher();
        this.preProcessors = preProcessors;
        this.workerGroup = requireNonNull(eventLoopGroup, "eventLoopGroup is null");
        this.swagger = requireNonNull(swagger, "swagger is null");
        this.mapper = mapper;
        this.customParameters = customParameters;
        this.swaggerOperationConsumer = swaggerOperationConsumer;
        this.uncaughtExceptionHandler = exceptionHandler == null ? (t, e) -> {
        } : exceptionHandler;
        this.postProcessors = postProcessors;
        this.proxyProtocol = proxyProtocol;
        this.maximumBodySize = maximumBodySize;
        this.debugMode = debugMode;

        this.bossGroup = useEpoll ? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1);
        registerEndPoints(requireNonNull(httpServicePlugins, "httpServices is null"), overriddenMappings);
        registerWebSocketPaths(requireNonNull(websocketServices, "webSocketServices is null"));
//        routeMatcher.add(GET, "/api/swagger.json", this::swaggerApiHandle);
        this.useEpoll = useEpoll && Epoll.isAvailable();
        this.processingRequests = new ConcurrentHashMap<>();
    }
 
Example #9
Source File: SwaggerReader.java    From netty-rest with Apache License 2.0 5 votes vote down vote up
public static Type typeFromString(String type)
    {
        final PrimitiveType primitive = PrimitiveType.fromName(type);
        if (primitive != null) {
            return primitive.getKeyClass();
        }
        try {
            return Class.forName(type);
        }
        catch (Exception e) {
//            LOGGER.error(String.format("Failed to resolve '%s' into class", type), e);
        }
        return null;
    }
 
Example #10
Source File: HttpServer.java    From netty-rest with Apache License 2.0 4 votes vote down vote up
private void registerEndPoints(Set<HttpService> httpServicePlugins, Map<Class, PrimitiveType> overriddenMappings)
    {
        Map<Class, PrimitiveType> swaggerBeanMappings;
        if (overriddenMappings != null) {
            swaggerBeanMappings = ImmutableMap.<Class, PrimitiveType>builder().putAll(this.swaggerBeanMappings).putAll(overriddenMappings).build();
        }
        else {
            swaggerBeanMappings = this.swaggerBeanMappings;
        }

        SwaggerReader reader = new SwaggerReader(swagger, mapper, swaggerOperationConsumer, swaggerBeanMappings);

        httpServicePlugins.forEach(service -> {
//            reader.read(service.getClass());
            if (!service.getClass().isAnnotationPresent(Path.class)) {
                throw new IllegalStateException(format("HttpService class %s must have javax.ws.rs.Path annotation", service.getClass()));
            }
            String mainPath = service.getClass().getAnnotation(Path.class).value();
            if (mainPath == null) {
                throw new IllegalStateException(format("Classes that implement HttpService must have %s annotation.", Path.class.getCanonicalName()));
            }
            RouteMatcher.MicroRouteMatcher microRouteMatcher = new RouteMatcher.MicroRouteMatcher(routeMatcher, mainPath);

            for (Method method : service.getClass().getMethods()) {
                Path annotation = method.getAnnotation(Path.class);

                if (annotation == null) {
                    continue;
                }

                method.setAccessible(true);
                String lastPath = annotation.value();
                Iterator<HttpMethod> methodExists = Arrays.stream(method.getAnnotations())
                        .filter(ann -> ann.annotationType().isAnnotationPresent(javax.ws.rs.HttpMethod.class))
                        .map(ann -> HttpMethod.valueOf(ann.annotationType().getAnnotation(javax.ws.rs.HttpMethod.class).value()))
                        .iterator();

                final JsonRequest jsonRequest = method.getAnnotation(JsonRequest.class);

                // if no @Path annotation exists and @JsonRequest annotation is present, bind POST httpMethod by default.
                if (!methodExists.hasNext() && jsonRequest != null) {
                    microRouteMatcher.add(lastPath, POST, getJsonRequestHandler(method, service));
                }
                else {
                    while (methodExists.hasNext()) {
                        HttpMethod httpMethod = methodExists.next();

                        if (jsonRequest != null && httpMethod != POST) {
                            if (Arrays.stream(method.getParameters()).anyMatch(p -> p.isAnnotationPresent(ApiParam.class))) {
                                throw new IllegalStateException("@ApiParam annotation can only be used within POST requests");
                            }
                            if (method.getParameterCount() == 1 && method.getParameters()[0].isAnnotationPresent(BodyParam.class)) {
                                throw new IllegalStateException("@ParamBody annotation can only be used within POST requests");
                            }
                        }

                        HttpRequestHandler handler;
                        if (httpMethod == GET && !method.getReturnType().equals(void.class)) {
                            handler = createGetRequestHandler(service, method);
                        }
                        else if (isRawRequestMethod(method)) {
                            handler = generateRawRequestHandler(service, method);
                        }
                        else {
                            handler = getJsonRequestHandler(method, service);
                        }

                        microRouteMatcher.add(lastPath, httpMethod, handler);
                    }
                }
            }
        });

        swagger.getDefinitions().forEach((k, v) -> Optional.ofNullable(v)
                .map(a -> a.getProperties())
                .ifPresent(a -> a.values().forEach(x -> x.setReadOnly(null))));
    }
 
Example #11
Source File: HttpServerBuilder.java    From netty-rest with Apache License 2.0 4 votes vote down vote up
public HttpServerBuilder setOverridenMappings(Map<Class, PrimitiveType> overridenMappings)
{
    this.overridenMappings = overridenMappings;
    return this;
}