Search in sources :

Example 1 with ApiInfo

use of com.mendmix.common.model.ApiInfo in project jeesuite-libs by vakinge.

the class AppMetadataHolder method scanApiInfos.

private static synchronized void scanApiInfos(AppMetadata metadata, List<String> classNameList) {
    if (!metadata.getApis().isEmpty())
        return;
    String contextPath = GlobalRuntimeContext.getContextPath();
    String pathPrefix;
    if (ResourceUtils.containsAnyProperty("mendmix.request.pathPrefix")) {
        pathPrefix = ResourceUtils.getProperty("mendmix.request.pathPrefix");
        if (!pathPrefix.startsWith("/")) {
            pathPrefix = "/" + pathPrefix;
        }
        pathPrefix = contextPath + pathPrefix;
    } else {
        pathPrefix = contextPath;
    }
    Map<String, String> packagePathPrefixs = ResourceUtils.getMappingValues("mendmix.request.pathPrefix.mapping");
    Method[] methods;
    String baseUri;
    ApiInfo apiInfo;
    ApiMetadata classMetadata;
    ApiMetadata methodMetadata;
    for (String className : classNameList) {
        try {
            Class<?> clazz = Class.forName(className);
            if (!clazz.isAnnotationPresent(Controller.class) && !clazz.isAnnotationPresent(RestController.class))
                continue;
            // 
            if (packagePathPrefixs.containsKey(clazz.getPackage().getName())) {
                baseUri = addFirstPathSeparator(packagePathPrefixs.get(clazz.getPackage().getName()));
            } else {
                baseUri = "";
            }
            RequestMapping requestMapping = AnnotationUtils.findAnnotation(clazz, RequestMapping.class);
            if (requestMapping != null) {
                baseUri = baseUri + addFirstPathSeparator(requestMapping.value().length > 0 ? requestMapping.value()[0] : requestMapping.path()[0]);
                if (baseUri.endsWith("/")) {
                    baseUri = baseUri.substring(0, baseUri.length() - 1);
                }
            }
            // 
            classMetadata = clazz.getAnnotation(ApiMetadata.class);
            methods = clazz.getDeclaredMethods();
            Map<String, Method> interfaceMethods = getInterfaceMethods(clazz);
            methodLoop: for (Method method : methods) {
                methodMetadata = method.isAnnotationPresent(ApiMetadata.class) ? method.getAnnotation(ApiMetadata.class) : classMetadata;
                // 
                if (methodMetadata != null && methodMetadata.IntranetAccessOnly()) {
                    continue methodLoop;
                }
                String apiUri = null;
                String apiHttpMethod = null;
                requestMapping = getAnnotation(method, interfaceMethods.get(method.getName()), RequestMapping.class);
                if (requestMapping != null) {
                    apiUri = requestMapping.value()[0];
                    if (requestMapping.method() != null && requestMapping.method().length > 0) {
                        apiHttpMethod = requestMapping.method()[0].name();
                    }
                } else {
                    PostMapping postMapping = getAnnotation(method, interfaceMethods.get(method.getName()), PostMapping.class);
                    if (postMapping != null) {
                        apiUri = postMapping.value().length > 0 ? postMapping.value()[0] : postMapping.path()[0];
                        apiHttpMethod = RequestMethod.POST.name();
                    }
                    GetMapping getMapping = getAnnotation(method, interfaceMethods.get(method.getName()), GetMapping.class);
                    if (getMapping != null) {
                        apiUri = getMapping.value().length > 0 ? getMapping.value()[0] : getMapping.path()[0];
                        apiHttpMethod = RequestMethod.GET.name();
                    }
                }
                if (StringUtils.isBlank(apiUri)) {
                    continue methodLoop;
                }
                apiInfo = new ApiInfo();
                if (apiUri == null) {
                    apiUri = baseUri;
                } else {
                    apiUri = baseUri + addFirstPathSeparator(apiUri);
                }
                apiInfo.setUrl(pathPrefix + apiUri);
                apiInfo.setMethod(apiHttpMethod);
                if (methodMetadata == null) {
                    apiInfo.setPermissionType(PermissionLevel.LoginRequired);
                } else {
                    apiInfo.setPermissionType(methodMetadata.permissionLevel());
                    apiInfo.setName(methodMetadata.actionName());
                    apiInfo.setActionLog(methodMetadata.actionLog());
                    apiInfo.setRequestLog(methodMetadata.requestLog());
                    apiInfo.setResponseLog(methodMetadata.responseLog());
                    apiInfo.setOpenApi(methodMetadata.openApi());
                }
                if (StringUtils.isBlank(apiInfo.getName())) {
                    String name = apiInfo.getUrl().replace("/", "_");
                    if (name.startsWith("_"))
                        name = name.substring(1);
                    apiInfo.setName(name);
                }
                // 分页查询
                if (method.getReturnType() == Page.class) {
                    apiInfo.setResponseLog(false);
                }
                // 上传
                Class<?>[] parameterTypes = method.getParameterTypes();
                for (Class<?> type : parameterTypes) {
                    if (type == MultipartFile.class || type == MultipartFile[].class) {
                        apiInfo.setRequestLog(false);
                        break;
                    }
                }
                metadata.addApi(apiInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error className:" + className);
        }
    }
}
Also used : ApiMetadata(com.mendmix.common.annotation.ApiMetadata) Page(com.mendmix.common.model.Page) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) MultipartFile(org.springframework.web.multipart.MultipartFile) GetMapping(org.springframework.web.bind.annotation.GetMapping) PostMapping(org.springframework.web.bind.annotation.PostMapping) ApiInfo(com.mendmix.common.model.ApiInfo)

Example 2 with ApiInfo

use of com.mendmix.common.model.ApiInfo in project jeesuite-libs by vakinge.

the class RewriteBodyServerHttpResponse method writeWith.

@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    HttpHeaders headers = exchange.getResponse().getHeaders();
    if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
        return super.writeWith(body);
    }
    boolean isNullBody = !headers.containsKey(HttpHeaders.TRANSFER_ENCODING) && headers.getContentLength() == 0;
    if (isNullBody) {
        for (PostFilterHandler handler : handlers) {
            bodyString = handler.process(exchange, module, bodyString);
        }
        if (bodyString != null) {
            byte[] bytes = bodyString.getBytes();
            DataBuffer dataBuffer = bufferFactory.wrap(bytes);
            headers.setContentLength(bytes.length);
            return super.writeWith(Flux.just(dataBuffer));
        }
        return super.writeWith(body);
    }
    MediaType contentType = headers.getContentType();
    if (contentType == null || !contentType.getType().equals(MediaType.APPLICATION_JSON.getType())) {
        return super.writeWith(body);
    }
    boolean buildNewResponse = rewriteEnabled && !module.isBodyRewriteIgnore();
    // 
    if (buildNewResponse) {
        buildNewResponse = !headers.containsKey(CustomRequestHeaders.HEADER_RESP_KEEP);
    }
    // 
    if (buildNewResponse) {
        buildNewResponse = !exchange.getRequest().getHeaders().containsKey(CustomRequestHeaders.HEADER_RESP_KEEP);
    }
    if (!buildNewResponse && GatewayConfigs.actionLogEnabled) {
        ApiInfo apiInfo = module.getApiInfo(exchange.getRequest().getMethodValue(), exchange.getRequest().getPath().value());
        buildNewResponse = apiInfo != null && apiInfo.isActionLog() && apiInfo.isResponseLog();
    }
    if (!buildNewResponse) {
        return super.writeWith(body);
    }
    if (body instanceof Flux) {
        Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
            DataBuffer dataBuffer = bufferFactory.join(dataBuffers);
            byte[] content = handleReadResponseBody(dataBuffer);
            return bufferFactory.wrap(content);
        }));
    }
    return super.writeWith(body);
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LoggerFactory(org.slf4j.LoggerFactory) PostFilterHandler(com.mendmix.gateway.filter.PostFilterHandler) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) BizSystemModule(com.mendmix.gateway.model.BizSystemModule) ByteArrayInputStream(java.io.ByteArrayInputStream) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) GatewayConfigs(com.mendmix.gateway.GatewayConfigs) ServerHttpResponseDecorator(org.springframework.http.server.reactive.ServerHttpResponseDecorator) Logger(org.slf4j.Logger) HttpHeaders(org.springframework.http.HttpHeaders) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) StandardCharsets(java.nio.charset.StandardCharsets) Flux(reactor.core.publisher.Flux) List(java.util.List) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ApiInfo(com.mendmix.common.model.ApiInfo) CustomRequestHeaders(com.mendmix.common.CustomRequestHeaders) GZIPOutputStream(java.util.zip.GZIPOutputStream) ResourceUtils(com.mendmix.common.util.ResourceUtils) Comparator(java.util.Comparator) FileCopyUtils(org.springframework.util.FileCopyUtils) HttpHeaders(org.springframework.http.HttpHeaders) PostFilterHandler(com.mendmix.gateway.filter.PostFilterHandler) ApiInfo(com.mendmix.common.model.ApiInfo) Flux(reactor.core.publisher.Flux) MediaType(org.springframework.http.MediaType) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 3 with ApiInfo

