2020-06-17 10:34:20 +00:00
|
|
|
import * as querystring from 'querystring'
|
|
|
|
|
2020-07-06 08:10:33 +00:00
|
|
|
import { web, plugin } from '@ccms/api'
|
2020-06-30 08:02:39 +00:00
|
|
|
import { provideSingleton, JSClass, postConstruct, Container, ContainerInstance, inject } from '@ccms/container'
|
2020-06-17 10:34:20 +00:00
|
|
|
|
2020-06-30 08:02:39 +00:00
|
|
|
import { WebProxyBeanName, FilterProxyBeanName, METADATA_KEY, PARAM_TYPE } from './constants'
|
|
|
|
import { Context, InterceptorAdapter, RequestHandler, interfaces } from './interfaces'
|
2020-07-06 08:10:33 +00:00
|
|
|
import { getControllerActions, getActionMetadata, getControllerMetadata, getActionParams, getControllerMetadatas } from './decorators'
|
2020-06-30 08:02:39 +00:00
|
|
|
|
|
|
|
const HttpServletRequestWrapper = Java.type('javax.servlet.http.HttpServletRequestWrapper')
|
|
|
|
const HttpServletResponseWrapper = Java.type('javax.servlet.http.HttpServletResponseWrapper')
|
|
|
|
const ServletInputStream = Java.type('javax.servlet.ServletInputStream')
|
|
|
|
const ServletOutputStream = Java.type('javax.servlet.ServletOutputStream')
|
2020-06-17 10:34:20 +00:00
|
|
|
|
|
|
|
@provideSingleton(web.Server)
|
|
|
|
export class Server {
|
|
|
|
@JSClass('pw.yumc.MiaoScript.web.WebServerProxy')
|
|
|
|
private WebServerProxy: any
|
|
|
|
@JSClass('pw.yumc.MiaoScript.web.WebFilterProxy')
|
|
|
|
private WebFilterProxy: any
|
|
|
|
|
2020-06-30 08:02:39 +00:00
|
|
|
@inject(ContainerInstance)
|
|
|
|
private container: Container
|
|
|
|
|
2020-06-17 10:34:20 +00:00
|
|
|
private StreamUtils = org.springframework.util.StreamUtils
|
|
|
|
private ResponseEntity = org.springframework.http.ResponseEntity
|
|
|
|
|
2020-07-06 09:41:50 +00:00
|
|
|
private controllerActions: Map<string, interfaces.ActionMetadata[]>
|
2020-06-17 10:34:20 +00:00
|
|
|
private interceptors: Map<string, InterceptorAdapter>
|
2020-06-30 08:02:39 +00:00
|
|
|
private methodMappings: Map<string, Map<string, RequestHandler>>
|
2020-06-17 10:34:20 +00:00
|
|
|
|
|
|
|
private beanFactory: org.springframework.beans.factory.support.DefaultListableBeanFactory
|
|
|
|
|
|
|
|
@postConstruct()
|
|
|
|
initialization() {
|
|
|
|
this.beanFactory = base.getInstance().getAutowireCapableBeanFactory()
|
2020-07-06 09:41:50 +00:00
|
|
|
this.controllerActions = new Map()
|
2020-06-17 10:34:20 +00:00
|
|
|
this.interceptors = new Map()
|
2020-06-30 08:02:39 +00:00
|
|
|
this.methodMappings = new Map()
|
2020-06-17 10:34:20 +00:00
|
|
|
this.start()
|
2020-07-06 08:10:33 +00:00
|
|
|
process.on('plugin.after.enable', (plugin: plugin.Plugin) => this.registryPlugin(plugin))
|
|
|
|
process.on('plugin.after.disable', (plugin: plugin.Plugin) => this.unregistryPlugin(plugin))
|
2020-06-17 10:34:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
|
|
|
this.registryFilterProxy()
|
|
|
|
this.registryWebProxy()
|
|
|
|
}
|
|
|
|
|
|
|
|
stop() {
|
|
|
|
try {
|
|
|
|
this.beanFactory.destroySingleton(FilterProxyBeanName)
|
|
|
|
this.beanFactory.destroySingleton(WebProxyBeanName)
|
2021-12-25 17:21:06 +00:00
|
|
|
} catch (error: any) {
|
2020-06-17 10:34:20 +00:00
|
|
|
console.ex(error)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:10:33 +00:00
|
|
|
registryPlugin(plugin: plugin.Plugin) {
|
|
|
|
let controllers = getControllerMetadatas(plugin).values()
|
|
|
|
for (const controller of controllers) {
|
|
|
|
console.debug(`Plugin ${plugin.description.name} Registry Controller ${controller.name}.`)
|
|
|
|
this.registryController(controller.target)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unregistryPlugin(plugin: plugin.Plugin) {
|
|
|
|
let controllers = getControllerMetadatas(plugin).values()
|
|
|
|
for (const controller of controllers) {
|
|
|
|
console.debug(`Plugin ${plugin.description.name} Unregistry Controller ${controller.name}.`)
|
|
|
|
this.unregistryController(controller.target)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-30 08:02:39 +00:00
|
|
|
registryController(target: any) {
|
|
|
|
if (!target) { throw new Error('Controller can\'t be undefiend!') }
|
|
|
|
let controllerMetadata = getControllerMetadata(target)
|
|
|
|
if (!controllerMetadata) { throw new Error(`Controller ${target.name} must have @Controller decorator!`) }
|
2020-07-06 08:10:33 +00:00
|
|
|
target = this.bindController(target)
|
2020-06-30 08:02:39 +00:00
|
|
|
let actions = getControllerActions(target)
|
2020-07-06 09:41:50 +00:00
|
|
|
this.controllerActions.set(controllerMetadata.name, [])
|
2020-06-30 08:02:39 +00:00
|
|
|
for (const action of actions) {
|
|
|
|
let actionMetadata = getActionMetadata(target, action)
|
2020-07-06 09:41:50 +00:00
|
|
|
this.controllerActions.get(controllerMetadata.name).push(actionMetadata)
|
2020-06-30 08:02:39 +00:00
|
|
|
let path = `${controllerMetadata.path || ''}${actionMetadata.path || ''}`
|
|
|
|
if (!path) throw new Error(`Controller ${controllerMetadata.name} Action ${actionMetadata.name} path is empty!`)
|
|
|
|
if (!this.methodMappings.has(path)) { this.methodMappings.set(path, new Map()) }
|
2020-07-06 08:10:33 +00:00
|
|
|
console.debug(`Controller ${controllerMetadata.name} Registry ${path} Action to ${actionMetadata.executor || '<anonymous>'} function.`)
|
2020-06-30 08:02:39 +00:00
|
|
|
this.methodMappings.get(path).set(actionMetadata.method || 'ALL', (ctx: Context) => {
|
|
|
|
let args = []
|
|
|
|
let params = getActionParams(target, action)
|
|
|
|
for (const index in params) {
|
|
|
|
let param = params[index]
|
|
|
|
let paramValue = undefined
|
|
|
|
switch (param.type) {
|
|
|
|
case PARAM_TYPE.REQUEST: paramValue = ctx.request; break
|
|
|
|
case PARAM_TYPE.RESPONSE: paramValue = ctx.response; break
|
|
|
|
case PARAM_TYPE.QUERY: paramValue = ctx.params[param.name]; break
|
|
|
|
case PARAM_TYPE.HEADER: paramValue = ctx.headers[param.name]; break
|
|
|
|
case PARAM_TYPE.BODY: paramValue = ctx.body; break
|
|
|
|
case PARAM_TYPE.COOKIE: paramValue = ctx.cookies[param.name]; break
|
|
|
|
}
|
|
|
|
if (param.require && !paramValue) {
|
|
|
|
return {
|
|
|
|
status: 400,
|
|
|
|
msg: param.message ?? `Param Type ${param.type} require not empty!`,
|
|
|
|
data: param
|
|
|
|
}
|
|
|
|
}
|
|
|
|
args[param.index] = paramValue ?? param.default
|
|
|
|
}
|
|
|
|
return target[actionMetadata.executor].apply(target, args)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:10:33 +00:00
|
|
|
private bindController(target: any) {
|
|
|
|
try {
|
|
|
|
this.container.rebind(METADATA_KEY.Controller).to(target).inSingletonScope().whenTargetNamed(target.name)
|
|
|
|
} catch{
|
|
|
|
this.container.bind(METADATA_KEY.Controller).to(target).inSingletonScope().whenTargetNamed(target.name)
|
|
|
|
}
|
|
|
|
return this.container.getNamed(METADATA_KEY.Controller, target.name)
|
|
|
|
}
|
|
|
|
|
2020-06-30 08:02:39 +00:00
|
|
|
unregistryController(target: any) {
|
|
|
|
if (!target) { throw new Error('Controller can\'t be undefiend!') }
|
|
|
|
let controllerMetadata = getControllerMetadata(target)
|
|
|
|
if (!controllerMetadata) { throw new Error(`Controller ${target.name} must have @Controller decorator!`) }
|
2020-07-06 09:41:50 +00:00
|
|
|
if (!this.controllerActions.has(controllerMetadata.name)) { return console.warn(`Controller ${controllerMetadata.name} not registry!`) }
|
|
|
|
let actions = this.controllerActions.get(controllerMetadata.name)
|
|
|
|
for (const actionMetadata of actions) {
|
2020-06-30 08:02:39 +00:00
|
|
|
let path = `${controllerMetadata.path || ''}${actionMetadata.path || ''}`
|
|
|
|
if (!this.methodMappings.has(path)) { continue }
|
|
|
|
this.methodMappings.get(path).delete(actionMetadata.method)
|
2020-07-06 08:10:33 +00:00
|
|
|
console.debug(`Controller ${controllerMetadata.name} Unregistry ${path} Action.`)
|
2020-06-30 08:02:39 +00:00
|
|
|
}
|
2020-07-06 09:41:50 +00:00
|
|
|
this.controllerActions.delete(controllerMetadata.name)
|
2020-06-30 08:02:39 +00:00
|
|
|
}
|
|
|
|
|
2020-06-17 10:34:20 +00:00
|
|
|
registryMapping(path: string, handler: RequestHandler) {
|
|
|
|
console.debug(`Registry Mapping ${path} to handle ${handler.name || '<anonymous>'} function.`)
|
2020-06-30 08:02:39 +00:00
|
|
|
if (!this.methodMappings.has(path)) { this.methodMappings.set(path, new Map()) }
|
|
|
|
this.methodMappings.get(path).set("ALL", handler)
|
2020-06-17 10:34:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
unregistryMapping(path: string) {
|
2020-06-30 08:02:39 +00:00
|
|
|
if (this.methodMappings.has(path)) { this.methodMappings.get(path).delete("ALL") }
|
2020-06-17 10:34:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
registryInterceptor(interceptor: InterceptorAdapter) {
|
|
|
|
console.debug(`Registry ${interceptor.name} Interceptor.`)
|
|
|
|
this.interceptors.set(interceptor.name, interceptor)
|
|
|
|
}
|
|
|
|
|
2020-07-06 08:10:33 +00:00
|
|
|
unregistryInterceptor(interceptor: string | InterceptorAdapter) {
|
|
|
|
if (typeof interceptor === "string") { interceptor = { name: interceptor } }
|
|
|
|
console.debug(`Unregistry ${interceptor.name} Interceptor.`)
|
2020-06-17 10:34:20 +00:00
|
|
|
this.interceptors.delete(interceptor.name)
|
|
|
|
}
|
|
|
|
|
|
|
|
private registryFilterProxy() {
|
2021-12-25 17:21:06 +00:00
|
|
|
try { this.beanFactory.destroySingleton(FilterProxyBeanName) } catch (ex: any) { }
|
2020-06-17 10:34:20 +00:00
|
|
|
var WebFilterProxyNashorn = Java.extend(this.WebFilterProxy, {
|
|
|
|
doFilter: (servletRequest: javax.servlet.http.HttpServletRequest, servletResponse: javax.servlet.http.HttpServletResponse, filterChain: javax.servlet.FilterChain) => {
|
|
|
|
filterChain.doFilter(servletRequest, servletResponse)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
this.beanFactory.registerSingleton(FilterProxyBeanName, new WebFilterProxyNashorn())
|
|
|
|
}
|
|
|
|
|
2020-06-30 08:02:39 +00:00
|
|
|
// private getRequestWrapper(servletRequest: javax.servlet.http.HttpServletRequest) {
|
|
|
|
// var body = org.springframework.util.StreamUtils.copyToByteArray(servletRequest.getInputStream())
|
|
|
|
// var HttpServletRequestWrapperAdapter = Java.extend(HttpServletRequestWrapper, {
|
|
|
|
// getInputStream: () => {
|
|
|
|
// var bais = new java.io.ByteArrayInputStream(body)
|
|
|
|
// return new ServletInputStream({
|
|
|
|
// read: () => bais.read(),
|
|
|
|
// isFinished: () => bais.available() == 0
|
|
|
|
// })
|
|
|
|
// }
|
|
|
|
// })
|
|
|
|
// var wrapper = new HttpServletRequestWrapperAdapter(servletRequest)
|
|
|
|
// return wrapper
|
|
|
|
// }
|
|
|
|
|
|
|
|
// private getResponseWrapper(servletResponse: javax.servlet.http.HttpServletResponse) {
|
|
|
|
// var HttpServletRequestWrapperAdapter = Java.extend(HttpServletRequestWrapper, {
|
|
|
|
// getOutputStream: () => {
|
|
|
|
// return new ServletOutputStream({
|
|
|
|
// })
|
|
|
|
// }
|
|
|
|
// })
|
|
|
|
// var wrapper = new HttpServletRequestWrapperAdapter(servletResponse)
|
|
|
|
// return wrapper
|
|
|
|
// }
|
|
|
|
|
2020-07-06 08:10:33 +00:00
|
|
|
private notFound(ctx: Context) {
|
2020-06-30 08:02:39 +00:00
|
|
|
return {
|
|
|
|
status: 404,
|
|
|
|
msg: "handlerMapping Not Found!",
|
2020-07-06 08:10:33 +00:00
|
|
|
method: ctx.request.getMethod(),
|
|
|
|
path: ctx.request.getRequestURI(),
|
2020-06-30 08:02:39 +00:00
|
|
|
timestamp: Date.now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-17 10:34:20 +00:00
|
|
|
private registryWebProxy() {
|
2021-12-25 17:21:06 +00:00
|
|
|
try { this.beanFactory.destroySingleton(WebProxyBeanName) } catch (ex: any) { }
|
2020-06-17 10:34:20 +00:00
|
|
|
var WebServerProxyNashorn = Java.extend(this.WebServerProxy, {
|
|
|
|
process: (req: javax.servlet.http.HttpServletRequest, resp: javax.servlet.http.HttpServletResponse) => {
|
2020-07-06 08:10:33 +00:00
|
|
|
let ctx: Context = { request: req, response: resp, params: {}, body: {} }
|
2020-06-17 10:34:20 +00:00
|
|
|
ctx.url = req.getRequestURI()
|
|
|
|
// @ts-ignore
|
2020-06-30 08:02:39 +00:00
|
|
|
ctx.headers = { __noSuchProperty__: (name: string) => req.getHeader(name) }
|
|
|
|
ctx.cookies = {}
|
|
|
|
for (const cookie of (req.getCookies() || [])) {
|
|
|
|
ctx.cookies[cookie.getName()] = cookie.getValue()
|
|
|
|
}
|
2020-06-17 10:34:20 +00:00
|
|
|
if (req.getQueryString()) {
|
|
|
|
ctx.url += `?${req.getQueryString()}`
|
|
|
|
ctx.params = querystring.parse(req.getQueryString())
|
|
|
|
}
|
|
|
|
if (req.getMethod() == "POST") {
|
|
|
|
ctx.body = this.StreamUtils.copyToString(req.getInputStream(), java.nio.charset.StandardCharsets.UTF_8)
|
2020-06-30 08:02:39 +00:00
|
|
|
if ((ctx.headers['Content-Type'] || '').includes('application/json')) {
|
2020-06-17 10:34:20 +00:00
|
|
|
try {
|
|
|
|
ctx.body = JSON.parse(ctx.body)
|
2021-12-25 17:21:06 +00:00
|
|
|
} catch (error: any) {
|
2020-06-17 10:34:20 +00:00
|
|
|
return {
|
|
|
|
status: 500,
|
|
|
|
msg: `parse json body error: ${error}`,
|
|
|
|
path: ctx.url,
|
|
|
|
error: console.stack(error, false),
|
|
|
|
timestamp: Date.now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let result = this.process(ctx)
|
|
|
|
result?.status && resp.setStatus(result.status)
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
})
|
|
|
|
this.beanFactory.registerSingleton(WebProxyBeanName, new WebServerProxyNashorn())
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private process(ctx: Context) {
|
|
|
|
let startTime = Date.now()
|
|
|
|
for (const [_, interceptor] of this.interceptors) {
|
|
|
|
if (interceptor.preHandle) {
|
|
|
|
try {
|
|
|
|
let startTime = Date.now()
|
|
|
|
ctx.result = interceptor.preHandle(ctx)
|
|
|
|
let preHandleTime = Date.now() - startTime
|
|
|
|
if (preHandleTime > 20) {
|
|
|
|
console.debug(`[WARN] Interceptor ${interceptor.name} preHandle cost time ${preHandleTime}ms!`)
|
|
|
|
}
|
|
|
|
if (ctx.result) { return ctx.result }
|
2021-12-25 17:21:06 +00:00
|
|
|
} catch (error: any) {
|
2020-06-17 10:34:20 +00:00
|
|
|
console.ex(error)
|
|
|
|
return {
|
|
|
|
status: 500,
|
|
|
|
msg: `Interceptor ${interceptor.name} preHandle error: ${error}`,
|
|
|
|
path: ctx.url,
|
|
|
|
error: console.stack(error, false),
|
|
|
|
timestamp: Date.now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-06 08:10:33 +00:00
|
|
|
let path = ctx.request.getRequestURI()
|
|
|
|
if (!this.methodMappings.has(path)) return this.notFound(ctx)
|
|
|
|
let mappings = this.methodMappings.get(ctx.request.getRequestURI())
|
|
|
|
ctx.handler = mappings.get(ctx.request.getMethod()) || mappings.get("ALL")
|
2020-06-17 10:34:20 +00:00
|
|
|
ctx.result = this.execRequestHandle(ctx)
|
|
|
|
for (const [_, interceptor] of this.interceptors) {
|
|
|
|
if (interceptor.postHandle) {
|
|
|
|
try {
|
|
|
|
let startTime = Date.now()
|
|
|
|
ctx.result = interceptor.postHandle(ctx)
|
|
|
|
let preHandleTime = Date.now() - startTime
|
|
|
|
if (preHandleTime > 20) {
|
|
|
|
console.debug(`[WARN] Interceptor ${interceptor.name} preHandle cost time ${preHandleTime}ms!`)
|
|
|
|
}
|
2021-12-25 17:21:06 +00:00
|
|
|
} catch (error: any) {
|
2020-06-17 10:34:20 +00:00
|
|
|
return {
|
|
|
|
status: 500,
|
|
|
|
msg: `Interceptor ${interceptor.name} postHandle error: ${error}`,
|
|
|
|
path: ctx.url,
|
|
|
|
error: console.stack(error, false),
|
|
|
|
timestamp: Date.now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
console.debug(`
|
|
|
|
===================== MiaoSpring =====================
|
2020-06-20 08:39:03 +00:00
|
|
|
Request Method : ${ctx.request.getMethod()}
|
|
|
|
Request URL : ${ctx.url}
|
2020-06-30 08:02:39 +00:00
|
|
|
Request Body : ${JSON.stringify(ctx.body)}
|
2020-06-20 08:39:03 +00:00
|
|
|
Response Body : ${JSON.stringify(Java.asJSONCompatible(ctx.result))}
|
|
|
|
Handle Time : ${Date.now() - startTime}ms
|
2020-06-17 10:34:20 +00:00
|
|
|
======================================================`)
|
|
|
|
return ctx.result
|
|
|
|
}
|
|
|
|
|
|
|
|
private execRequestHandle(ctx: Context) {
|
2020-07-06 08:10:33 +00:00
|
|
|
if (!ctx.handler) return this.notFound(ctx)
|
2020-06-17 10:34:20 +00:00
|
|
|
try {
|
2020-06-30 08:02:39 +00:00
|
|
|
return ctx.handler(ctx)
|
2021-12-25 17:21:06 +00:00
|
|
|
} catch (error: any) {
|
2020-06-17 10:34:20 +00:00
|
|
|
return {
|
|
|
|
status: 500,
|
|
|
|
msg: '' + error,
|
|
|
|
path: ctx.url,
|
|
|
|
error: console.stack(error, false),
|
|
|
|
timestamp: Date.now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|