use of com.mendmix.common.model.ApiInfo in project jeesuite-libs by vakinge.

the class RequestLogHanlder method process.

@Override
public Builder process(ServerWebExchange exchange, BizSystemModule module, Builder requestBuilder) {
    if (RuequestHelper.isWebSocketRequest(exchange.getRequest())) {
        return requestBuilder;
    }
    ActionLog actionLog = exchange.getAttribute(ActionLogCollector.CURRENT_LOG_CONTEXT_NAME);
    if (actionLog == null)
        return requestBuilder;
    actionLog.setModuleId(module.getServiceId());
    ServerHttpRequest request = exchange.getRequest();
    ApiInfo apiInfo = RuequestHelper.getCurrentApi(exchange);
    if (apiInfo != null && !apiInfo.isRequestLog()) {
        return requestBuilder;
    }
    actionLog.setQueryParameters(JsonUtils.toJson(request.getQueryParams()));
    if (HttpMethod.POST.equals(request.getMethod()) && !isMultipartRequest(request)) {
        try {
            String data = RuequestHelper.getCachingBodyString(exchange);
            actionLog.setRequestData(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return requestBuilder;
}
Also used : ApiInfo(com.mendmix.common.model.ApiInfo) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ActionLog(com.mendmix.logging.integrate.ActionLog)

Example 4 with ApiInfo

use of com.mendmix.common.model.ApiInfo in project jeesuite-libs by vakinge.

the class SignatureRequestHandler method process.

@Override
public Builder process(ServerWebExchange exchange, BizSystemModule module, Builder requestBuilder) {
    ApiInfo apiInfo = module.getApiInfo(exchange.getRequest().getMethodValue(), exchange.getRequest().getPath().value());
    if (apiInfo == null || !apiInfo.isOpenApi()) {
        throw new JeesuiteBaseException("该接口未开放访问权限");
    }
    HttpHeaders headers = exchange.getRequest().getHeaders();
    String sign = headers.getFirst(GatewayConstants.X_SIGN_HEADER);
    if (StringUtils.isBlank(sign))
        return requestBuilder;
    if (StringUtils.isBlank(sign))
        return requestBuilder;
    String timestamp = headers.getFirst(GatewayConstants.TIMESTAMP_HEADER);
    String appId = headers.getFirst(GatewayConstants.APP_ID_HEADER);
    if (StringUtils.isAnyBlank(timestamp, appId)) {
        throw new JeesuiteBaseException("认证头信息不完整");
    }
    String secret = appIdSecretMappings.get(appId);
    if (StringUtils.isBlank(secret)) {
        throw new JeesuiteBaseException("appId不存在");
    }
    Object body = RuequestHelper.getCachingBodyString(exchange);
    Map<String, Object> map = JsonUtils.toHashMap(body.toString(), Object.class);
    String signBaseString = StringUtils.trimToEmpty(ParameterUtils.mapToQueryParams(map)) + timestamp + secret;
    String expectSign = DigestUtils.md5(signBaseString);
    if (!expectSign.equals(sign)) {
        throw new JeesuiteBaseException("签名错误");
    }
    return requestBuilder;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) JeesuiteBaseException(com.mendmix.common.JeesuiteBaseException) ApiInfo(com.mendmix.common.model.ApiInfo)

Example 5 with ApiInfo

use of com.mendmix.common.model.ApiInfo in project jeesuite-libs by vakinge.

the class RuequestHelper method getCurrentApi.

public static ApiInfo getCurrentApi(ServerWebExchange exchange) {
    ApiInfo api = exchange.getAttribute(GatewayConstants.CONTEXT_CURRENT_API);
    if (api != null)
        return api;
    BizSystemModule module = getCurrentModule(exchange);
    ServerHttpRequest request = exchange.getRequest();
    ApiInfo apiInfo = module.getApiInfo(request.getMethodValue(), request.getPath().value());
    if (apiInfo != null) {
        exchange.getAttributes().put(GatewayConstants.CONTEXT_CURRENT_API, apiInfo);
    }
    return apiInfo;
}
Also used : ApiInfo(com.mendmix.common.model.ApiInfo) BizSystemModule(com.mendmix.gateway.model.BizSystemModule) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest)

Aggregations

ApiInfo (com.mendmix.common.model.ApiInfo)10 BizSystemModule (com.mendmix.gateway.model.BizSystemModule)4 ActionLog (com.mendmix.logging.integrate.ActionLog)3 HttpHeaders (org.springframework.http.HttpHeaders)3 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)3 JeesuiteBaseException (com.mendmix.common.JeesuiteBaseException)2 ArrayList (java.util.ArrayList)2 CustomRequestHeaders (com.mendmix.common.CustomRequestHeaders)1 ApiMetadata (com.mendmix.common.annotation.ApiMetadata)1 Page (com.mendmix.common.model.Page)1 ResourceUtils (com.mendmix.common.util.ResourceUtils)1 GatewayConfigs (com.mendmix.gateway.GatewayConfigs)1 PostFilterHandler (com.mendmix.gateway.filter.PostFilterHandler)1 ApiPermission (com.mendmix.security.model.ApiPermission)1 AppMetadata (com.mendmix.springweb.model.AppMetadata)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 StandardCharsets (java.nio.charset.StandardCharsets)1