diff --git a/gringotts-frontend/components/constants.js b/gringotts-frontend/components/constants.js index 697087d..4945354 100644 --- a/gringotts-frontend/components/constants.js +++ b/gringotts-frontend/components/constants.js @@ -1,91 +1,91 @@ export const information = { - debug: false, - // baseUrl: '', - baseUrl: 'http://127.0.0.1:20080', - title: '可信供给中心', + debug: false, + // baseUrl: '', + baseUrl: 'http://127.0.0.1:20080', + title: '可信供给中心', } export function useAmis(amisObject) { - document.title = information.title - let amis = amisRequire('amis/embed') - let struct = amisObject(information) - if (information.debug) { - console.log(struct) + document.title = information.title + let amis = amisRequire('amis/embed') + let struct = amisObject(information) + if (information.debug) { + console.log(struct) + } + amis.embed( + '#app', + struct, + { + data: { + debug: information.debug, + base: information.baseUrl, + }, + }, + { + theme: 'antd', + enableAMISDebug: information.debug, } - amis.embed( - '#app', - struct, - { - data: { - debug: information.debug, - base: information.baseUrl, - }, - }, - { - theme: 'antd', - enableAMISDebug: information.debug, - } - ) + ) } export function crudCommonOptions() { - return { - affixHeader: false, - stopAutoRefreshWhenModalIsOpen: true, - resizable: false, - syncLocation: false, - silentPolling: true, - } + return { + affixHeader: false, + stopAutoRefreshWhenModalIsOpen: true, + resizable: false, + syncLocation: false, + silentPolling: true, + } } export function readOnlyDialogOptions() { - return { - actions: [], - showCloseButton: false, - closeOnEsc: true, - closeOnOutside: true, - disabled: true, - } + return { + actions: [], + showCloseButton: false, + closeOnEsc: true, + closeOnOutside: true, + disabled: true, + } } export function horizontalFormOptions() { - return { - mode: 'horizontal', - canAccessSuperData: false, - horizontal: { - left: 3, - }, - } + return { + mode: 'horizontal', + canAccessSuperData: false, + horizontal: { + left: 3, + }, + } } export function paginationCommonOptions(perPage = true, maxButtons = 5) { - let option = { - type: 'pagination', - layout: [ - 'pager' - ], - maxButtons: maxButtons, - showPageInput: false, - perPageAvailable: [10, 15, 20, 50, 100, 200], - } - if (perPage) { - option.layout.push('perPage') - } - return option + let option = { + type: 'pagination', + layout: [ + 'pager' + ], + maxButtons: maxButtons, + showPageInput: false, + perPageAvailable: [10, 15, 20, 50, 100, 200], + } + if (perPage) { + option.layout.push('perPage') + } + return option } export function paginationTemplate(perPage = 20, maxButtons = 5) { - return { - perPage: perPage, - headerToolbar: [ - "reload", - paginationCommonOptions(true, maxButtons), - ], - footerToolbar: [ - "statistics", - paginationCommonOptions(true, maxButtons), - ], - } + return { + perPage: perPage, + headerToolbar: [ + "reload", + paginationCommonOptions(true, maxButtons), + ], + footerToolbar: [ + "statistics", + paginationCommonOptions(true, maxButtons), + ], + } } export const size5MB = 5242880 @@ -94,16 +94,16 @@ export const size500MB = 524288000 export const size1GB = 1073741824 export function inputFileFormItemCommonOptions(accept = '*', maxSize = size5MB) { - return { - useChunk: true, - accept: accept, - maxSize: maxSize, - autoUpload: false, - drag: true, - startChunkApi: apiPost('${base}/upload/start'), - chunkApi: apiPost('${base}/upload/slice'), - finishChunkApi: apiPost('${base}/upload/finish'), - } + return { + useChunk: true, + accept: accept, + maxSize: maxSize, + autoUpload: false, + drag: true, + startChunkApi: apiPost('${base}/upload/start'), + chunkApi: apiPost('${base}/upload/slice'), + finishChunkApi: apiPost('${base}/upload/finish'), + } } /** @@ -114,41 +114,41 @@ export function inputFileFormItemCommonOptions(accept = '*', maxSize = size5MB) * @param {{}} extra */ export function copyField(field, label, tips = '复制', ignoreLength = 0, extra = undefined) { - let tpl = ignoreLength === 0 ? `\${${field}}` : `\${TRUNCATE(${field}, ${ignoreLength})}` - let content = extra - ? { - type: 'action', - level: 'link', - label: `\${${field}}`, - className: 'text-current underline', - size: 'xs', - ...extra, - } - : { - type: 'tpl', - className: 'mr-1', - tpl: tpl, - } - return { - name: field, - label: label, - type: 'wrapper', - size: 'none', - className: 'nowrap', - body: [ - content, - { - type: 'action', - level: 'link', - label: '', - icon: 'fa fa-copy', - size: 'xs', - actionType: 'copy', - content: `\$${field}`, - tooltip: `${tips}`, - }, - ] + let tpl = ignoreLength === 0 ? `\${${field}}` : `\${TRUNCATE(${field}, ${ignoreLength})}` + let content = extra + ? { + type: 'action', + level: 'link', + label: `\${${field}}`, + className: 'text-current underline', + size: 'xs', + ...extra, } + : { + type: 'tpl', + className: 'mr-1', + tpl: tpl, + } + return { + name: field, + label: label, + type: 'wrapper', + size: 'none', + className: 'nowrap', + body: [ + content, + { + type: 'action', + level: 'link', + label: '', + icon: 'fa fa-copy', + size: 'xs', + actionType: 'copy', + content: `\$${field}`, + tooltip: `${tips}`, + }, + ] + } } /** @@ -157,14 +157,14 @@ export function copyField(field, label, tips = '复制', ignoreLength = 0, extra * @param {Array} buttons */ export function operationField(label, width = 100, buttons = []) { - return { - label: label, - width: width, - type: 'operation', - fixed: 'right', - className: 'nowrap', - buttons: buttons, - } + return { + label: label, + width: width, + type: 'operation', + fixed: 'right', + className: 'nowrap', + buttons: buttons, + } } /** @@ -173,17 +173,17 @@ export function operationField(label, width = 100, buttons = []) { * @param {number} width */ export function timeField(field, label, width = 150) { - return { - label: label, - width: width, - align: 'center', - type: 'tpl', - tpl: `\${IF(${field}, DATETOSTR(${field}), '-')}` - } + return { + label: label, + width: width, + align: 'center', + type: 'tpl', + tpl: `\${IF(${field}, DATETOSTR(${field}), '-')}` + } } export function stringWrapField(field, label, width = undefined) { - return stringField(field, label, width, true) + return stringField(field, label, width, true) } /** @@ -193,17 +193,17 @@ export function stringWrapField(field, label, width = undefined) { * @param {boolean} wrap */ export function stringField(field, label, width = undefined, wrap = false) { - let data = { - name: field, - label: label, - } - if (width) { - data['width'] = width - } - if (!wrap) { - data['className'] = 'nowrap' - } - return data + let data = { + name: field, + label: label, + } + if (width) { + data['width'] = width + } + if (!wrap) { + data['className'] = 'nowrap' + } + return data } /** @@ -213,107 +213,107 @@ export function stringField(field, label, width = undefined, wrap = false) { * @param {number} width */ export function mappingField(field, label, mapping, width = 80) { - let mapData = { - '*': `\${${field}}`, - } - mapping.forEach(item => { - mapData[item['value']] = `${item['label']}` - }) - return { - label: label, - type: 'mapping', - width: width, - value: `\${${field}}`, - align: 'center', - map: mapData, - } + let mapData = { + '*': `\${${field}}`, + } + mapping.forEach(item => { + mapData[item['value']] = `${item['label']}` + }) + return { + label: label, + type: 'mapping', + width: width, + value: `\${${field}}`, + align: 'center', + map: mapData, + } } function mappingItem(label, value, color = 'bg-info') { - return { - label: label, - value: value, - color: color, - } + return { + label: label, + value: value, + color: color, + } } export const userRoleMapping = [ - mappingItem('数据提供方', 'PROVIDER', 'bg-blue-500'), - mappingItem('数据使用方', 'CUSTOMER', 'bg-purple-500'), - mappingItem('审核监管方', 'CHECKER', 'bg-cyan-500'), - mappingItem('系统管理员', 'ADMINISTRATOR', 'bg-green-500'), + mappingItem('数据提供方', 'PROVIDER', 'bg-blue-500'), + mappingItem('数据使用方', 'CUSTOMER', 'bg-purple-500'), + mappingItem('审核监管方', 'CHECKER', 'bg-cyan-500'), + mappingItem('系统管理员', 'ADMINISTRATOR', 'bg-green-500'), ] export const userStateMapping = [ - mappingItem('审查中', 'CHECKING', 'bg-warning'), - mappingItem('正常', 'NORMAL', 'bg-success'), - mappingItem('禁用', 'DISABLED', 'bg-danger'), + mappingItem('审查中', 'CHECKING', 'bg-warning'), + mappingItem('正常', 'NORMAL', 'bg-success'), + mappingItem('禁用', 'DISABLED', 'bg-danger'), ] export const permissionStateMapping = [ - mappingItem('未确权', 'NONE'), - mappingItem('草稿', 'DRAFT', 'bg-primary'), - mappingItem('审查中', 'CHECKING', 'bg-warning'), - mappingItem('用户审查中', 'OWNER_CHECKING', 'bg-warning'), - mappingItem('通过', 'NORMAL', 'bg-success'), - mappingItem('驳回', 'REJECT', 'bg-danger'), + mappingItem('未确权', 'NONE'), + mappingItem('草稿', 'DRAFT', 'bg-primary'), + mappingItem('审查中', 'CHECKING', 'bg-warning'), + mappingItem('用户审查中', 'OWNER_CHECKING', 'bg-warning'), + mappingItem('通过', 'NORMAL', 'bg-success'), + mappingItem('驳回', 'REJECT', 'bg-danger'), ] export const checkTypeMapping = [ - mappingItem('确权审查', 'CONFIRMATION', 'bg-blue-500'), - mappingItem('授权审查', 'AUTHENTICATION', 'bg-purple-500'), - mappingItem('上架审查', 'MARKET', 'bg-green-500'), + mappingItem('确权审查', 'CONFIRMATION', 'bg-blue-500'), + mappingItem('授权审查', 'AUTHENTICATION', 'bg-purple-500'), + mappingItem('上架审查', 'MARKET', 'bg-green-500'), ] export const checkOverMapping = [ - mappingItem('进行中', 'CHECKING', 'bg-warning'), - mappingItem('已撤销', 'RETRACT', 'bg-primary'), - mappingItem('已办结', 'OVER', 'bg-success'), + mappingItem('进行中', 'CHECKING', 'bg-warning'), + mappingItem('已撤销', 'RETRACT', 'bg-primary'), + mappingItem('已办结', 'OVER', 'bg-success'), ] function api(method, url) { - return { - method: method, - url: url, - headers: { - token: '${token|default:undefined}', - } + return { + method: method, + url: url, + headers: { + token: '${token|default:undefined}', } + } } export function apiGet(url) { - return api('get', url) + return api('get', url) } export function apiPost(url) { - return api('post', url) + return api('post', url) } export function arrayInCheck(array, field) { - return `\${ARRAYINCLUDES(['${array.join("','")}'], ${field})}` + return `\${ARRAYINCLUDES(['${array.join("','")}'], ${field})}` } export function arrayOutCheck(array, field) { - return `\${!ARRAYINCLUDES(['${array.join("','")}'], ${field})}` + return `\${!ARRAYINCLUDES(['${array.join("','")}'], ${field})}` } export const checkState = { - none: 'NONE', - draft: 'DRAFT', - checking: 'CHECKING', - ownerChecking: 'OWNER_CHECKING', - normal: 'NORMAL', + none: 'NONE', + draft: 'DRAFT', + checking: 'CHECKING', + ownerChecking: 'OWNER_CHECKING', + normal: 'NORMAL', } export function roleCheck(roles) { - return `\${ARRAYINCLUDES(['${roles.join("','")}'], role)}` + return `\${ARRAYINCLUDES(['${roles.join("','")}'], role)}` } export const role = { - administrator: 'ADMINISTRATOR', - checker: 'CHECKER', - provider: 'PROVIDER', - customer: 'CUSTOMER', + administrator: 'ADMINISTRATOR', + checker: 'CHECKER', + provider: 'PROVIDER', + customer: 'CUSTOMER', } export const administratorOnly = roleCheck([role.administrator]) @@ -324,98 +324,98 @@ export const customerOnly = roleCheck([role.administrator, role.customer]) export const formInputClearable = { - clearable: true, - clearValueOnEmpty: true, + clearable: true, + clearValueOnEmpty: true, } const formInputFileStaticColumns = [ - { - name: 'filename', - label: '文件名', - }, - { - type: 'operation', - label: '操作', - width: 140, - buttons: [ - { - type: 'action', - label: '预览', - level: 'link', - icon: 'fas fa-eye' - }, - { - type: 'action', - label: '下载', - level: 'link', - icon: 'fa fa-download', - actionType: 'ajax', - api: { - ...apiGet('${base}/upload/download/${id}'), - responseType: 'blob', - } - } - ] - } + { + name: 'filename', + label: '文件名', + }, + { + type: 'operation', + label: '操作', + width: 140, + buttons: [ + { + type: 'action', + label: '预览', + level: 'link', + icon: 'fas fa-eye' + }, + { + type: 'action', + label: '下载', + level: 'link', + icon: 'fa fa-download', + actionType: 'ajax', + api: { + ...apiGet('${base}/upload/download/${id}'), + responseType: 'blob', + } + } + ] + } ] export function formInputSingleFileStatic(field, label) { - return { - visibleOn: '${detail}', - type: 'control', - label: label, - required: true, - body: { - type: 'table', - source: `\${${field}|asArray}`, - columns: formInputFileStaticColumns, - } + return { + visibleOn: '${detail}', + type: 'control', + label: label, + required: true, + body: { + type: 'table', + source: `\${${field}|asArray}`, + columns: formInputFileStaticColumns, } + } } export function formInputMultiFileStatic(field, label) { - return { - visibleOn: '${detail}', - type: 'input-table', - label: label, - name: field, - required: true, - resizable: false, - columns: formInputFileStaticColumns, - } + return { + visibleOn: '${detail}', + type: 'input-table', + label: label, + name: field, + required: true, + resizable: false, + columns: formInputFileStaticColumns, + } } export function formCreatedUserAndModifiedUser() { - return [ + return [ + { + type: 'group', + body: [ { - type: 'group', - body: [ - { - type: 'input-text', - name: 'createdUsername', - label: '创建人', - }, - { - type: 'input-datetime', - name: 'createdTime', - label: '创建时间', - }, - ] + type: 'input-text', + name: 'createdUsername', + label: '创建人', }, { - type: 'group', - body: [ - { - type: 'input-text', - name: 'modifiedUsername', - label: '最后修改人', - }, - { - type: 'input-datetime', - name: 'modifiedTime', - label: '最后修改时间', - }, - ] + type: 'input-datetime', + name: 'createdTime', + label: '创建时间', }, - ] + ] + }, + { + type: 'group', + body: [ + { + type: 'input-text', + name: 'modifiedUsername', + label: '最后修改人', + }, + { + type: 'input-datetime', + name: 'modifiedTime', + label: '最后修改时间', + }, + ] + }, + ] } diff --git a/gringotts-frontend/components/permission/dialog-permission.js b/gringotts-frontend/components/permission/dialog-permission.js index 7d845ce..0e69d35 100644 --- a/gringotts-frontend/components/permission/dialog-permission.js +++ b/gringotts-frontend/components/permission/dialog-permission.js @@ -1,14 +1,14 @@ import './dialog-permission.css' import { - apiGet, - apiPost, - formCreatedUserAndModifiedUser, - formInputClearable, - formInputMultiFileStatic, - horizontalFormOptions, - information, - inputFileFormItemCommonOptions, - size100MB + apiGet, + apiPost, + formCreatedUserAndModifiedUser, + formInputClearable, + formInputMultiFileStatic, + horizontalFormOptions, + information, + inputFileFormItemCommonOptions, + size100MB } from "../constants.js"; import {resourceList} from "../../pages/index/tab-data.js"; import {resourceDetailDialog} from "../resource/dialog-resource.js"; @@ -17,192 +17,192 @@ const CONFIRMATION_TYPE = 'confirmation' const AUTHENTICATION_TYPE = 'authentication' const CONFIRMATION = { - type: 'confirmation', - pickerApi: apiGet('${base}/data_resource/list_no_confirmation') + type: 'confirmation', + pickerApi: apiGet('${base}/data_resource/list_no_confirmation') } const AUTHENTICATION = { - type: 'authentication', - pickerApi: apiGet('${base}/data_resource/list_no_authentication') + type: 'authentication', + pickerApi: apiGet('${base}/data_resource/list_no_authentication') } function detailForm(pickerApi = apiGet('${base}/data_resource/list'), showCreatedUserAndModifiedUser = false) { - return { - debug: information.debug, - id: 'permission_form', - type: 'form', - ...horizontalFormOptions(), - horizontal: { - left: 2, + return { + debug: information.debug, + id: 'permission_form', + type: 'form', + ...horizontalFormOptions(), + horizontal: { + left: 2, + }, + body: [ + { + type: 'hidden', + name: 'id', + }, + { + type: 'picker', + name: 'targetId', + label: '数据资源', + required: true, + multiple: false, + size: 'md', + valueField: 'id', + labelField: 'name', + source: pickerApi, + pickerSchema: { + ...resourceList(), }, - body: [ - { - type: 'hidden', - name: 'id', - }, - { - type: 'picker', - name: 'targetId', - label: '数据资源', - required: true, - multiple: false, - size: 'md', - valueField: 'id', - labelField: 'name', - source: pickerApi, - pickerSchema: { - ...resourceList(), - }, - staticSchema: { - type: 'tpl', - tpl: "${targetName}", - onEvent: { - click: { - actions: [ - { - actionType: 'dialog', - ...resourceDetailDialog('targetId'), - } - ] - } - } + staticSchema: { + type: 'tpl', + tpl: "${targetName}", + onEvent: { + click: { + actions: [ + { + actionType: 'dialog', + ...resourceDetailDialog('targetId'), } - }, - { - type: 'textarea', - placeholder: '请输入确权说明', - label: '确权说明', - name: 'description', - ...formInputClearable, - }, - formInputMultiFileStatic('evidenceFiles', '相关材料'), - { - visibleOn: '${!detail}', - type: 'input-file', - label: '相关材料', - name: 'evidenceFiles', - multiple: true, - required: true, - joinValues: false, - ...inputFileFormItemCommonOptions(undefined, size100MB), - }, - { - visibleOn: `\${${AUTHENTICATION_TYPE}}`, - type: 'input-datetime-range', - name: 'activeTime', - extraName: 'expiredTime', - label: '授权时间', - required: true, - format: 'YYYY-MM-DD HH:mm:ss', - shortcuts: [ - '7dayslater', - '14dayslater', - '30dayslater', - '180dayslater', - '365dayslater', - ] - }, - ...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : []) + ] + } + } + } + }, + { + type: 'textarea', + placeholder: '请输入确权说明', + label: '确权说明', + name: 'description', + ...formInputClearable, + }, + formInputMultiFileStatic('evidenceFiles', '相关材料'), + { + visibleOn: '${!detail}', + type: 'input-file', + label: '相关材料', + name: 'evidenceFiles', + multiple: true, + required: true, + joinValues: false, + ...inputFileFormItemCommonOptions(undefined, size100MB), + }, + { + visibleOn: `\${${AUTHENTICATION_TYPE}}`, + type: 'input-datetime-range', + name: 'activeTime', + extraName: 'expiredTime', + label: '授权时间', + required: true, + format: 'YYYY-MM-DD HH:mm:ss', + shortcuts: [ + '7dayslater', + '14dayslater', + '30dayslater', + '180dayslater', + '365dayslater', ] - } + }, + ...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : []) + ] + } } export function confirmationAddDialog() { - return permissionAddDialog(CONFIRMATION) + return permissionAddDialog(CONFIRMATION) } export function authenticationAddDialog() { - return permissionAddDialog(AUTHENTICATION) + return permissionAddDialog(AUTHENTICATION) } function permissionAddDialog(config) { - let data = {add: true} - data[config.type] = true - return { - actionType: 'dialog', - dialog: { - title: '新增确权申请', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(config.pickerApi), - api: apiPost(`\${base}/${config.type}/save`), - data: data, - } + let data = {add: true} + data[config.type] = true + return { + actionType: 'dialog', + dialog: { + title: '新增确权申请', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(config.pickerApi), + api: apiPost(`\${base}/${config.type}/save`), + data: data, + } } + } } export function confirmationDetailDialog(field = 'id', actions = []) { - return permissionDetailDialog(CONFIRMATION, field, actions) + return permissionDetailDialog(CONFIRMATION, field, actions) } export function authenticationDetailDialog(field = 'id', actions = []) { - return permissionDetailDialog(AUTHENTICATION, field, actions) + return permissionDetailDialog(AUTHENTICATION, field, actions) } function permissionDetailDialog(config, field = 'id', actions = []) { - let data = {detail: true} - data[config.type] = true - return { - actionType: 'dialog', - dialog: { - title: '确权申请详情', - size: 'md', - actions: actions, - body: { - ...detailForm(config.pickerApi, true), - initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`), - static: true, - data: data, - } - } + let data = {detail: true} + data[config.type] = true + return { + actionType: 'dialog', + dialog: { + title: '确权申请详情', + size: 'md', + actions: actions, + body: { + ...detailForm(config.pickerApi, true), + initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`), + static: true, + data: data, + } } + } } export function confirmationEditeDialog(field = 'id') { - return permissionEditeDialog(CONFIRMATION, field) + return permissionEditeDialog(CONFIRMATION, field) } export function authenticationEditeDialog(field = 'id') { - return permissionEditeDialog(AUTHENTICATION, field) + return permissionEditeDialog(AUTHENTICATION, field) } function permissionEditeDialog(config, field = 'id') { - let data = {edit: true} - data[config.type] = true - return { - actionType: 'dialog', - dialog: { - title: '确权申请详情', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(config.pickerApi), - api: apiPost(`\${base}/${config.type}/save`), - initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`), - data: data, - }, + let data = {edit: true} + data[config.type] = true + return { + actionType: 'dialog', + dialog: { + title: '确权申请详情', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(config.pickerApi), + api: apiPost(`\${base}/${config.type}/save`), + initApi: apiGet(`\${base}/${config.type}/detail/\${${field}}`), + data: data, + }, } + } } diff --git a/gringotts-frontend/components/resource/dialog-resource.js b/gringotts-frontend/components/resource/dialog-resource.js index 78af8cc..178dbbb 100644 --- a/gringotts-frontend/components/resource/dialog-resource.js +++ b/gringotts-frontend/components/resource/dialog-resource.js @@ -1,378 +1,378 @@ import './dialog-resource.css' import { - apiGet, - apiPost, - formCreatedUserAndModifiedUser, - formInputClearable, - formInputSingleFileStatic, - horizontalFormOptions, - inputFileFormItemCommonOptions, - size1GB, - size500MB + apiGet, + apiPost, + formCreatedUserAndModifiedUser, + formInputClearable, + formInputSingleFileStatic, + horizontalFormOptions, + inputFileFormItemCommonOptions, + size1GB, + size500MB } from "../constants.js"; function detailForm(showCreatedUserAndModifiedUser = false) { - return { - type: 'form', - ...horizontalFormOptions(), - horizontal: { - left: 2, - }, + return { + type: 'form', + ...horizontalFormOptions(), + horizontal: { + left: 2, + }, + body: [ + { + type: 'hidden', + name: 'id', + }, + { + type: 'input-text', + name: 'name', + label: '资源名称', + maxLength: 10, + showCounter: true, + required: true, + ...formInputClearable, + }, + { + type: 'textarea', + name: 'description', + label: '资源描述', + ...formInputClearable, + showCounter: true, + trimContents: true, + minRows: 2, + maxRows: 2, + }, + { + type: 'fieldSet', + title: '资源类型定义', body: [ - { - type: 'hidden', - name: 'id', - }, - { + { + name: 'resourceType', + type: 'select', + label: '资源类型', + selectFirst: true, + required: true, + options: [ + {label: 'API', value: 'API'}, + {label: '文件', value: 'FILE'}, + {label: '数据库', value: 'DATABASE'}, + {label: 'HDFS', value: 'HDFS'}, + {label: 'FTP', value: 'FTP'}, + ] + }, + { + visibleOn: "${resourceType === 'API'}", + type: 'fieldSet', + body: [ + { type: 'input-text', - name: 'name', - label: '资源名称', - maxLength: 10, - showCounter: true, + label: 'API地址', + name: 'apiUrl', required: true, ...formInputClearable, - }, - { - type: 'textarea', - name: 'description', - label: '资源描述', + }, + { + type: 'input-text', + label: '用户名', + name: 'apiUsername', ...formInputClearable, - showCounter: true, - trimContents: true, - minRows: 2, - maxRows: 2, - }, - { - type: 'fieldSet', - title: '资源类型定义', - body: [ - { - name: 'resourceType', - type: 'select', - label: '资源类型', - selectFirst: true, - required: true, - options: [ - {label: 'API', value: 'API'}, - {label: '文件', value: 'FILE'}, - {label: '数据库', value: 'DATABASE'}, - {label: 'HDFS', value: 'HDFS'}, - {label: 'FTP', value: 'FTP'}, - ] - }, - { - visibleOn: "${resourceType === 'API'}", - type: 'fieldSet', - body: [ - { - type: 'input-text', - label: 'API地址', - name: 'apiUrl', - required: true, - ...formInputClearable, - }, - { - type: 'input-text', - label: '用户名', - name: 'apiUsername', - ...formInputClearable, - }, - { - type: 'input-password', - label: '密码', - name: 'apiPassword', - ...formInputClearable, - }, - ] - }, - { - visibleOn: "${resourceType === 'FILE'}", - type: 'fieldSet', - body: [ - formInputSingleFileStatic('file', '数据文件'), - { - visibleOn: "${!detail}", - type: 'input-file', - label: '数据文件', - description: '只适合小于1GB的资源文件使用,大文件请使用其他资源类型', - name: 'file', - multiple: false, - required: true, - joinValues: false, - ...inputFileFormItemCommonOptions('.zip', size1GB), - }, - ] - }, - { - visibleOn: "${resourceType === 'DATABASE'}", - type: 'fieldSet', - body: [ - { - type: 'select', - label: '数据库类型', - name: 'databaseType', - required: true, - options: [ - {label: 'MySQL', value: 'MYSQL'}, - {label: 'Oracle', value: 'ORACLE'}, - {label: 'PostgreSQL', value: 'POSTGRESQL'}, - ] - }, - { - type: 'input-text', - label: 'JDBC', - name: 'databaseJdbc', - required: true, - ...formInputClearable, - }, - { - type: 'input-text', - label: '用户名', - name: 'databaseUsername', - ...formInputClearable, - }, - { - type: 'input-password', - label: '密码', - name: 'databasePassword', - ...formInputClearable, - }, - ] - }, - { - visibleOn: "${resourceType === 'HDFS'}", - type: 'fieldSet', - body: [ - formInputSingleFileStatic('coreSiteFile', 'core-site.xml'), - { - visibleOn: "${!detail}", - type: 'input-file', - label: 'core-site.xml', - name: 'coreSiteFile', - multiple: false, - required: true, - joinValues: false, - ...inputFileFormItemCommonOptions('.xml'), - }, - formInputSingleFileStatic('hdfsSiteFile', 'hdfs-site.xml'), - { - visibleOn: "${!detail}", - type: 'input-file', - label: 'hdfs-site.xml', - name: 'hdfsSiteFile', - multiple: false, - required: true, - joinValues: false, - ...inputFileFormItemCommonOptions('.xml'), - }, - ] - }, - { - visibleOn: "${resourceType === 'FTP'}", - type: 'fieldSet', - body: [ - { - type: 'input-text', - label: 'FTP地址', - name: 'ftpUrl', - required: true, - ...formInputClearable, - }, - { - type: 'input-text', - label: 'FTP账号', - name: 'ftpUsername', - ...formInputClearable, - }, - { - type: 'input-password', - label: 'FTP密码', - name: 'ftpPassword', - ...formInputClearable, - }, - { - type: 'input-text', - label: '相对路径', - name: 'ftpPath', - description: '若为空,则使用用户根目录', - ...formInputClearable, - }, - { - type: 'input-text', - label: '文件筛选', - name: 'ftpRegexFilter', - description: '正则表达式,用于匹配文件的路径,只有符合筛选条件的文件才会被采集;若为空则默认采集全部文件', - ...formInputClearable, - }, - ] - }, + }, + { + type: 'input-password', + label: '密码', + name: 'apiPassword', + ...formInputClearable, + }, + ] + }, + { + visibleOn: "${resourceType === 'FILE'}", + type: 'fieldSet', + body: [ + formInputSingleFileStatic('file', '数据文件'), + { + visibleOn: "${!detail}", + type: 'input-file', + label: '数据文件', + description: '只适合小于1GB的资源文件使用,大文件请使用其他资源类型', + name: 'file', + multiple: false, + required: true, + joinValues: false, + ...inputFileFormItemCommonOptions('.zip', size1GB), + }, + ] + }, + { + visibleOn: "${resourceType === 'DATABASE'}", + type: 'fieldSet', + body: [ + { + type: 'select', + label: '数据库类型', + name: 'databaseType', + required: true, + options: [ + {label: 'MySQL', value: 'MYSQL'}, + {label: 'Oracle', value: 'ORACLE'}, + {label: 'PostgreSQL', value: 'POSTGRESQL'}, ] - }, - { - type: 'fieldSet', - title: '资源格式定义', - className: 'mt-5', - body: [ - { - name: 'formatType', - type: 'select', - label: '资源格式', - selectFirst: true, - required: true, - options: [ - {label: '无', value: 'NONE'}, - {label: 'Line', value: 'LINE'}, - {label: 'JSON', value: 'JSON'}, - {label: 'JSON Line', value: 'JSON_LINE'}, - {label: 'CSV', value: 'CSV'}, - ] - }, - { - visibleOn: "${formatType === 'JSON' && !detail}", - type: 'json-schema-editor', - name: 'jsonSchema', - label: 'JSON格式', - description: '(使用JSON Schema格式)', - required: true, - enableAdvancedSetting: true, - mini: true, - }, - { - visibleOn: "${formatType === 'JSON' && detail}", - type: 'editor', - name: 'jsonSchemaText', - label: 'JSON格式', - language: 'json', - }, - { - visibleOn: "${formatType === 'JSON_LINE' && !detail}", - type: 'json-schema-editor', - name: 'jsonLineSchema', - label: 'JSON格式', - description: 'JSON Line类型请定义单行JSON数据格式(使用JSON Schema格式)', - required: true, - enableAdvancedSetting: true, - mini: true, - }, - { - visibleOn: "${formatType === 'JSON_LINE' && detail}", - type: 'editor', - name: 'jsonLineSchemaText', - label: 'JSON格式', - language: 'json', - }, - { - visibleOn: "${formatType === 'CSV' && !detail}", - type: 'json-schema-editor', - name: 'csvSchema', - label: 'CSV格式', - description: '请定义单行数据中各个字段的格式(使用JSON Schema格式)', - required: true, - enableAdvancedSetting: true, - mini: true, - disabledTypes: [ - 'object', - 'array', - 'null', - ] - }, - { - visibleOn: "${formatType === 'CSV' && detail}", - type: 'editor', - name: 'csvSchemaText', - label: 'JSON格式', - language: 'json', - }, - formInputSingleFileStatic('exampleFile', '资源示例'), - { - visibleOn: "${!detail}", - type: 'input-file', - label: '资源示例', - name: 'exampleFile', - description: '可以上传用于作为格式示范的样例数据', - multiple: false, - joinValues: false, - ...inputFileFormItemCommonOptions(undefined, size500MB), - }, - ] - }, - ...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : []) + }, + { + type: 'input-text', + label: 'JDBC', + name: 'databaseJdbc', + required: true, + ...formInputClearable, + }, + { + type: 'input-text', + label: '用户名', + name: 'databaseUsername', + ...formInputClearable, + }, + { + type: 'input-password', + label: '密码', + name: 'databasePassword', + ...formInputClearable, + }, + ] + }, + { + visibleOn: "${resourceType === 'HDFS'}", + type: 'fieldSet', + body: [ + formInputSingleFileStatic('coreSiteFile', 'core-site.xml'), + { + visibleOn: "${!detail}", + type: 'input-file', + label: 'core-site.xml', + name: 'coreSiteFile', + multiple: false, + required: true, + joinValues: false, + ...inputFileFormItemCommonOptions('.xml'), + }, + formInputSingleFileStatic('hdfsSiteFile', 'hdfs-site.xml'), + { + visibleOn: "${!detail}", + type: 'input-file', + label: 'hdfs-site.xml', + name: 'hdfsSiteFile', + multiple: false, + required: true, + joinValues: false, + ...inputFileFormItemCommonOptions('.xml'), + }, + ] + }, + { + visibleOn: "${resourceType === 'FTP'}", + type: 'fieldSet', + body: [ + { + type: 'input-text', + label: 'FTP地址', + name: 'ftpUrl', + required: true, + ...formInputClearable, + }, + { + type: 'input-text', + label: 'FTP账号', + name: 'ftpUsername', + ...formInputClearable, + }, + { + type: 'input-password', + label: 'FTP密码', + name: 'ftpPassword', + ...formInputClearable, + }, + { + type: 'input-text', + label: '相对路径', + name: 'ftpPath', + description: '若为空,则使用用户根目录', + ...formInputClearable, + }, + { + type: 'input-text', + label: '文件筛选', + name: 'ftpRegexFilter', + description: '正则表达式,用于匹配文件的路径,只有符合筛选条件的文件才会被采集;若为空则默认采集全部文件', + ...formInputClearable, + }, + ] + }, ] - } + }, + { + type: 'fieldSet', + title: '资源格式定义', + className: 'mt-5', + body: [ + { + name: 'formatType', + type: 'select', + label: '资源格式', + selectFirst: true, + required: true, + options: [ + {label: '无', value: 'NONE'}, + {label: 'Line', value: 'LINE'}, + {label: 'JSON', value: 'JSON'}, + {label: 'JSON Line', value: 'JSON_LINE'}, + {label: 'CSV', value: 'CSV'}, + ] + }, + { + visibleOn: "${formatType === 'JSON' && !detail}", + type: 'json-schema-editor', + name: 'jsonSchema', + label: 'JSON格式', + description: '(使用JSON Schema格式)', + required: true, + enableAdvancedSetting: true, + mini: true, + }, + { + visibleOn: "${formatType === 'JSON' && detail}", + type: 'editor', + name: 'jsonSchemaText', + label: 'JSON格式', + language: 'json', + }, + { + visibleOn: "${formatType === 'JSON_LINE' && !detail}", + type: 'json-schema-editor', + name: 'jsonLineSchema', + label: 'JSON格式', + description: 'JSON Line类型请定义单行JSON数据格式(使用JSON Schema格式)', + required: true, + enableAdvancedSetting: true, + mini: true, + }, + { + visibleOn: "${formatType === 'JSON_LINE' && detail}", + type: 'editor', + name: 'jsonLineSchemaText', + label: 'JSON格式', + language: 'json', + }, + { + visibleOn: "${formatType === 'CSV' && !detail}", + type: 'json-schema-editor', + name: 'csvSchema', + label: 'CSV格式', + description: '请定义单行数据中各个字段的格式(使用JSON Schema格式)', + required: true, + enableAdvancedSetting: true, + mini: true, + disabledTypes: [ + 'object', + 'array', + 'null', + ] + }, + { + visibleOn: "${formatType === 'CSV' && detail}", + type: 'editor', + name: 'csvSchemaText', + label: 'JSON格式', + language: 'json', + }, + formInputSingleFileStatic('exampleFile', '资源示例'), + { + visibleOn: "${!detail}", + type: 'input-file', + label: '资源示例', + name: 'exampleFile', + description: '可以上传用于作为格式示范的样例数据', + multiple: false, + joinValues: false, + ...inputFileFormItemCommonOptions(undefined, size500MB), + }, + ] + }, + ...(showCreatedUserAndModifiedUser ? formCreatedUserAndModifiedUser() : []) + ] + } } export function resourceAddDialog() { - return { - actionType: 'dialog', - dialog: { - title: '新增数据资源', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(), - api: apiPost('${base}/data_resource/save'), - data: { - add: true, - } - } + return { + actionType: 'dialog', + dialog: { + title: '新增数据资源', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(), + api: apiPost('${base}/data_resource/save'), + data: { + add: true, + } + } } + } } export function resourceDetailDialog(field = 'id') { - return { - actionType: 'dialog', - dialog: { - title: '账号详情', - actions: [], - size: 'md', - body: { - ...detailForm(true), - static: true, - initApi: apiGet(`\${base}/data_resource/detail/\${${field}}`), - data: { - detail: true, - } - }, + return { + actionType: 'dialog', + dialog: { + title: '账号详情', + actions: [], + size: 'md', + body: { + ...detailForm(true), + static: true, + initApi: apiGet(`\${base}/data_resource/detail/\${${field}}`), + data: { + detail: true, } + }, } + } } export function resourceEditeDialog() { - return { - actionType: 'dialog', - dialog: { - title: '账号详情', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(), - api: apiPost('${base}/data_resource/save'), - initApi: apiGet('${base}/data_resource/detail/${id}'), - data: { - edit: true, - } - }, + return { + actionType: 'dialog', + dialog: { + title: '账号详情', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(), + api: apiPost('${base}/data_resource/save'), + initApi: apiGet('${base}/data_resource/detail/${id}'), + data: { + edit: true, + } + }, } + } } \ No newline at end of file diff --git a/gringotts-frontend/components/user/dialog-user-change-password.js b/gringotts-frontend/components/user/dialog-user-change-password.js index f036c05..0c3ce5f 100644 --- a/gringotts-frontend/components/user/dialog-user-change-password.js +++ b/gringotts-frontend/components/user/dialog-user-change-password.js @@ -1,38 +1,38 @@ -import {horizontalFormOptions, apiPost} from '../constants.js' +import {apiPost, horizontalFormOptions} from '../constants.js' import {confirmPasswordFormItem, passwordFormItem} from "./dialog-user-item.js"; export function userChangePasswordDialog() { - return { - actionType: 'dialog', - dialog: { - title: '修改密码', - actions: [ - { - type: 'reset', - label: '清空', - }, - { - type: 'submit', - label: '修改', - level: 'primary', - } - ], - body: { - type: 'form', - api: apiPost('${base}/user_management/change_password'), - ...horizontalFormOptions(), - body: [ - { - type: 'input-password', - name: 'oldPassword', - label: '旧密码', - placeholder: '请输入旧密码', - required: true, - }, - passwordFormItem('newPassword', '新密码'), - confirmPasswordFormItem('confirmNewPassword', 'newPassword', '新密码'), - ] - } + return { + actionType: 'dialog', + dialog: { + title: '修改密码', + actions: [ + { + type: 'reset', + label: '清空', + }, + { + type: 'submit', + label: '修改', + level: 'primary', } + ], + body: { + type: 'form', + api: apiPost('${base}/user_management/change_password'), + ...horizontalFormOptions(), + body: [ + { + type: 'input-password', + name: 'oldPassword', + label: '旧密码', + placeholder: '请输入旧密码', + required: true, + }, + passwordFormItem('newPassword', '新密码'), + confirmPasswordFormItem('confirmNewPassword', 'newPassword', '新密码'), + ] + } } + } } \ No newline at end of file diff --git a/gringotts-frontend/components/user/dialog-user-check.js b/gringotts-frontend/components/user/dialog-user-check.js index 071c706..b847817 100644 --- a/gringotts-frontend/components/user/dialog-user-check.js +++ b/gringotts-frontend/components/user/dialog-user-check.js @@ -1,106 +1,106 @@ import { - apiGet, - formCreatedUserAndModifiedUser, - horizontalFormOptions, - mappingField, - userRoleMapping, - userStateMapping + apiGet, + formCreatedUserAndModifiedUser, + horizontalFormOptions, + mappingField, + userRoleMapping, + userStateMapping } from "../constants.js"; const dialogBody = [ - { - type: 'input-email', - name: 'username', - label: '邮箱', - }, - { - type: 'group', - body: [ - { - type: 'control', - label: '角色', - body: mappingField('role', '角色', userRoleMapping, 120), - }, - { - type: 'control', - label: '账号状态', - body: mappingField('state', '账号状态', userStateMapping), - } - ] - }, - ...formCreatedUserAndModifiedUser(), - { - type: 'group', - body: [ - { - type: 'input-text', - name: 'checkedUsername', - label: '审核人', - }, - { - type: 'input-datetime', - name: 'checkedTime', - label: '审核时间', - }, - ] - }, + { + type: 'input-email', + name: 'username', + label: '邮箱', + }, + { + type: 'group', + body: [ + { + type: 'control', + label: '角色', + body: mappingField('role', '角色', userRoleMapping, 120), + }, + { + type: 'control', + label: '账号状态', + body: mappingField('state', '账号状态', userStateMapping), + } + ] + }, + ...formCreatedUserAndModifiedUser(), + { + type: 'group', + body: [ + { + type: 'input-text', + name: 'checkedUsername', + label: '审核人', + }, + { + type: 'input-datetime', + name: 'checkedTime', + label: '审核时间', + }, + ] + }, ] export function userDetailDialog() { - return { - actionType: 'dialog', - dialog: { - title: '账号详情', - actions: [], - size: 'md', - body: { - type: 'form', - initApi: apiGet('${base}/user_management/detail/${username}'), - ...horizontalFormOptions(), - horizontal: { - left: 2, - }, - static: true, - body: [ - ...dialogBody, - { - type: 'input-datetime', - name: 'lastLoginTime', - label: '上次登陆时间', - }, - ], - } - } + return { + actionType: 'dialog', + dialog: { + title: '账号详情', + actions: [], + size: 'md', + body: { + type: 'form', + initApi: apiGet('${base}/user_management/detail/${username}'), + ...horizontalFormOptions(), + horizontal: { + left: 2, + }, + static: true, + body: [ + ...dialogBody, + { + type: 'input-datetime', + name: 'lastLoginTime', + label: '上次登陆时间', + }, + ], + } } + } } export function userCheckDialog() { - return { - actionType: 'dialog', - dialog: { - title: '账号审核', - actions: [ - { - type: 'action', - label: '同意', - level: 'primary', - actionType: 'submit', - confirmTitle: '审核通过', - confirmText: '确认通过账号为${username}通过审核吗?审核通过后将无法撤销。', - }, - ], - size: 'md', - body: { - type: 'form', - api: apiGet('${base}/user_management/check/${username}'), - initApi: apiGet('${base}/user_management/detail/${username}'), - ...horizontalFormOptions(), - horizontal: { - left: 2, - }, - static: true, - body: dialogBody, - } - } + return { + actionType: 'dialog', + dialog: { + title: '账号审核', + actions: [ + { + type: 'action', + label: '同意', + level: 'primary', + actionType: 'submit', + confirmTitle: '审核通过', + confirmText: '确认通过账号为${username}通过审核吗?审核通过后将无法撤销。', + }, + ], + size: 'md', + body: { + type: 'form', + api: apiGet('${base}/user_management/check/${username}'), + initApi: apiGet('${base}/user_management/detail/${username}'), + ...horizontalFormOptions(), + horizontal: { + left: 2, + }, + static: true, + body: dialogBody, + } } + } } \ No newline at end of file diff --git a/gringotts-frontend/components/user/dialog-user-item.js b/gringotts-frontend/components/user/dialog-user-item.js index b8827e9..671d0c4 100644 --- a/gringotts-frontend/components/user/dialog-user-item.js +++ b/gringotts-frontend/components/user/dialog-user-item.js @@ -1,49 +1,49 @@ export function emailFormItem(name) { - return { - type: 'input-email', - name: name, - label: '邮箱', - placeholder: '请输入邮箱', - required: true, - clearable: true, - clearValueOnEmpty: true, - validateApi: '${base}/user/exists_username/${username}', - } + return { + type: 'input-email', + name: name, + label: '邮箱', + placeholder: '请输入邮箱', + required: true, + clearable: true, + clearValueOnEmpty: true, + validateApi: '${base}/user/exists_username/${username}', + } } export function passwordFormItem(name, label = '密码') { - return { - type: 'input-password', - name: name, - label: label, - placeholder: `请输入${label}`, - required: true, - clearable: true, - clearValueOnEmpty: true, - validations: { - matchRegexp: - /^(?=.*\d)(?!.*(\d)\1{2})(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210))(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,16}$/, - }, - validationErrors: { - matchRegexp: - `${label}至少包含字母、数字、特殊字符,8-16位,并且不能连续出现3个大小连续或相同的数字`, - }, - } + return { + type: 'input-password', + name: name, + label: label, + placeholder: `请输入${label}`, + required: true, + clearable: true, + clearValueOnEmpty: true, + validations: { + matchRegexp: + /^(?=.*\d)(?!.*(\d)\1{2})(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210))(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,16}$/, + }, + validationErrors: { + matchRegexp: + `${label}至少包含字母、数字、特殊字符,8-16位,并且不能连续出现3个大小连续或相同的数字`, + }, + } } export function confirmPasswordFormItem(name, target, label = '密码') { - return { - type: 'input-password', - name: name, - label: `确认${label}`, - placeholder: `请再次输入${label}`, - required: true, - clearable: true, - validations: { - equalsField: target, - }, - validationErrors: { - equalsField: `两次输入${label}不一致`, - }, - } + return { + type: 'input-password', + name: name, + label: `确认${label}`, + placeholder: `请再次输入${label}`, + required: true, + clearable: true, + validations: { + equalsField: target, + }, + validationErrors: { + equalsField: `两次输入${label}不一致`, + }, + } } \ No newline at end of file diff --git a/gringotts-frontend/components/user/dialog-user-register.js b/gringotts-frontend/components/user/dialog-user-register.js index df3a445..657f1a2 100644 --- a/gringotts-frontend/components/user/dialog-user-register.js +++ b/gringotts-frontend/components/user/dialog-user-register.js @@ -32,9 +32,9 @@ export function userRegisterDialog() { required: true, selectFirst: true, options: [ - { label: '数据提供方', value: 'PROVIDER' }, - { label: '数据使用方', value: 'CUSTOMER' }, - { label: '审查监管方', value: 'CHECKER' }, + {label: '数据提供方', value: 'PROVIDER'}, + {label: '数据使用方', value: 'CUSTOMER'}, + {label: '审查监管方', value: 'CHECKER'}, ], }, ], @@ -76,9 +76,9 @@ export function userAdministratorRegisterDialog() { inline: false, columnsCount: 2, options: [ - { label: '数据提供方', value: 'PROVIDER' }, - { label: '数据使用方', value: 'CUSTOMER' }, - { label: '审查监管方', value: 'CHECKER' }, + {label: '数据提供方', value: 'PROVIDER'}, + {label: '数据使用方', value: 'CUSTOMER'}, + {label: '审查监管方', value: 'CHECKER'}, ], }, ], diff --git a/gringotts-frontend/components/ware/dialog-ware.js b/gringotts-frontend/components/ware/dialog-ware.js index 35c608a..fa98752 100644 --- a/gringotts-frontend/components/ware/dialog-ware.js +++ b/gringotts-frontend/components/ware/dialog-ware.js @@ -4,188 +4,188 @@ import {resourceList} from '../../pages/index/tab-data.js' import {resourceDetailDialog} from '../resource/dialog-resource.js' function detailForm() { - return { - id: 'ware-form', - debug: information.debug, - type: 'form', - ...horizontalFormOptions(), - horizontal: { - left: 2, + return { + id: 'ware-form', + debug: information.debug, + type: 'form', + ...horizontalFormOptions(), + horizontal: { + left: 2, + }, + body: [ + { + type: 'hidden', + name: 'id', + }, + { + visibleOn: '${!detail}', + type: 'input-image', + name: 'icon', + label: '图标', + required: true, + receiver: apiPost("${base}/upload"), + onEvent: { + success: { + actions: [ + { + actionType: 'setValue', + componentId: 'ware-form', + args: { + value: { + iconId: '${event.data.result.id}' + } + } + } + ] + } + } + }, + { + visibleOn: '${detail}', + type: 'control', + name: 'icon', + label: '图标', + required: true, + body: { + type: 'image', + src: '${icon}', + innerClassName: 'no-border', + } + }, + { + type: 'picker', + name: 'resourceId', + label: '数据资源', + required: true, + multiple: false, + size: 'md', + valueField: 'id', + labelField: 'name', + source: apiGet('${base}/data_resource/list_no_ware'), + pickerSchema: { + ...resourceList(), }, - body: [ - { - type: 'hidden', - name: 'id', - }, - { - visibleOn: '${!detail}', - type: 'input-image', - name: 'icon', - label: '图标', - required: true, - receiver: apiPost("${base}/upload"), - onEvent: { - success: { - actions: [ - { - actionType: 'setValue', - componentId: 'ware-form', - args: { - value: { - iconId: '${event.data.result.id}' - } - } - } - ] - } - } - }, - { - visibleOn: '${detail}', - type: 'control', - name: 'icon', - label: '图标', - required: true, - body: { - type: 'image', - src: '${icon}', - innerClassName: 'no-border', - } - }, - { - type: 'picker', - name: 'resourceId', - label: '数据资源', - required: true, - multiple: false, - size: 'md', - valueField: 'id', - labelField: 'name', - source: apiGet('${base}/data_resource/list_no_ware'), - pickerSchema: { - ...resourceList(), - }, - staticSchema: { - type: 'tpl', - tpl: "${resourceName}", - onEvent: { - click: { - actions: [ - { - actionType: 'dialog', - ...resourceDetailDialog('resourceId'), - } - ] - } - } - } - }, - { - type: 'input-text', - name: 'name', - label: '商品名称', - maxLength: 10, - showCounter: true, - required: true, - ...formInputClearable, - }, - { - type: 'textarea', - name: 'description', - label: '商品简介', - required: true, - ...formInputClearable, - showCounter: true, - trimContents: true, - minRows: 2, - maxRows: 2, - }, - { - type: 'input-rich-text', - name: 'content', - label: '商品详情', - required: true, - receiver: apiPost("${base}/upload"), - options: { - min_height: 300, + staticSchema: { + type: 'tpl', + tpl: "${resourceName}", + onEvent: { + click: { + actions: [ + { + actionType: 'dialog', + ...resourceDetailDialog('resourceId'), } + ] } - ] - } + } + } + }, + { + type: 'input-text', + name: 'name', + label: '商品名称', + maxLength: 10, + showCounter: true, + required: true, + ...formInputClearable, + }, + { + type: 'textarea', + name: 'description', + label: '商品简介', + required: true, + ...formInputClearable, + showCounter: true, + trimContents: true, + minRows: 2, + maxRows: 2, + }, + { + type: 'input-rich-text', + name: 'content', + label: '商品详情', + required: true, + receiver: apiPost("${base}/upload"), + options: { + min_height: 300, + } + } + ] + } } export function wareAddDialog() { - return { - actionType: 'dialog', - dialog: { - title: '上架数据产品', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(), - api: apiPost(`\${base}/ware/save`), - data: { - add: true, - } - } + return { + actionType: 'dialog', + dialog: { + title: '上架数据产品', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(), + api: apiPost(`\${base}/ware/save`), + data: { + add: true, + } + } } + } } export function wareDetailDialog(field = 'id', actions = []) { - return { - actionType: 'dialog', - dialog: { - title: '数据产品详情', - size: 'md', - actions: actions, - body: { - ...detailForm(), - initApi: apiGet(`\${base}/ware/detail/\${${field}}`), - static: true, - data: { - detail: true, - } - } + return { + actionType: 'dialog', + dialog: { + title: '数据产品详情', + size: 'md', + actions: actions, + body: { + ...detailForm(), + initApi: apiGet(`\${base}/ware/detail/\${${field}}`), + static: true, + data: { + detail: true, } + } } + } } export function wareEditeDialog() { - return { - actionType: 'dialog', - dialog: { - title: '数据产品详情', - size: 'md', - actions: [ - { - type: 'reset', - label: '重置', - }, - { - type: 'submit', - label: '确定', - level: 'primary', - } - ], - body: { - ...detailForm(), - api: apiPost(`\${base}/ware/save`), - initApi: apiGet(`\${base}/ware/detail/\${id}`), - data: { - edit: true - } - }, + return { + actionType: 'dialog', + dialog: { + title: '数据产品详情', + size: 'md', + actions: [ + { + type: 'reset', + label: '重置', + }, + { + type: 'submit', + label: '确定', + level: 'primary', } + ], + body: { + ...detailForm(), + api: apiPost(`\${base}/ware/save`), + initApi: apiGet(`\${base}/ware/detail/\${id}`), + data: { + edit: true + } + }, } + } } diff --git a/gringotts-frontend/pages/index/index.html b/gringotts-frontend/pages/index/index.html index dae0101..82658dd 100644 --- a/gringotts-frontend/pages/index/index.html +++ b/gringotts-frontend/pages/index/index.html @@ -2,7 +2,7 @@ - + @@ -20,6 +20,6 @@
- + diff --git a/gringotts-frontend/pages/index/main.js b/gringotts-frontend/pages/index/main.js index ec62db0..6b6aabf 100644 --- a/gringotts-frontend/pages/index/main.js +++ b/gringotts-frontend/pages/index/main.js @@ -8,66 +8,66 @@ import {tabPermissions} from "./tab-permissions.js"; import {tabMarket} from "./tab-market.js"; useAmis(information => { - return { - id: 'header-service', - className: 'h-full', - type: 'service', - api: apiGet('${base}/user/state'), - onEvent: { - fetchInited: { - actions: [ - { - expression: '${!event.data.responseData.token}', - actionType: 'url', - args: { - url: '/pages/login/index.html', - blank: false, - } - } - ] - } - }, - body: [ - { - type: 'page', - title: information.title, - subTitle: '提供合法合规的数据要素可信供给工具', - toolbar: [ - { - type: 'dropdown-button', - label: '${username}', - align: 'right', - trigger: 'hover', - buttons: [ - { - label: '修改密码', - ...userChangePasswordDialog(), - }, - { - label: '退出登陆', - actionType: 'ajax', - api: apiGet('${base}/user/logout'), - reload: 'header-service', - } - ] - } - ], - bodyClassName: 'p-0', - body: { - className: 'h-full border-0', - type: 'tabs', - tabsMode: 'vertical', - tabs: [ - // tabOverview(), - tabMarket(), - tabPermissions(), - tabCheck(), - tabData(), - tabUser(), - tabSettings(), - ] - }, + return { + id: 'header-service', + className: 'h-full', + type: 'service', + api: apiGet('${base}/user/state'), + onEvent: { + fetchInited: { + actions: [ + { + expression: '${!event.data.responseData.token}', + actionType: 'url', + args: { + url: '/pages/login/index.html', + blank: false, } + } ] - } + } + }, + body: [ + { + type: 'page', + title: information.title, + subTitle: '提供合法合规的数据要素可信供给工具', + toolbar: [ + { + type: 'dropdown-button', + label: '${username}', + align: 'right', + trigger: 'hover', + buttons: [ + { + label: '修改密码', + ...userChangePasswordDialog(), + }, + { + label: '退出登陆', + actionType: 'ajax', + api: apiGet('${base}/user/logout'), + reload: 'header-service', + } + ] + } + ], + bodyClassName: 'p-0', + body: { + className: 'h-full border-0', + type: 'tabs', + tabsMode: 'vertical', + tabs: [ + // tabOverview(), + tabMarket(), + tabPermissions(), + tabCheck(), + tabData(), + tabUser(), + tabSettings(), + ] + }, + } + ] + } }) diff --git a/gringotts-frontend/pages/index/tab-check.js b/gringotts-frontend/pages/index/tab-check.js index 1a185e2..ee87fdf 100644 --- a/gringotts-frontend/pages/index/tab-check.js +++ b/gringotts-frontend/pages/index/tab-check.js @@ -1,146 +1,146 @@ import { - apiGet, - checkerOnly, - checkOverMapping, - checkTypeMapping, - crudCommonOptions, - mappingField, - operationField, - stringField, - timeField, + apiGet, + checkerOnly, + checkOverMapping, + checkTypeMapping, + crudCommonOptions, + mappingField, + operationField, + stringField, + timeField, } from "../../components/constants.js"; import {authenticationDetailDialog, confirmationDetailDialog} from "../../components/permission/dialog-permission.js"; import {wareDetailDialog} from "../../components/ware/dialog-ware.js"; export function tabCheck() { - return { - visibleOn: checkerOnly, - title: '审核审查', - icon: 'fa fa-shield-halved', - reload: true, - body: [ - { - name: 'check_order_list', - type: 'crud', - api: apiGet('${base}/check_order/list'), - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - ], - columns: [ - stringField('description', '描述'), - mappingField('type', '类型', checkTypeMapping), - mappingField('state', '状态', checkOverMapping), - timeField('createdTime', '创建时间'), - stringField('createdUsername', '创建人', 100), - timeField('modifiedTime', '最后修改时间'), - stringField('modifiedUsername', '最后操作人', 100), - operationField('操作', undefined, [ - { - visibleOn: `\${type === 'CONFIRMATION' && state === 'CHECKING'}`, - type: 'action', - label: '处理', - level: 'link', - ...confirmationDetailDialog( - 'parameters.confirmationId', - [ - { - type: 'action', - label: '同意', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), - reload: 'check_order_list', - }, - { - type: 'action', - label: '拒绝', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), - reload: 'check_order_list', - }, - ], - ), - }, - { - visibleOn: `\${type === 'CONFIRMATION' && state !== NORMAL}`, - type: 'action', - label: '查看', - level: 'link', - ...confirmationDetailDialog('parameters.confirmationId'), - }, - { - visibleOn: `\${type === 'AUTHENTICATION' && state === 'CHECKING'}`, - type: 'action', - label: '处理', - level: 'link', - ...authenticationDetailDialog( - 'parameters.authenticationId', - [ - { - type: 'action', - label: '同意', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), - reload: 'check_order_list', - }, - { - type: 'action', - label: '拒绝', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), - reload: 'check_order_list', - }, - ], - ), - }, - { - visibleOn: `\${type === 'AUTHENTICATION' && state !== NORMAL}`, - type: 'action', - label: '查看', - level: 'link', - ...authenticationDetailDialog('parameters.authenticationId'), - }, - { - visibleOn: `\${type === 'MARKET' && state === 'CHECKING'}`, - type: 'action', - label: '处理', - level: 'link', - ...wareDetailDialog( - 'parameters.wareId', - [ - { - type: 'action', - label: '同意', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), - reload: 'check_order_list', - }, - { - type: 'action', - label: '拒绝', - actionType: 'ajax', - close: true, - api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), - reload: 'check_order_list', - }, - ], - ), - }, - { - visibleOn: `\${type === 'MARKET' && state !== NORMAL}`, - type: 'action', - label: '查看', - level: 'link', - ...wareDetailDialog('parameters.wareId'), - }, - ]), - ], - }, + return { + visibleOn: checkerOnly, + title: '审核审查', + icon: 'fa fa-shield-halved', + reload: true, + body: [ + { + name: 'check_order_list', + type: 'crud', + api: apiGet('${base}/check_order/list'), + ...crudCommonOptions(), + headerToolbar: [ + 'reload', ], - } + columns: [ + stringField('description', '描述'), + mappingField('type', '类型', checkTypeMapping), + mappingField('state', '状态', checkOverMapping), + timeField('createdTime', '创建时间'), + stringField('createdUsername', '创建人', 100), + timeField('modifiedTime', '最后修改时间'), + stringField('modifiedUsername', '最后操作人', 100), + operationField('操作', undefined, [ + { + visibleOn: `\${type === 'CONFIRMATION' && state === 'CHECKING'}`, + type: 'action', + label: '处理', + level: 'link', + ...confirmationDetailDialog( + 'parameters.confirmationId', + [ + { + type: 'action', + label: '同意', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), + reload: 'check_order_list', + }, + { + type: 'action', + label: '拒绝', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), + reload: 'check_order_list', + }, + ], + ), + }, + { + visibleOn: `\${type === 'CONFIRMATION' && state !== NORMAL}`, + type: 'action', + label: '查看', + level: 'link', + ...confirmationDetailDialog('parameters.confirmationId'), + }, + { + visibleOn: `\${type === 'AUTHENTICATION' && state === 'CHECKING'}`, + type: 'action', + label: '处理', + level: 'link', + ...authenticationDetailDialog( + 'parameters.authenticationId', + [ + { + type: 'action', + label: '同意', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), + reload: 'check_order_list', + }, + { + type: 'action', + label: '拒绝', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), + reload: 'check_order_list', + }, + ], + ), + }, + { + visibleOn: `\${type === 'AUTHENTICATION' && state !== NORMAL}`, + type: 'action', + label: '查看', + level: 'link', + ...authenticationDetailDialog('parameters.authenticationId'), + }, + { + visibleOn: `\${type === 'MARKET' && state === 'CHECKING'}`, + type: 'action', + label: '处理', + level: 'link', + ...wareDetailDialog( + 'parameters.wareId', + [ + { + type: 'action', + label: '同意', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/APPLY'), + reload: 'check_order_list', + }, + { + type: 'action', + label: '拒绝', + actionType: 'ajax', + close: true, + api: apiGet('${base}/check_order/operation/${checkOrderId}/REJECT'), + reload: 'check_order_list', + }, + ], + ), + }, + { + visibleOn: `\${type === 'MARKET' && state !== NORMAL}`, + type: 'action', + label: '查看', + level: 'link', + ...wareDetailDialog('parameters.wareId'), + }, + ]), + ], + }, + ], + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-data.js b/gringotts-frontend/pages/index/tab-data.js index abc0ebe..38b8b82 100644 --- a/gringotts-frontend/pages/index/tab-data.js +++ b/gringotts-frontend/pages/index/tab-data.js @@ -1,94 +1,94 @@ import { - resourceAddDialog, - resourceDetailDialog, - resourceEditeDialog + resourceAddDialog, + resourceDetailDialog, + resourceEditeDialog } from "../../components/resource/dialog-resource.js"; import { - apiGet, - arrayInCheck, - arrayOutCheck, - checkState, - crudCommonOptions, - mappingField, - operationField, - permissionStateMapping, - timeField, - userOnly + apiGet, + arrayInCheck, + arrayOutCheck, + checkState, + crudCommonOptions, + mappingField, + operationField, + permissionStateMapping, + timeField, + userOnly } from "../../components/constants.js"; export function resourceList() { - return { - type: 'crud', - api: apiGet('${base}/data_resource/list'), - ...crudCommonOptions(), - headerToolbar: [ - 'reload', + return { + type: 'crud', + api: apiGet('${base}/data_resource/list'), + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + { + type: 'action', + label: '', + icon: 'fa fa-plus', + ...resourceAddDialog() + }, + ], + columns: [ + { + label: '名称', + name: 'name', + width: 150, + }, + { + label: '描述', + name: 'description', + }, + mappingField('confirmationState', '确权状态', permissionStateMapping), + timeField('createdTime', '创建时间'), + operationField('操作', undefined, [ + { + type: 'action', + label: '详情', + level: 'link', + ...resourceDetailDialog(), + }, + { + type: 'dropdown-button', + level: 'link', + icon: 'fa fa-ellipsis-h', + hideCaret: true, + trigger: 'hover', + buttons: [ { - type: 'action', - label: '', - icon: 'fa fa-plus', - ...resourceAddDialog() - }, - ], - columns: [ - { - label: '名称', - name: 'name', - width: 150, + disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'), + disabledTip: '审查或确权成功后无法编辑', + tooltipPlacement: 'top', + type: 'action', + label: '编辑', + level: 'link', + ...resourceEditeDialog(), }, { - label: '描述', - name: 'description', + disabledOn: arrayInCheck([checkState.checking], 'confirmationState'), + disabledTip: '审查中无法删除', + tooltipPlacement: 'bottom', + type: 'action', + label: "删除", + confirmTitle: '确认删除', + confirmText: '确认删除名称为「${name}」的数据资源吗?', + actionType: 'ajax', + api: apiGet('${base}/data_resource/remove/${id}') }, - mappingField('confirmationState', '确权状态', permissionStateMapping), - timeField('createdTime', '创建时间'), - operationField('操作', undefined, [ - { - type: 'action', - label: '详情', - level: 'link', - ...resourceDetailDialog(), - }, - { - type: 'dropdown-button', - level: 'link', - icon: 'fa fa-ellipsis-h', - hideCaret: true, - trigger: 'hover', - buttons: [ - { - disabledOn: arrayOutCheck([checkState.none, checkState.draft], 'confirmationState'), - disabledTip: '审查或确权成功后无法编辑', - tooltipPlacement: 'top', - type: 'action', - label: '编辑', - level: 'link', - ...resourceEditeDialog(), - }, - { - disabledOn: arrayInCheck([checkState.checking], 'confirmationState'), - disabledTip: '审查中无法删除', - tooltipPlacement: 'bottom', - type: 'action', - label: "删除", - confirmTitle: '确认删除', - confirmText: '确认删除名称为「${name}」的数据资源吗?', - actionType: 'ajax', - api: apiGet('${base}/data_resource/remove/${id}') - }, - ] - }, - ]), - ] - } + ] + }, + ]), + ] + } } export function tabData() { - return { - visibleOn: userOnly, - title: '数据资源', - icon: 'fa fa-database', - reload: true, - body: resourceList(), - } + return { + visibleOn: userOnly, + title: '数据资源', + icon: 'fa fa-database', + reload: true, + body: resourceList(), + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-market.js b/gringotts-frontend/pages/index/tab-market.js index 07af0b1..cae211b 100644 --- a/gringotts-frontend/pages/index/tab-market.js +++ b/gringotts-frontend/pages/index/tab-market.js @@ -1,153 +1,153 @@ import {wareAddDialog, wareDetailDialog, wareEditeDialog} from "../../components/ware/dialog-ware.js"; import { - apiGet, - crudCommonOptions, - mappingField, - operationField, - permissionStateMapping, - timeField + apiGet, + crudCommonOptions, + mappingField, + operationField, + permissionStateMapping, + timeField } from "../../components/constants.js"; import {authenticationAddDialog} from "../../components/permission/dialog-permission.js"; export function tabMarket() { - return { - title: '数据市场', - icon: 'fa fa-store', - reload: true, - body: [ - { - type: 'tabs', - tabs: [ - { - title: '公开数据', - body: { - type: 'crud', - api: { - ...apiGet('${base}/ware/list_public'), - adaptor: (payload, response, api, context) => { - payload.data = payload.data.map(i => { - return { - ...i, - targetId: i.resourceId, - } - }) - return payload - } - }, - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - ], - mode: 'cards', - card: { - header: { - title: '${name}', - subTitle: '${createdTime}', - description: '${description}', - avatar: '${icon}', - avatarClassName: 'pull-left thumb-md avatar b-3x m-r' - }, - actions: [ - { - type: 'action', - label: '查看', - ...wareDetailDialog(), - }, - { - type: 'action', - label: '申请授权', - ...authenticationAddDialog(), - } - ] - }, - } - }, - { - title: '我的数据', - body: { - type: 'crud', - api: apiGet('${base}/ware/list'), - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - { - type: 'action', - label: '', - icon: 'fa fa-plus', - ...wareAddDialog() - }, - ], - columns: [ - { - name: 'name', - label: '名称', - width: 200, - }, - { - name: 'description', - label: '描述', - }, - mappingField('state', '状态', permissionStateMapping), - timeField('createdTime', '创建时间'), - operationField('操作', undefined, [ - { - type: 'action', - label: '查看', - level: 'link', - ...wareDetailDialog(), - }, - { - visibleOn: "${state === 'CHECKING'}", - type: 'action', - label: '撤销', - level: 'link', - confirmTitle: '确认撤销', - confirmText: '确认撤销名称为「${name}」的确权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/ware/retract/${id}'), - }, - { - visibleOn: "${state === 'DRAFT' || state === 'REJECT'}", - type: 'action', - label: '提交', - level: 'link', - confirmTitle: '确认提交', - confirmText: '确认提交名称为「${name}」的确权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/ware/submit/${id}'), - }, - { - visibleOn: "${!public}", - type: 'dropdown-button', - level: 'link', - icon: 'fa fa-ellipsis-h', - hideCaret: true, - trigger: 'hover', - buttons: [ - { - disabledOn: "${state !== 'DRAFT'}", - type: 'action', - label: '编辑', - level: 'link', - ...wareEditeDialog(), - }, - { - disabledOn: "${state === 'CHECKING'}", - type: 'action', - label: "删除", - confirmTitle: '确认删除', - confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', - actionType: 'ajax', - api: apiGet('${base}/ware/remove/${id}'), - }, - ] - }, - ]), - ] - } - }, + return { + title: '数据市场', + icon: 'fa fa-store', + reload: true, + body: [ + { + type: 'tabs', + tabs: [ + { + title: '公开数据', + body: { + type: 'crud', + api: { + ...apiGet('${base}/ware/list_public'), + adaptor: (payload, response, api, context) => { + payload.data = payload.data.map(i => { + return { + ...i, + targetId: i.resourceId, + } + }) + return payload + } + }, + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + ], + mode: 'cards', + card: { + header: { + title: '${name}', + subTitle: '${createdTime}', + description: '${description}', + avatar: '${icon}', + avatarClassName: 'pull-left thumb-md avatar b-3x m-r' + }, + actions: [ + { + type: 'action', + label: '查看', + ...wareDetailDialog(), + }, + { + type: 'action', + label: '申请授权', + ...authenticationAddDialog(), + } ] + }, } + }, + { + title: '我的数据', + body: { + type: 'crud', + api: apiGet('${base}/ware/list'), + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + { + type: 'action', + label: '', + icon: 'fa fa-plus', + ...wareAddDialog() + }, + ], + columns: [ + { + name: 'name', + label: '名称', + width: 200, + }, + { + name: 'description', + label: '描述', + }, + mappingField('state', '状态', permissionStateMapping), + timeField('createdTime', '创建时间'), + operationField('操作', undefined, [ + { + type: 'action', + label: '查看', + level: 'link', + ...wareDetailDialog(), + }, + { + visibleOn: "${state === 'CHECKING'}", + type: 'action', + label: '撤销', + level: 'link', + confirmTitle: '确认撤销', + confirmText: '确认撤销名称为「${name}」的确权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/ware/retract/${id}'), + }, + { + visibleOn: "${state === 'DRAFT' || state === 'REJECT'}", + type: 'action', + label: '提交', + level: 'link', + confirmTitle: '确认提交', + confirmText: '确认提交名称为「${name}」的确权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/ware/submit/${id}'), + }, + { + visibleOn: "${!public}", + type: 'dropdown-button', + level: 'link', + icon: 'fa fa-ellipsis-h', + hideCaret: true, + trigger: 'hover', + buttons: [ + { + disabledOn: "${state !== 'DRAFT'}", + type: 'action', + label: '编辑', + level: 'link', + ...wareEditeDialog(), + }, + { + disabledOn: "${state === 'CHECKING'}", + type: 'action', + label: "删除", + confirmTitle: '确认删除', + confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', + actionType: 'ajax', + api: apiGet('${base}/ware/remove/${id}'), + }, + ] + }, + ]), + ] + } + }, ] - } + } + ] + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-overview.js b/gringotts-frontend/pages/index/tab-overview.js index a149562..be0abf6 100644 --- a/gringotts-frontend/pages/index/tab-overview.js +++ b/gringotts-frontend/pages/index/tab-overview.js @@ -1,9 +1,9 @@ export function tabOverview() { - return { - title: '概览', - icon: 'fa fa-house', - body: [ - 'hello world' - ] - } + return { + title: '概览', + icon: 'fa fa-house', + body: [ + 'hello world' + ] + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-permissions.js b/gringotts-frontend/pages/index/tab-permissions.js index d6eaae8..bb84eed 100644 --- a/gringotts-frontend/pages/index/tab-permissions.js +++ b/gringotts-frontend/pages/index/tab-permissions.js @@ -1,196 +1,196 @@ import { - apiGet, - arrayInCheck, - arrayOutCheck, - checkState, - crudCommonOptions, - customerOnly, - mappingField, - operationField, - permissionStateMapping, - providerOnly, - stringField, - stringWrapField, - timeField, - userOnly, + apiGet, + arrayInCheck, + arrayOutCheck, + checkState, + crudCommonOptions, + customerOnly, + mappingField, + operationField, + permissionStateMapping, + providerOnly, + stringField, + stringWrapField, + timeField, + userOnly, } from "../../components/constants.js"; import { - authenticationAddDialog, - authenticationDetailDialog, - authenticationEditeDialog, - confirmationAddDialog, - confirmationDetailDialog, - confirmationEditeDialog, + authenticationAddDialog, + authenticationDetailDialog, + authenticationEditeDialog, + confirmationAddDialog, + confirmationDetailDialog, + confirmationEditeDialog, } from "../../components/permission/dialog-permission.js"; export function tabPermissions() { - return { - visibleOn: userOnly, - title: '权属管理', - icon: 'fa fa-key', - reload: true, - body: { - type: 'tabs', - tabs: [ + return { + visibleOn: userOnly, + title: '权属管理', + icon: 'fa fa-key', + reload: true, + body: { + type: 'tabs', + tabs: [ + { + visibleOn: providerOnly, + title: '确权管理', + body: { + type: 'crud', + api: { + ...apiGet('${base}/confirmation/list') + }, + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + { + type: 'action', + label: '', + icon: 'fa fa-plus', + ...confirmationAddDialog() + }, + ], + columns: [ + stringField('name', '名称', 200), + stringWrapField('description', '描述'), + mappingField('state', '状态', permissionStateMapping), + timeField('createdTime', '创建时间'), + operationField('操作', undefined, [ { - visibleOn: providerOnly, - title: '确权管理', - body: { - type: 'crud', - api: { - ...apiGet('${base}/confirmation/list') - }, - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - { - type: 'action', - label: '', - icon: 'fa fa-plus', - ...confirmationAddDialog() - }, - ], - columns: [ - stringField('name', '名称', 200), - stringWrapField('description', '描述'), - mappingField('state', '状态', permissionStateMapping), - timeField('createdTime', '创建时间'), - operationField('操作', undefined, [ - { - type: 'action', - label: '查看', - level: 'link', - ...confirmationDetailDialog(), - }, - { - visibleOn: "${state === 'CHECKING'}", - type: 'action', - label: '撤销', - level: 'link', - confirmTitle: '确认撤销', - confirmText: '确认撤销名称为「${name}」的确权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/confirmation/retract/${id}'), - }, - { - visibleOn: "${state === 'DRAFT' || state === 'REJECT'}", - type: 'action', - label: '提交', - level: 'link', - confirmTitle: '确认提交', - confirmText: '确认提交名称为「${name}」的确权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/confirmation/submit/${id}'), - }, - { - type: 'dropdown-button', - level: 'link', - icon: 'fa fa-ellipsis-h', - hideCaret: true, - trigger: 'hover', - buttons: [ - { - disabledOn: "${state !== 'DRAFT'}", - type: 'action', - label: '编辑', - level: 'link', - ...confirmationEditeDialog(), - }, - { - disabledOn: "${state === 'CHECKING'}", - type: 'action', - label: "删除", - confirmTitle: '确认删除', - confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', - actionType: 'ajax', - api: apiGet('${base}/confirmation/remove/${id}'), - }, - ] - }, - ]), - ] - } + type: 'action', + label: '查看', + level: 'link', + ...confirmationDetailDialog(), }, { - visibleOn: customerOnly, - title: '授权管理', - body: { - type: 'crud', - api: { - ...apiGet('${base}/authentication/list') - }, - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - { - type: 'action', - label: '', - icon: 'fa fa-plus', - ...authenticationAddDialog() - }, - ], - columns: [ - stringField('name', '名称', 200), - stringWrapField('description', '描述'), - mappingField('state', '状态', permissionStateMapping), - timeField('createdTime', '创建时间'), - operationField('操作', undefined, [ - { - type: 'action', - label: '查看', - level: 'link', - ...authenticationDetailDialog(), - }, - { - visibleOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'), - type: 'action', - label: '撤销', - level: 'link', - confirmTitle: '确认撤销', - confirmText: '确认撤销名称为「${name}」的授权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/authentication/retract/${id}'), - }, - { - visibleOn: arrayInCheck([checkState.draft], 'state'), - type: 'action', - label: '提交', - level: 'link', - confirmTitle: '确认提交', - confirmText: '确认提交名称为「${name}」的授权申请吗?', - actionType: 'ajax', - api: apiGet('${base}/authentication/submit/${id}'), - }, - { - type: 'dropdown-button', - level: 'link', - icon: 'fa fa-ellipsis-h', - hideCaret: true, - trigger: 'hover', - buttons: [ - { - disabledOn: arrayOutCheck([checkState.draft], 'state'), - type: 'action', - label: '编辑', - level: 'link', - ...authenticationEditeDialog(), - }, - { - disabledOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'), - type: 'action', - label: "删除", - confirmTitle: '确认删除', - confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', - actionType: 'ajax', - api: apiGet('${base}/authentication/remove/${id}'), - }, - ] - }, - ]), - ] - } + visibleOn: "${state === 'CHECKING'}", + type: 'action', + label: '撤销', + level: 'link', + confirmTitle: '确认撤销', + confirmText: '确认撤销名称为「${name}」的确权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/confirmation/retract/${id}'), }, + { + visibleOn: "${state === 'DRAFT' || state === 'REJECT'}", + type: 'action', + label: '提交', + level: 'link', + confirmTitle: '确认提交', + confirmText: '确认提交名称为「${name}」的确权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/confirmation/submit/${id}'), + }, + { + type: 'dropdown-button', + level: 'link', + icon: 'fa fa-ellipsis-h', + hideCaret: true, + trigger: 'hover', + buttons: [ + { + disabledOn: "${state !== 'DRAFT'}", + type: 'action', + label: '编辑', + level: 'link', + ...confirmationEditeDialog(), + }, + { + disabledOn: "${state === 'CHECKING'}", + type: 'action', + label: "删除", + confirmTitle: '确认删除', + confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', + actionType: 'ajax', + api: apiGet('${base}/confirmation/remove/${id}'), + }, + ] + }, + ]), ] - } + } + }, + { + visibleOn: customerOnly, + title: '授权管理', + body: { + type: 'crud', + api: { + ...apiGet('${base}/authentication/list') + }, + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + { + type: 'action', + label: '', + icon: 'fa fa-plus', + ...authenticationAddDialog() + }, + ], + columns: [ + stringField('name', '名称', 200), + stringWrapField('description', '描述'), + mappingField('state', '状态', permissionStateMapping), + timeField('createdTime', '创建时间'), + operationField('操作', undefined, [ + { + type: 'action', + label: '查看', + level: 'link', + ...authenticationDetailDialog(), + }, + { + visibleOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'), + type: 'action', + label: '撤销', + level: 'link', + confirmTitle: '确认撤销', + confirmText: '确认撤销名称为「${name}」的授权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/authentication/retract/${id}'), + }, + { + visibleOn: arrayInCheck([checkState.draft], 'state'), + type: 'action', + label: '提交', + level: 'link', + confirmTitle: '确认提交', + confirmText: '确认提交名称为「${name}」的授权申请吗?', + actionType: 'ajax', + api: apiGet('${base}/authentication/submit/${id}'), + }, + { + type: 'dropdown-button', + level: 'link', + icon: 'fa fa-ellipsis-h', + hideCaret: true, + trigger: 'hover', + buttons: [ + { + disabledOn: arrayOutCheck([checkState.draft], 'state'), + type: 'action', + label: '编辑', + level: 'link', + ...authenticationEditeDialog(), + }, + { + disabledOn: arrayInCheck([checkState.ownerChecking, checkState.checking], 'state'), + type: 'action', + label: "删除", + confirmTitle: '确认删除', + confirmText: '确认删除名称为「${name}」的确权申请吗?删除后对应的数据资源处于未确权状态。', + actionType: 'ajax', + api: apiGet('${base}/authentication/remove/${id}'), + }, + ] + }, + ]), + ] + } + }, + ] } + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-settings.js b/gringotts-frontend/pages/index/tab-settings.js index 360dd93..9ac8a28 100644 --- a/gringotts-frontend/pages/index/tab-settings.js +++ b/gringotts-frontend/pages/index/tab-settings.js @@ -1,12 +1,12 @@ import {administratorOnly} from "../../components/constants.js"; export function tabSettings() { - return { - visibleOn: administratorOnly, - title: '系统管理', - icon: 'fa fa-gear', - body: [ - 'hello world' - ] - } + return { + visibleOn: administratorOnly, + title: '系统管理', + icon: 'fa fa-gear', + body: [ + 'hello world' + ] + } } \ No newline at end of file diff --git a/gringotts-frontend/pages/index/tab-user.js b/gringotts-frontend/pages/index/tab-user.js index 4671103..7ec06ff 100644 --- a/gringotts-frontend/pages/index/tab-user.js +++ b/gringotts-frontend/pages/index/tab-user.js @@ -1,83 +1,83 @@ import { - administratorOnly, - apiGet, - copyField, - crudCommonOptions, - mappingField, - operationField, - timeField, - userRoleMapping, - userStateMapping + administratorOnly, + apiGet, + copyField, + crudCommonOptions, + mappingField, + operationField, + timeField, + userRoleMapping, + userStateMapping } from '../../components/constants.js' import {userCheckDialog, userDetailDialog} from "../../components/user/dialog-user-check.js"; import {userAdministratorRegisterDialog} from "../../components/user/dialog-user-register.js"; export function tabUser() { - return { - visibleOn: administratorOnly, - title: '用户管理', - icon: 'fa fa-user', - reload: true, - body: [ + return { + visibleOn: administratorOnly, + title: '用户管理', + icon: 'fa fa-user', + reload: true, + body: [ + { + type: 'crud', + api: apiGet('${base}/user_management/list'), + ...crudCommonOptions(), + headerToolbar: [ + 'reload', + { + type: 'action', + icon: 'fa fa-plus', + tooltip: '新增账号', + ...userAdministratorRegisterDialog(), + }, + ], + columns: [ + copyField( + 'username', + '邮箱', + undefined, + undefined, + userDetailDialog(), + ), + mappingField('role', '角色', userRoleMapping, 120), + mappingField('state', '账号状态', userStateMapping), + timeField('createdTime', '创建时间'), + timeField('lastLoginTime', '上次登陆时间'), + operationField('操作', undefined, [ { - type: 'crud', - api: apiGet('${base}/user_management/list'), - ...crudCommonOptions(), - headerToolbar: [ - 'reload', - { - type: 'action', - icon: 'fa fa-plus', - tooltip: '新增账号', - ...userAdministratorRegisterDialog(), - }, - ], - columns: [ - copyField( - 'username', - '邮箱', - undefined, - undefined, - userDetailDialog(), - ), - mappingField('role', '角色', userRoleMapping, 120), - mappingField('state', '账号状态', userStateMapping), - timeField('createdTime', '创建时间'), - timeField('lastLoginTime', '上次登陆时间'), - operationField('操作', undefined, [ - { - visibleOn: "${state === 'CHECKING'}", - label: '审核', - icon: 'fa fa-fingerprint', - level: 'primary', - size: 'xs', - ...userCheckDialog(), - }, - { - visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}", - label: '禁用', - icon: 'fa fa-ban', - level: 'danger', - size: 'xs', - confirmText: '确认禁用账号${username}?', - confirmTitle: '禁用账号', - actionType: 'ajax', - api: apiGet('${base}/user_management/disable/${username}'), - }, - { - visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}", - label: '启用', - icon: 'fa fa-check', - level: 'success', - size: 'xs', - confirmText: '确认启用账号${username}?', - confirmTitle: '启用账号', - actionType: 'ajax', - api: apiGet('${base}/user_management/enable/${username}'), - } - ]), - ] + visibleOn: "${state === 'CHECKING'}", + label: '审核', + icon: 'fa fa-fingerprint', + level: 'primary', + size: 'xs', + ...userCheckDialog(), + }, + { + visibleOn: "${state === 'NORMAL' && role !== 'ADMINISTRATOR'}", + label: '禁用', + icon: 'fa fa-ban', + level: 'danger', + size: 'xs', + confirmText: '确认禁用账号${username}?', + confirmTitle: '禁用账号', + actionType: 'ajax', + api: apiGet('${base}/user_management/disable/${username}'), + }, + { + visibleOn: "${state === 'DISABLED' && role !== 'ADMINISTRATOR'}", + label: '启用', + icon: 'fa fa-check', + level: 'success', + size: 'xs', + confirmText: '确认启用账号${username}?', + confirmTitle: '启用账号', + actionType: 'ajax', + api: apiGet('${base}/user_management/enable/${username}'), } + ]), ] - } + } + ] + } } \ No newline at end of file diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/WebApplication.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/WebApplication.java index 1b54fc0..c6063f1 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/WebApplication.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/WebApplication.java @@ -29,24 +29,24 @@ import org.springframework.scheduling.annotation.EnableAsync; @EnableConfigurationProperties @EnableEncryptableProperties public class WebApplication implements ApplicationRunner { - private final UserService userService; + private final UserService userService; - public WebApplication(UserService userService) { - this.userService = userService; - } + public WebApplication(UserService userService) { + this.userService = userService; + } - public static void main(String[] args) { - SpringApplication.run(WebApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(WebApplication.class, args); + } - @Override - public void run(ApplicationArguments args) throws Exception { - // 初始化系统管理员 - userService.initial(); - } + @Override + public void run(ApplicationArguments args) throws Exception { + // 初始化系统管理员 + userService.initial(); + } - @Bean - public AuditorAware auditorAware(UserService userService) { - return userService::currentLoginUserOptional; - } + @Bean + public AuditorAware auditorAware(UserService userService) { + return userService::currentLoginUserOptional; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/ErrorController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/ErrorController.java index 71f1934..973919b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/ErrorController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/ErrorController.java @@ -16,12 +16,12 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; */ @RestControllerAdvice public class ErrorController { - private static final Logger logger = LoggerFactory.getLogger(ErrorController.class); + private static final Logger logger = LoggerFactory.getLogger(ErrorController.class); - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ExceptionHandler(Throwable.class) - public AmisResponse errorHandler(Throwable throwable) { - logger.error("Error", throwable); - return AmisResponse.responseError(throwable.getMessage()); - } + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler(Throwable.class) + public AmisResponse errorHandler(Throwable throwable) { + logger.error("Error", throwable); + return AmisResponse.responseError(throwable.getMessage()); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/HostConfiguration.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/HostConfiguration.java index eafffc8..62a8fef 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/HostConfiguration.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/HostConfiguration.java @@ -12,5 +12,5 @@ import org.springframework.context.annotation.Configuration; @ConfigurationProperties(prefix = "gringotts.host") @Configuration public class HostConfiguration { - private String prefix = "http://127.0.0.1:20080"; + private String prefix = "http://127.0.0.1:20080"; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SaTokenConfiguration.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SaTokenConfiguration.java index 630bc03..f7217cc 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SaTokenConfiguration.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SaTokenConfiguration.java @@ -12,33 +12,33 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * web配置 * * @author wn - * @since 2024-11-14 + * @since 2024-11-14 */ @Slf4j @Configuration public class SaTokenConfiguration implements WebMvcConfigurer { - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry - .addInterceptor( - new SaInterceptor(handler -> { - SaRouter - .match("/**") - .notMatch("/") - .notMatch("/index.html") - .notMatch("/assets/**") - .notMatch("/pages/**") - .notMatch("/user/**") - .notMatch("/upload/download/**") - .check(r -> { - try { - StpUtil.checkLogin(); - } catch (Exception e) { - throw new RuntimeException("账号未登陆", e); - } - }); - }) - ) - .addPathPatterns("/**"); - } + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry + .addInterceptor( + new SaInterceptor(handler -> { + SaRouter + .match("/**") + .notMatch("/") + .notMatch("/index.html") + .notMatch("/assets/**") + .notMatch("/pages/**") + .notMatch("/user/**") + .notMatch("/upload/download/**") + .check(r -> { + try { + StpUtil.checkLogin(); + } catch (Exception e) { + throw new RuntimeException("账号未登陆", e); + } + }); + }) + ) + .addPathPatterns("/**"); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SnowflakeIdGenerator.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SnowflakeIdGenerator.java index 441172d..3662bd8 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SnowflakeIdGenerator.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/SnowflakeIdGenerator.java @@ -14,80 +14,80 @@ import org.slf4j.LoggerFactory; * @date 2024-11-14 */ public class SnowflakeIdGenerator implements IdentifierGenerator { - private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class); + private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class); - @Override - public Serializable generate(SharedSessionContractImplementor session, Object object) { - try { - return Snowflake.next(); - } catch (Exception e) { - logger.error("Generate snowflake id failed", e); - throw new RuntimeException(e); + @Override + public Serializable generate(SharedSessionContractImplementor session, Object object) { + try { + return Snowflake.next(); + } catch (Exception e) { + logger.error("Generate snowflake id failed", e); + throw new RuntimeException(e); + } + } + + private static class Snowflake { + /** + * 起始的时间戳 + */ + private final static long START_TIMESTAMP = 1; + + /** + * 序列号占用的位数 + */ + private final static long SEQUENCE_BIT = 11; + + /** + * 序列号最大值 + */ + private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT); + + /** + * 时间戳值向左位移 + */ + private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT; + + /** + * 序列号 + */ + private static long sequence = 0; + /** + * 上一次时间戳 + */ + private static long lastTimestamp = -1; + + public static synchronized long next() { + long currentTimestamp = nowTimestamp(); + if (currentTimestamp < lastTimestamp) { + throw new RuntimeException("Clock have moved backwards."); + } + + if (currentTimestamp == lastTimestamp) { + // 相同毫秒内, 序列号自增 + sequence = (sequence + 1) & MAX_SEQUENCE_BIT; + // 同一毫秒的序列数已经达到最大 + if (sequence == 0) { + currentTimestamp = nextTimestamp(); } + } else { + // 不同毫秒内, 序列号置为0 + sequence = 0; + } + + lastTimestamp = currentTimestamp; + return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence; } - private static class Snowflake { - /** - * 起始的时间戳 - */ - private final static long START_TIMESTAMP = 1; - - /** - * 序列号占用的位数 - */ - private final static long SEQUENCE_BIT = 11; - - /** - * 序列号最大值 - */ - private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT); - - /** - * 时间戳值向左位移 - */ - private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT; - - /** - * 序列号 - */ - private static long sequence = 0; - /** - * 上一次时间戳 - */ - private static long lastTimestamp = -1; - - public static synchronized long next() { - long currentTimestamp = nowTimestamp(); - if (currentTimestamp < lastTimestamp) { - throw new RuntimeException("Clock have moved backwards."); - } - - if (currentTimestamp == lastTimestamp) { - // 相同毫秒内, 序列号自增 - sequence = (sequence + 1) & MAX_SEQUENCE_BIT; - // 同一毫秒的序列数已经达到最大 - if (sequence == 0) { - currentTimestamp = nextTimestamp(); - } - } else { - // 不同毫秒内, 序列号置为0 - sequence = 0; - } - - lastTimestamp = currentTimestamp; - return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence; - } - - private static long nextTimestamp() { - long milli = nowTimestamp(); - while (milli <= lastTimestamp) { - milli = nowTimestamp(); - } - return milli; - } - - private static long nowTimestamp() { - return Instant.now().toEpochMilli(); - } + private static long nextTimestamp() { + long milli = nowTimestamp(); + while (milli <= lastTimestamp) { + milli = nowTimestamp(); + } + return milli; } + + private static long nowTimestamp() { + return Instant.now().toEpochMilli(); + } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/UploadConfiguration.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/UploadConfiguration.java index 8656036..6828a81 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/UploadConfiguration.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/UploadConfiguration.java @@ -14,5 +14,5 @@ import org.springframework.context.annotation.Configuration; @ConfigurationProperties(prefix = "gringotts.upload") @Configuration public class UploadConfiguration { - private String uploadPath = "./upload"; + private String uploadPath = "./upload"; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisItemResponse.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisItemResponse.java index 6f626db..5d9fbc0 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisItemResponse.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisItemResponse.java @@ -7,7 +7,7 @@ package com.eshore.gringotts.web.configuration.amis; * @date 2023-07-06 */ public class AmisItemResponse extends AmisMapResponse { - public void setDetail(Object detail) { - getData().put("item", detail); - } + public void setDetail(Object detail) { + getData().put("item", detail); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisListResponse.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisListResponse.java index 5fb19cb..d13e74d 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisListResponse.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisListResponse.java @@ -7,24 +7,24 @@ package com.eshore.gringotts.web.configuration.amis; * @date 2023-07-06 */ public class AmisListResponse extends AmisMapResponse { - public void setData(Iterable list) { - getData().put("items", list); - } + public void setData(Iterable list) { + getData().put("items", list); + } - public void setTotal(Long total) { - getData().put("total", total); - } + public void setTotal(Long total) { + getData().put("total", total); + } - public void setTotal(Integer total) { - setTotal(total.longValue()); - } + public void setTotal(Integer total) { + setTotal(total.longValue()); + } - public void setData(Iterable list, Long total) { - setData(list); - setTotal(total); - } + public void setData(Iterable list, Long total) { + setData(list); + setTotal(total); + } - public void setData(Iterable list, Integer total) { - setData(list, total.longValue()); - } + public void setData(Iterable list, Integer total) { + setData(list, total.longValue()); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisMapResponse.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisMapResponse.java index a8832ac..9c66a48 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisMapResponse.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisMapResponse.java @@ -10,12 +10,12 @@ import java.util.Map; * @date 2023-07-06 */ public class AmisMapResponse extends AmisResponse> { - public AmisMapResponse() { - setData(new HashMap<>()); - } + public AmisMapResponse() { + setData(new HashMap<>()); + } - public AmisMapResponse setData(String key, Object value) { - getData().put(key, value); - return this; - } + public AmisMapResponse setData(String key, Object value) { + getData().put(key, value); + return this; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisResponse.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisResponse.java index 309d272..6fe0aec 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisResponse.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/configuration/amis/AmisResponse.java @@ -16,91 +16,91 @@ import lombok.ToString; @Getter @Setter public class AmisResponse { - private static final int SUCCESS_STATUS = 0; - private static final int ERROR_STATUS = 500; - private static final String SUCCESS_MESSAGE = "成功"; - private static final String ERROR_MESSAGE = "错误"; - private Integer status; - @JsonProperty("msg") - private String message; - private T data; + private static final int SUCCESS_STATUS = 0; + private static final int ERROR_STATUS = 500; + private static final String SUCCESS_MESSAGE = "成功"; + private static final String ERROR_MESSAGE = "错误"; + private Integer status; + @JsonProperty("msg") + private String message; + private T data; - public static AmisResponse responseError() { - return responseError(ERROR_MESSAGE); - } + public static AmisResponse responseError() { + return responseError(ERROR_MESSAGE); + } - public static AmisResponse responseError(String message) { - AmisResponse response = new AmisResponse<>(); - response.setStatus(ERROR_STATUS); - response.setMessage(message); - return response; - } + public static AmisResponse responseError(String message) { + AmisResponse response = new AmisResponse<>(); + response.setStatus(ERROR_STATUS); + response.setMessage(message); + return response; + } - public static AmisResponse responseSuccess() { - return responseSuccess(SUCCESS_MESSAGE); - } + public static AmisResponse responseSuccess() { + return responseSuccess(SUCCESS_MESSAGE); + } - public static AmisResponse responseSuccess(String message) { - AmisResponse response = new AmisResponse<>(); - response.setStatus(SUCCESS_STATUS); - response.setMessage(message); - return response; - } + public static AmisResponse responseSuccess(String message) { + AmisResponse response = new AmisResponse<>(); + response.setStatus(SUCCESS_STATUS); + response.setMessage(message); + return response; + } - public static AmisResponse responseSuccess(String message, E data) { - AmisResponse response = new AmisResponse<>(); - response.setStatus(SUCCESS_STATUS); - response.setMessage(message); - response.setData(data); - return response; - } + public static AmisResponse responseSuccess(String message, E data) { + AmisResponse response = new AmisResponse<>(); + response.setStatus(SUCCESS_STATUS); + response.setMessage(message); + response.setData(data); + return response; + } - public static AmisResponse responseSuccess(E data) { - return responseSuccess(SUCCESS_MESSAGE, data); - } + public static AmisResponse responseSuccess(E data) { + return responseSuccess(SUCCESS_MESSAGE, data); + } - public static AmisMapResponse responseMapData() { - AmisMapResponse response = new AmisMapResponse(); - response.setStatus(SUCCESS_STATUS); - response.setMessage(SUCCESS_MESSAGE); - return response; - } + public static AmisMapResponse responseMapData() { + AmisMapResponse response = new AmisMapResponse(); + response.setStatus(SUCCESS_STATUS); + response.setMessage(SUCCESS_MESSAGE); + return response; + } - public static AmisMapResponse responseMapData(Map data) { - AmisMapResponse response = responseMapData(); - response.setData(data); - return response; - } + public static AmisMapResponse responseMapData(Map data) { + AmisMapResponse response = responseMapData(); + response.setData(data); + return response; + } - public static AmisMapResponse responseMapData(String key, Object value) { - AmisMapResponse response = responseMapData(); - response.setData(key, value); - return response; - } + public static AmisMapResponse responseMapData(String key, Object value) { + AmisMapResponse response = responseMapData(); + response.setData(key, value); + return response; + } - public static AmisListResponse responseListData(Iterable data) { - AmisListResponse response = new AmisListResponse(); - response.setStatus(SUCCESS_STATUS); - response.setMessage(SUCCESS_MESSAGE); - response.setData(data); - return response; - } + public static AmisListResponse responseListData(Iterable data) { + AmisListResponse response = new AmisListResponse(); + response.setStatus(SUCCESS_STATUS); + response.setMessage(SUCCESS_MESSAGE); + response.setData(data); + return response; + } - public static AmisListResponse responseListData(Iterable data, Integer total) { - AmisListResponse response = responseListData(data); - response.setTotal(total); - return response; - } + public static AmisListResponse responseListData(Iterable data, Integer total) { + AmisListResponse response = responseListData(data); + response.setTotal(total); + return response; + } - public static AmisListResponse responseListData(Iterable data, Long total) { - AmisListResponse response = responseListData(data); - response.setTotal(total); - return response; - } + public static AmisListResponse responseListData(Iterable data, Long total) { + AmisListResponse response = responseListData(data); + response.setTotal(total); + return response; + } - public static AmisItemResponse responseItemData(Object detail) { - AmisItemResponse response = new AmisItemResponse(); - response.setDetail(detail); - return response; - } + public static AmisItemResponse responseItemData(Object detail) { + AmisItemResponse response = new AmisItemResponse(); + response.setDetail(detail); + return response; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/DetailController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/DetailController.java index 69c5899..4e9343a 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/DetailController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/DetailController.java @@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse; * @date 2024-11-28 */ public interface DetailController { - AmisResponse detail(Long id) throws Exception; + AmisResponse detail(Long id) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/ListController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/ListController.java index ebdffe0..8501f41 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/ListController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/ListController.java @@ -9,7 +9,7 @@ import org.eclipse.collections.api.list.ImmutableList; * @date 2024-11-28 */ public interface ListController { - AmisResponse> list() throws Exception; + AmisResponse> list() throws Exception; - AmisResponse> list(Query query) throws Exception; + AmisResponse> list(Query query) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/RemoveController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/RemoveController.java index 5728b0a..9ac836b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/RemoveController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/RemoveController.java @@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse; * @date 2024-11-28 */ public interface RemoveController { - AmisResponse remove(Long id) throws Exception; + AmisResponse remove(Long id) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SaveController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SaveController.java index 5635ddd..630b877 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SaveController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SaveController.java @@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse; * @date 2024-11-28 */ public interface SaveController { - AmisResponse save(SAVE_ITEM item) throws Exception; + AmisResponse save(SAVE_ITEM item) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SimpleControllerSupport.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SimpleControllerSupport.java index 740c5b3..e088b84 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SimpleControllerSupport.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/SimpleControllerSupport.java @@ -19,66 +19,66 @@ import org.springframework.web.bind.annotation.RequestBody; */ @Slf4j public abstract class SimpleControllerSupport implements SimpleController { - protected static final String SAVE = "/save"; - protected static final String LIST = "/list"; - protected static final String DETAIL = "/detail/{id}"; - protected static final String REMOVE = "/remove/{id}"; + protected static final String SAVE = "/save"; + protected static final String LIST = "/list"; + protected static final String DETAIL = "/detail/{id}"; + protected static final String REMOVE = "/remove/{id}"; - private final SimpleServiceSupport service; + private final SimpleServiceSupport service; - public SimpleControllerSupport(SimpleServiceSupport service) { - this.service = service; + public SimpleControllerSupport(SimpleServiceSupport service) { + this.service = service; + } + + @PostMapping(SAVE) + @Override + public AmisResponse save(@RequestBody SAVE_ITEM item) throws Exception { + return AmisResponse.responseSuccess(service.save(fromSaveItem(item))); + } + + @GetMapping(LIST) + @Override + public AmisResponse> list() throws Exception { + return AmisResponse.responseSuccess(service.list().collect(entity -> { + try { + return toListItem(entity); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + } + + @PostMapping(LIST) + @Override + public AmisResponse> list(@RequestBody Query query) throws Exception { + if (ObjectUtil.isNull(query)) { + return AmisResponse.responseSuccess(Lists.immutable.empty()); } + return AmisResponse.responseSuccess(service.list(query).collect(entity -> { + try { + return toListItem(entity); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + } - @PostMapping(SAVE) - @Override - public AmisResponse save(@RequestBody SAVE_ITEM item) throws Exception { - return AmisResponse.responseSuccess(service.save(fromSaveItem(item))); - } + @GetMapping(DETAIL) + @Override + public AmisResponse detail(@PathVariable Long id) throws Exception { + return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id))); + } - @GetMapping(LIST) - @Override - public AmisResponse> list() throws Exception { - return AmisResponse.responseSuccess(service.list().collect(entity -> { - try { - return toListItem(entity); - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } + @GetMapping(REMOVE) + @Override + public AmisResponse remove(@PathVariable Long id) { + service.remove(id); + return AmisResponse.responseSuccess(); + } - @PostMapping(LIST) - @Override - public AmisResponse> list(@RequestBody Query query) throws Exception { - if (ObjectUtil.isNull(query)) { - return AmisResponse.responseSuccess(Lists.immutable.empty()); - } - return AmisResponse.responseSuccess(service.list(query).collect(entity -> { - try { - return toListItem(entity); - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } + protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception; - @GetMapping(DETAIL) - @Override - public AmisResponse detail(@PathVariable Long id) throws Exception { - return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id))); - } + protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception; - @GetMapping(REMOVE) - @Override - public AmisResponse remove(@PathVariable Long id) { - service.remove(id); - return AmisResponse.responseSuccess(); - } - - protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception; - - protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception; - - protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception; + protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/query/Query.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/query/Query.java index 729326a..3f2de88 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/query/Query.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/controller/query/Query.java @@ -12,50 +12,50 @@ import org.eclipse.collections.api.map.ImmutableMap; */ @Data public class Query { - private Queryable query; - private ImmutableList sort; - private Pageable page; + private Queryable query; + private ImmutableList sort; + private Pageable page; + + @Data + public static class Queryable { + private ImmutableList nullEqual; + private ImmutableList notNullEqual; + private ImmutableList empty; + private ImmutableList notEmpty; + private ImmutableMap equal; + private ImmutableMap notEqual; + private ImmutableMap like; + private ImmutableMap notLike; + private ImmutableMap great; + private ImmutableMap less; + private ImmutableMap greatEqual; + private ImmutableMap lessEqual; + private ImmutableMap> in; + private ImmutableMap> notIn; + private ImmutableMap between; + private ImmutableMap notBetween; @Data - public static class Queryable { - private ImmutableList nullEqual; - private ImmutableList notNullEqual; - private ImmutableList empty; - private ImmutableList notEmpty; - private ImmutableMap equal; - private ImmutableMap notEqual; - private ImmutableMap like; - private ImmutableMap notLike; - private ImmutableMap great; - private ImmutableMap less; - private ImmutableMap greatEqual; - private ImmutableMap lessEqual; - private ImmutableMap> in; - private ImmutableMap> notIn; - private ImmutableMap between; - private ImmutableMap notBetween; - - @Data - public static class Between { - private String start; - private String end; - } + public static class Between { + private String start; + private String end; } + } - @Data - public static class Sortable { - private String column; - private Direction direction; + @Data + public static class Sortable { + private String column; + private Direction direction; - public enum Direction { - ASC, - DESC, - } + public enum Direction { + ASC, + DESC, } + } - @Data - public static class Pageable { - private Integer page; - private Integer size; - } + @Data + public static class Pageable { + private Integer page; + private Integer size; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/CheckingNeededEntity.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/CheckingNeededEntity.java index 3c4b0ff..f978ad5 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/CheckingNeededEntity.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/CheckingNeededEntity.java @@ -20,40 +20,40 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class CheckingNeededEntity extends LogicDeleteEntity { - private String description; + private String description; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private State state = State.DRAFT; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private State state = State.DRAFT; - @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY) - @ToString.Exclude - private CheckOrder order; + @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY) + @ToString.Exclude + private CheckOrder order; - public enum State { - /** - * 无确权 - */ - NONE, - /** - * 草稿 - */ - DRAFT, - /** - * 审查中 - */ - CHECKING, - /** - * 用户审核 - */ - OWNER_CHECKING, - /** - * 正常 - */ - NORMAL, - /** - * 驳回 - */ - REJECT, - } + public enum State { + /** + * 无确权 + */ + NONE, + /** + * 草稿 + */ + DRAFT, + /** + * 审查中 + */ + CHECKING, + /** + * 用户审核 + */ + OWNER_CHECKING, + /** + * 正常 + */ + NORMAL, + /** + * 驳回 + */ + REJECT, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/FileInfo.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/FileInfo.java index 1f48791..aa2c880 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/FileInfo.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/FileInfo.java @@ -17,35 +17,35 @@ import lombok.NoArgsConstructor; @AllArgsConstructor @JsonDeserialize(using = FileInfo.FileInfoDeserializer.class) public final class FileInfo { - private String id; - private String name; - private String filename; - private Long value; - private String state; + private String id; + private String name; + private String filename; + private Long value; + private String state; - public FileInfo(DataFile dataFile) { - this.id = dataFile.getId().toString(); - this.name = dataFile.getFilename(); - this.filename = dataFile.getFilename(); - this.value = dataFile.getId(); - this.state = "uploaded"; - } + public FileInfo(DataFile dataFile) { + this.id = dataFile.getId().toString(); + this.name = dataFile.getFilename(); + this.filename = dataFile.getFilename(); + this.value = dataFile.getId(); + this.state = "uploaded"; + } - public static final class FileInfoDeserializer extends JsonDeserializer { - @Override - public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException { - TreeNode root = parser.readValueAsTree(); - if (root instanceof ObjectNode) { - ObjectNode node = (ObjectNode) root; - return new FileInfo( - node.get("id").asText(), - node.get("name").asText(), - node.get("filename").asText(), - node.get("value").asLong(), - node.get("state").asText() - ); - } - return null; - } + public static final class FileInfoDeserializer extends JsonDeserializer { + @Override + public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException { + TreeNode root = parser.readValueAsTree(); + if (root instanceof ObjectNode) { + ObjectNode node = (ObjectNode) root; + return new FileInfo( + node.get("id").asText(), + node.get("name").asText(), + node.get("filename").asText(), + node.get("value").asLong(), + node.get("state").asText() + ); + } + return null; } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/IdOnlyEntity.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/IdOnlyEntity.java index 011e6e2..89eddc2 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/IdOnlyEntity.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/IdOnlyEntity.java @@ -22,24 +22,24 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class IdOnlyEntity { - @Id - @GeneratedValue(generator = "snowflake") - @GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator") - private Long id; + @Id + @GeneratedValue(generator = "snowflake") + @GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator") + private Long id; - @Override - public final boolean equals(Object object) { - if (this == object) - return true; - if (!(object instanceof IdOnlyEntity)) - return false; + @Override + public final boolean equals(Object object) { + if (this == object) + return true; + if (!(object instanceof IdOnlyEntity)) + return false; - IdOnlyEntity that = (IdOnlyEntity) object; - return id.equals(that.id); - } + IdOnlyEntity that = (IdOnlyEntity) object; + return id.equals(that.id); + } - @Override - public int hashCode() { - return id.hashCode(); - } + @Override + public int hashCode() { + return id.hashCode(); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteEntity.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteEntity.java index 2292100..4c83e34 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteEntity.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteEntity.java @@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class LogicDeleteEntity extends SimpleEntity { - public static final String LOGIC_DELETE_CLAUSE = "deleted = false"; + public static final String LOGIC_DELETE_CLAUSE = "deleted = false"; - @Column(nullable = false) - private Boolean deleted = false; + @Column(nullable = false) + private Boolean deleted = false; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteIdOnlyEntity.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteIdOnlyEntity.java index 0f43598..8fb29ea 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteIdOnlyEntity.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/LogicDeleteIdOnlyEntity.java @@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class LogicDeleteIdOnlyEntity extends IdOnlyEntity { - public static final String LOGIC_DELETE_CLAUSE = "deleted = false"; + public static final String LOGIC_DELETE_CLAUSE = "deleted = false"; - @Column(nullable = false) - private Boolean deleted = false; + @Column(nullable = false) + private Boolean deleted = false; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleDetailItem.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleDetailItem.java index 834282d..b3e341a 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleDetailItem.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleDetailItem.java @@ -10,5 +10,5 @@ import lombok.Data; */ @Data public abstract class SimpleDetailItem { - private Long id; + private Long id; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleEntity.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleEntity.java index 285a159..bc4d3b6 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleEntity.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleEntity.java @@ -30,18 +30,18 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public class SimpleEntity extends IdOnlyEntity { - @CreatedDate - private LocalDateTime createdTime; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - @CreatedBy - private User createdUser; - @LastModifiedDate - private LocalDateTime modifiedTime; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - @LastModifiedBy - private User modifiedUser; + @CreatedDate + private LocalDateTime createdTime; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + @CreatedBy + private User createdUser; + @LastModifiedDate + private LocalDateTime modifiedTime; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + @LastModifiedBy + private User modifiedUser; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleListItem.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleListItem.java index 17cfb51..128f543 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleListItem.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleListItem.java @@ -11,7 +11,7 @@ import lombok.Data; */ @Data public abstract class SimpleListItem { - private Long id; - private String createdUsername; - private LocalDateTime createdTime; + private Long id; + private String createdUsername; + private LocalDateTime createdTime; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleSaveItem.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleSaveItem.java index f9d2fb8..3cfb2a8 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleSaveItem.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/entity/SimpleSaveItem.java @@ -10,5 +10,5 @@ import lombok.Data; */ @Data public abstract class SimpleSaveItem { - private Long id; + private Long id; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/CheckingService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/CheckingService.java index 4385ea4..47449dc 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/CheckingService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/CheckingService.java @@ -10,5 +10,5 @@ import org.eclipse.collections.api.map.ImmutableMap; * @date 2024-11-28 */ public interface CheckingService { - void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters); + void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/LogicDeleteService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/LogicDeleteService.java index 39e855d..7e5d22e 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/LogicDeleteService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/LogicDeleteService.java @@ -21,24 +21,24 @@ import org.eclipse.collections.api.list.ImmutableList; */ @Slf4j public abstract class LogicDeleteService extends SimpleServiceSupport { - private final EntityManager manager; + private final EntityManager manager; - public LogicDeleteService(SimpleRepository repository, UserService userService, EntityManager manager) { - super(repository, userService); - this.manager = manager; - } + public LogicDeleteService(SimpleRepository repository, UserService userService, EntityManager manager) { + super(repository, userService); + this.manager = manager; + } - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false)); - } + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false)); + } - @Transactional(rollbackOn = Throwable.class) - @Override - public void remove(Long id) { - String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName(); - Query query = manager.createQuery(StrUtil.format("update {} entity set deleted=true where id=?1", entityName)); - query.setParameter(1, id); - query.executeUpdate(); - } + @Transactional(rollbackOn = Throwable.class) + @Override + public void remove(Long id) { + String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName(); + Query query = manager.createQuery(StrUtil.format("update {} entity set deleted=true where id=?1", entityName)); + query.setParameter(1, id); + query.executeUpdate(); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleService.java index 924239d..03e1851 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleService.java @@ -11,21 +11,21 @@ import org.eclipse.collections.api.set.ImmutableSet; * @date 2024-11-28 */ public interface SimpleService { - Long save(ENTITY entity) throws Exception; + Long save(ENTITY entity) throws Exception; - ImmutableList list() throws Exception; + ImmutableList list() throws Exception; - ImmutableList list(ImmutableSet ids) throws Exception; + ImmutableList list(ImmutableSet ids) throws Exception; - ImmutableList list(Query query) throws Exception; + ImmutableList list(Query query) throws Exception; - Optional detailOptional(Long id) throws Exception; + Optional detailOptional(Long id) throws Exception; - ENTITY detail(Long id) throws Exception; + ENTITY detail(Long id) throws Exception; - ENTITY detailOrThrow(Long id) throws Exception; + ENTITY detailOrThrow(Long id) throws Exception; - ENTITY detailOrNull(Long id) throws Exception; + ENTITY detailOrNull(Long id) throws Exception; - void remove(Long id) throws Exception; + void remove(Long id) throws Exception; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleServiceSupport.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleServiceSupport.java index c1df68a..a67b49a 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleServiceSupport.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/base/service/SimpleServiceSupport.java @@ -32,206 +32,206 @@ import org.springframework.data.domain.Sort; */ @Slf4j public abstract class SimpleServiceSupport implements SimpleService { - protected final SimpleRepository repository; - protected final UserService userService; + protected final SimpleRepository repository; + protected final UserService userService; - public SimpleServiceSupport(SimpleRepository repository, UserService userService) { - this.repository = repository; - this.userService = userService; + public SimpleServiceSupport(SimpleRepository repository, UserService userService) { + this.repository = repository; + this.userService = userService; + } + + @Transactional(rollbackOn = Throwable.class) + @Override + public Long save(ENTITY entity) { + if (ObjectUtil.isNotNull(entity.getId())) { + Long id = entity.getId(); + ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id)); + BeanUtil.copyProperties( + entity, + targetEntity, + CopyOptions.create() + .setIgnoreProperties( + IdOnlyEntity_.ID, + SimpleEntity_.CREATED_USER, + SimpleEntity_.CREATED_TIME, + SimpleEntity_.MODIFIED_USER, + SimpleEntity_.MODIFIED_TIME + ) + ); + entity = targetEntity; + } + entity = repository.save(entity); + return entity.getId(); + } + + @Override + public ImmutableList list() throws Exception { + return Lists.immutable.ofAll(repository.findAll( + (root, query, builder) -> + builder.and( + listPredicate(root, query, builder) + .reject(ObjectUtil::isNull) + .toArray(new Predicate[]{}) + ) + )); + } + + @Override + public ImmutableList list(ImmutableSet ids) throws Exception { + return Lists.immutable.ofAll(repository.findAll( + (root, query, builder) -> { + MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); + predicates.add(builder.in(root.get("id")).value(ids)); + return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); + } + )); + } + + private Path column(Root root, String column) { + String[] columns = StrUtil.splitToArray(column, "/"); + Path path = root.get(columns[0]); + for (int i = 1; i < columns.length; i++) { + path = path.get(columns[i]); + } + return path; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Object value(Path column, Object value) { + Class javaType = column.getJavaType(); + if (EnumUtil.isEnum(javaType)) { + return EnumUtil.fromString((Class) javaType, (String) value); + } + return value; + } + + @SuppressWarnings("unchecked") + private ImmutableList queryPredicates(Query.Queryable queryable, Root root, CriteriaQuery query, CriteriaBuilder builder) { + MutableList predicates = Lists.mutable.empty(); + if (ObjectUtil.isEmpty(queryable)) { + return predicates.toImmutable(); + } + if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) { + queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column)))); + } + if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) { + queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column)))); + } + if (ObjectUtil.isNotEmpty(queryable.getEmpty())) { + queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column)))); + } + if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) { + queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column)))); + } + if (ObjectUtil.isNotEmpty(queryable.getEqual())) { + queryable.getEqual().forEachKeyValue((column, value) -> { + Path path = column(root, column); + predicates.add(builder.equal(path, value(path, value))); + }); + } + if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) { + queryable.getEqual().forEachKeyValue((column, value) -> { + Path path = column(root, column); + predicates.add(builder.notEqual(path, value(path, value))); + }); + } + if (ObjectUtil.isNotEmpty(queryable.getLike())) { + queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value))); + } + if (ObjectUtil.isNotEmpty(queryable.getNotLike())) { + queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value))); + } + if (ObjectUtil.isNotEmpty(queryable.getGreat())) { + queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable) value))); + } + if (ObjectUtil.isNotEmpty(queryable.getLess())) { + queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable) value))); + } + if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) { + queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable) value))); + } + if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) { + queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable) value))); + } + if (ObjectUtil.isNotEmpty(queryable.getIn())) { + queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value))); + } + if (ObjectUtil.isNotEmpty(queryable.getNotIn())) { + queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not())); + } + if (ObjectUtil.isNotEmpty(queryable.getBetween())) { + queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd()))); + } + if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) { + queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd()))); + } + return predicates.toImmutable(); + } + + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User user = userService.currentLoginUser(); + if (User.isNotAdministrator(user)) { + return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user)); + } + return Lists.immutable.empty(); + } + + @Override + public ImmutableList list(Query listQuery) throws Exception { + return Lists.immutable.ofAll(repository.findAll( + (root, query, builder) -> { + MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); + predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder)); + return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); + }, + Sort.by(SimpleEntity_.CREATED_TIME).descending() + )); + } + + @Override + public Optional detailOptional(Long id) { + if (ObjectUtil.isNull(id)) { + return Optional.empty(); + } + return repository.findOne( + (root, query, builder) -> { + MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); + predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id)); + return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); + } + ); + } + + @Override + public ENTITY detail(Long id) { + return detailOrNull(id); + } + + @Override + public ENTITY detailOrThrow(Long id) { + return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id)); + } + + @Override + public ENTITY detailOrNull(Long id) { + return detailOptional(id).orElse(null); + } + + @Transactional(rollbackOn = Throwable.class) + @Override + public void remove(Long id) { + if (ObjectUtil.isNotNull(id)) { + repository.deleteById(id); + } + } + + public static final class IdNotFoundException extends RuntimeException { + public IdNotFoundException() { + super("资源不存在"); } - @Transactional(rollbackOn = Throwable.class) - @Override - public Long save(ENTITY entity) { - if (ObjectUtil.isNotNull(entity.getId())) { - Long id = entity.getId(); - ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id)); - BeanUtil.copyProperties( - entity, - targetEntity, - CopyOptions.create() - .setIgnoreProperties( - IdOnlyEntity_.ID, - SimpleEntity_.CREATED_USER, - SimpleEntity_.CREATED_TIME, - SimpleEntity_.MODIFIED_USER, - SimpleEntity_.MODIFIED_TIME - ) - ); - entity = targetEntity; - } - entity = repository.save(entity); - return entity.getId(); - } - - @Override - public ImmutableList list() throws Exception { - return Lists.immutable.ofAll(repository.findAll( - (root, query, builder) -> - builder.and( - listPredicate(root, query, builder) - .reject(ObjectUtil::isNull) - .toArray(new Predicate[]{}) - ) - )); - } - - @Override - public ImmutableList list(ImmutableSet ids) throws Exception { - return Lists.immutable.ofAll(repository.findAll( - (root, query, builder) -> { - MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); - predicates.add(builder.in(root.get("id")).value(ids)); - return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); - } - )); - } - - private Path column(Root root, String column) { - String[] columns = StrUtil.splitToArray(column, "/"); - Path path = root.get(columns[0]); - for (int i = 1; i < columns.length; i++) { - path = path.get(columns[i]); - } - return path; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private Object value(Path column, Object value) { - Class javaType = column.getJavaType(); - if (EnumUtil.isEnum(javaType)) { - return EnumUtil.fromString((Class) javaType, (String) value); - } - return value; - } - - @SuppressWarnings("unchecked") - private ImmutableList queryPredicates(Query.Queryable queryable, Root root, CriteriaQuery query, CriteriaBuilder builder) { - MutableList predicates = Lists.mutable.empty(); - if (ObjectUtil.isEmpty(queryable)) { - return predicates.toImmutable(); - } - if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) { - queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column)))); - } - if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) { - queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column)))); - } - if (ObjectUtil.isNotEmpty(queryable.getEmpty())) { - queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column)))); - } - if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) { - queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column)))); - } - if (ObjectUtil.isNotEmpty(queryable.getEqual())) { - queryable.getEqual().forEachKeyValue((column, value) -> { - Path path = column(root, column); - predicates.add(builder.equal(path, value(path, value))); - }); - } - if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) { - queryable.getEqual().forEachKeyValue((column, value) -> { - Path path = column(root, column); - predicates.add(builder.notEqual(path, value(path, value))); - }); - } - if (ObjectUtil.isNotEmpty(queryable.getLike())) { - queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value))); - } - if (ObjectUtil.isNotEmpty(queryable.getNotLike())) { - queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value))); - } - if (ObjectUtil.isNotEmpty(queryable.getGreat())) { - queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable) value))); - } - if (ObjectUtil.isNotEmpty(queryable.getLess())) { - queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable) value))); - } - if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) { - queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable) value))); - } - if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) { - queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable) value))); - } - if (ObjectUtil.isNotEmpty(queryable.getIn())) { - queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value))); - } - if (ObjectUtil.isNotEmpty(queryable.getNotIn())) { - queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not())); - } - if (ObjectUtil.isNotEmpty(queryable.getBetween())) { - queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd()))); - } - if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) { - queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd()))); - } - return predicates.toImmutable(); - } - - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User user = userService.currentLoginUser(); - if (User.isNotAdministrator(user)) { - return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user)); - } - return Lists.immutable.empty(); - } - - @Override - public ImmutableList list(Query listQuery) throws Exception { - return Lists.immutable.ofAll(repository.findAll( - (root, query, builder) -> { - MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); - predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder)); - return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); - }, - Sort.by(SimpleEntity_.CREATED_TIME).descending() - )); - } - - @Override - public Optional detailOptional(Long id) { - if (ObjectUtil.isNull(id)) { - return Optional.empty(); - } - return repository.findOne( - (root, query, builder) -> { - MutableList predicates = Lists.mutable.ofAll(listPredicate(root, query, builder)); - predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id)); - return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()])); - } - ); - } - - @Override - public ENTITY detail(Long id) { - return detailOrNull(id); - } - - @Override - public ENTITY detailOrThrow(Long id) { - return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id)); - } - - @Override - public ENTITY detailOrNull(Long id) { - return detailOptional(id).orElse(null); - } - - @Transactional(rollbackOn = Throwable.class) - @Override - public void remove(Long id) { - if (ObjectUtil.isNotNull(id)) { - repository.deleteById(id); - } - } - - public static final class IdNotFoundException extends RuntimeException { - public IdNotFoundException() { - super("资源不存在"); - } - - public IdNotFoundException(Long id) { - super(StrUtil.format("ID为{}的资源不存在", id)); - } + public IdNotFoundException(Long id) { + super(StrUtil.format("ID为{}的资源不存在", id)); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/AuthenticationController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/AuthenticationController.java index 110bb89..a934829 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/AuthenticationController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/AuthenticationController.java @@ -30,101 +30,101 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("authentication") public class AuthenticationController extends SimpleControllerSupport { - private final AuthenticationService authenticationService; - private final DataResourceService dataResourceService; - private final DataFileService dataFileService; + private final AuthenticationService authenticationService; + private final DataResourceService dataResourceService; + private final DataFileService dataFileService; - public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) { - super(service); - this.authenticationService = service; - this.dataResourceService = dataResourceService; - this.dataFileService = dataFileService; + public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) { + super(service); + this.authenticationService = service; + this.dataResourceService = dataResourceService; + this.dataFileService = dataFileService; + } + + @GetMapping("/submit/{id}") + public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { + authenticationService.submit(id); + return AmisResponse.responseSuccess(); + } + + @GetMapping("/retract/{id}") + public AmisResponse retract(@PathVariable Long id) { + authenticationService.retract(id); + return AmisResponse.responseSuccess(); + } + + @Override + protected Authentication fromSaveItem(SaveItem item) throws Exception { + Authentication authentication = new Authentication(); + authentication.setId(item.getId()); + authentication.setDescription(item.getDescription()); + authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId())); + authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet()); + authentication.setActiveTime(item.getActiveTime()); + authentication.setExpiredTime(item.getExpiredTime()); + return authentication; + } + + @Override + protected ListItem toListItem(Authentication entity) { + return new ListItem(entity); + } + + @Override + protected DetailItem toDetailItem(Authentication entity) { + return new DetailItem(entity); + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class SaveItem extends SimpleSaveItem { + private Long targetId; + private String description; + private ImmutableSet evidenceFiles; + private LocalDateTime activeTime; + private LocalDateTime expiredTime; + } + + @Data + @NoArgsConstructor + @EqualsAndHashCode(callSuper = true) + public static final class ListItem extends SimpleListItem { + private String name; + private String description; + private String state; + + public ListItem(Authentication authentication) { + this.setId(authentication.getId()); + this.setName(authentication.getTarget().getName()); + this.setDescription(authentication.getDescription()); + this.setState(authentication.getState().name()); + this.setCreatedUsername(authentication.getCreatedUser().getUsername()); + this.setCreatedTime(authentication.getCreatedTime()); } + } - @GetMapping("/submit/{id}") - public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { - authenticationService.submit(id); - return AmisResponse.responseSuccess(); - } - - @GetMapping("/retract/{id}") - public AmisResponse retract(@PathVariable Long id) { - authenticationService.retract(id); - return AmisResponse.responseSuccess(); - } - - @Override - protected Authentication fromSaveItem(SaveItem item) throws Exception { - Authentication authentication = new Authentication(); - authentication.setId(item.getId()); - authentication.setDescription(item.getDescription()); - authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId())); - authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet()); - authentication.setActiveTime(item.getActiveTime()); - authentication.setExpiredTime(item.getExpiredTime()); - return authentication; - } - - @Override - protected ListItem toListItem(Authentication entity) { - return new ListItem(entity); - } - - @Override - protected DetailItem toDetailItem(Authentication entity) { - return new DetailItem(entity); - } - - @Data - @EqualsAndHashCode(callSuper = true) - public static class SaveItem extends SimpleSaveItem { - private Long targetId; - private String description; - private ImmutableSet evidenceFiles; - private LocalDateTime activeTime; - private LocalDateTime expiredTime; - } - - @Data - @NoArgsConstructor - @EqualsAndHashCode(callSuper = true) - public static final class ListItem extends SimpleListItem { - private String name; - private String description; - private String state; - - public ListItem(Authentication authentication) { - this.setId(authentication.getId()); - this.setName(authentication.getTarget().getName()); - this.setDescription(authentication.getDescription()); - this.setState(authentication.getState().name()); - this.setCreatedUsername(authentication.getCreatedUser().getUsername()); - this.setCreatedTime(authentication.getCreatedTime()); - } - } - - @Data - @NoArgsConstructor - @EqualsAndHashCode(callSuper = true) - public static final class DetailItem extends SaveItem { - private String targetName; - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - - public DetailItem(Authentication authentication) { - this.setId(authentication.getId()); - this.setTargetId(authentication.getTarget().getId()); - this.setTargetName(authentication.getTarget().getName()); - this.setDescription(authentication.getDescription()); - this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new)); - this.setActiveTime(authentication.getActiveTime()); - this.setExpiredTime(authentication.getExpiredTime()); - this.setCreatedTime(authentication.getCreatedTime()); - this.setCreatedUsername(authentication.getCreatedUser().getUsername()); - this.setModifiedTime(authentication.getModifiedTime()); - this.setModifiedUsername(authentication.getModifiedUser().getUsername()); - } + @Data + @NoArgsConstructor + @EqualsAndHashCode(callSuper = true) + public static final class DetailItem extends SaveItem { + private String targetName; + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + + public DetailItem(Authentication authentication) { + this.setId(authentication.getId()); + this.setTargetId(authentication.getTarget().getId()); + this.setTargetName(authentication.getTarget().getName()); + this.setDescription(authentication.getDescription()); + this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new)); + this.setActiveTime(authentication.getActiveTime()); + this.setExpiredTime(authentication.getExpiredTime()); + this.setCreatedTime(authentication.getCreatedTime()); + this.setCreatedUsername(authentication.getCreatedUser().getUsername()); + this.setModifiedTime(authentication.getModifiedTime()); + this.setModifiedUsername(authentication.getModifiedUser().getUsername()); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/CheckOrderController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/CheckOrderController.java index 9b224a3..24dab6f 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/CheckOrderController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/CheckOrderController.java @@ -32,58 +32,58 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("check_order") public class CheckOrderController implements ListController { - private final CheckOrderService checkOrderService; - private final ObjectMapper mapper; + private final CheckOrderService checkOrderService; + private final ObjectMapper mapper; - public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { - this.checkOrderService = checkOrderService; - this.mapper = builder.build(); - } + public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { + this.checkOrderService = checkOrderService; + this.mapper = builder.build(); + } - @GetMapping("/list") - @Override - public AmisResponse> list() throws Exception { - return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); - } + @GetMapping("/list") + @Override + public AmisResponse> list() throws Exception { + return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); + } - @PostMapping("/list") - @Override - public AmisResponse> list(@RequestBody Query query) throws Exception { - return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); - } + @PostMapping("/list") + @Override + public AmisResponse> list(@RequestBody Query query) throws Exception { + return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem)); + } - @SneakyThrows - private ListItem toListItem(CheckOrder order) { - ListItem item = new ListItem(); - item.setCheckOrderId(order.getId()); - item.setDescription(order.getDescription()); - item.setType(order.getType()); - item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {})); - item.setState(order.getState()); - item.setCreatedUsername(order.getCreatedUser().getUsername()); - item.setCreatedTime(order.getCreatedTime()); - item.setModifiedUsername(order.getModifiedUser().getUsername()); - item.setModifiedTime(order.getModifiedTime()); - return item; - } + @SneakyThrows + private ListItem toListItem(CheckOrder order) { + ListItem item = new ListItem(); + item.setCheckOrderId(order.getId()); + item.setDescription(order.getDescription()); + item.setType(order.getType()); + item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {})); + item.setState(order.getState()); + item.setCreatedUsername(order.getCreatedUser().getUsername()); + item.setCreatedTime(order.getCreatedTime()); + item.setModifiedUsername(order.getModifiedUser().getUsername()); + item.setModifiedTime(order.getModifiedTime()); + return item; + } - @GetMapping("/operation/{id}/{operation}") - public AmisResponse operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException { - log.info("id:{}, operation:{}", id, operation); - checkOrderService.operation(id, operation); - return AmisResponse.responseSuccess(); - } + @GetMapping("/operation/{id}/{operation}") + public AmisResponse operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException { + log.info("id:{}, operation:{}", id, operation); + checkOrderService.operation(id, operation); + return AmisResponse.responseSuccess(); + } - @Data - public static final class ListItem { - private Long checkOrderId; - private String description; - private CheckOrder.Type type; - private ImmutableMap parameters; - private CheckOrder.State state; - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - } + @Data + public static final class ListItem { + private Long checkOrderId; + private String description; + private CheckOrder.Type type; + private ImmutableMap parameters; + private CheckOrder.State state; + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/ConfirmationController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/ConfirmationController.java index 0333603..eae6ea0 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/ConfirmationController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/ConfirmationController.java @@ -29,93 +29,93 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("confirmation") public class ConfirmationController extends SimpleControllerSupport { - private final ConfirmationService confirmationService; - private final DataResourceService dataResourceService; - private final DataFileService dataFileService; + private final ConfirmationService confirmationService; + private final DataResourceService dataResourceService; + private final DataFileService dataFileService; - public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) { - super(service); - this.confirmationService = confirmationService; - this.dataResourceService = dataResourceService; - this.dataFileService = dataFileService; + public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) { + super(service); + this.confirmationService = confirmationService; + this.dataResourceService = dataResourceService; + this.dataFileService = dataFileService; + } + + @GetMapping("/submit/{id}") + public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { + confirmationService.submit(id); + return AmisResponse.responseSuccess(); + } + + @GetMapping("/retract/{id}") + public AmisResponse retract(@PathVariable Long id) { + confirmationService.retract(id); + return AmisResponse.responseSuccess(); + } + + @Override + protected Confirmation fromSaveItem(SaveItem item) throws Exception { + Confirmation confirmation = new Confirmation(); + confirmation.setId(item.getId()); + confirmation.setDescription(item.getDescription()); + confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId())); + confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet()); + return confirmation; + } + + @Override + protected ListItem toListItem(Confirmation entity) { + return new ListItem(entity); + } + + @Override + protected DetailItem toDetailItem(Confirmation entity) { + return new DetailItem(entity); + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static class SaveItem extends SimpleSaveItem { + private Long targetId; + private String description; + private ImmutableSet evidenceFiles; + } + + @Data + @EqualsAndHashCode(callSuper = true) + public static final class ListItem extends SimpleListItem { + private String name; + private String description; + private String state; + + public ListItem(Confirmation confirmation) { + this.setId(confirmation.getId()); + this.setName(confirmation.getTarget().getName()); + this.setDescription(confirmation.getDescription()); + this.setState(confirmation.getState().name()); + this.setCreatedUsername(confirmation.getCreatedUser().getUsername()); + this.setCreatedTime(confirmation.getCreatedTime()); } + } - @GetMapping("/submit/{id}") - public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { - confirmationService.submit(id); - return AmisResponse.responseSuccess(); - } - - @GetMapping("/retract/{id}") - public AmisResponse retract(@PathVariable Long id) { - confirmationService.retract(id); - return AmisResponse.responseSuccess(); - } - - @Override - protected Confirmation fromSaveItem(SaveItem item) throws Exception { - Confirmation confirmation = new Confirmation(); - confirmation.setId(item.getId()); - confirmation.setDescription(item.getDescription()); - confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId())); - confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet()); - return confirmation; - } - - @Override - protected ListItem toListItem(Confirmation entity) { - return new ListItem(entity); - } - - @Override - protected DetailItem toDetailItem(Confirmation entity) { - return new DetailItem(entity); - } - - @Data - @EqualsAndHashCode(callSuper = true) - public static class SaveItem extends SimpleSaveItem { - private Long targetId; - private String description; - private ImmutableSet evidenceFiles; - } - - @Data - @EqualsAndHashCode(callSuper = true) - public static final class ListItem extends SimpleListItem { - private String name; - private String description; - private String state; - - public ListItem(Confirmation confirmation) { - this.setId(confirmation.getId()); - this.setName(confirmation.getTarget().getName()); - this.setDescription(confirmation.getDescription()); - this.setState(confirmation.getState().name()); - this.setCreatedUsername(confirmation.getCreatedUser().getUsername()); - this.setCreatedTime(confirmation.getCreatedTime()); - } - } - - @Data - @EqualsAndHashCode(callSuper = true) - public static final class DetailItem extends SaveItem { - private String targetName; - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - - public DetailItem(Confirmation confirmation) { - this.setId(confirmation.getId()); - this.setTargetId(confirmation.getTarget().getId()); - this.setTargetName(confirmation.getTarget().getName()); - this.setDescription(confirmation.getDescription()); - this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new)); - this.setCreatedTime(confirmation.getCreatedTime()); - this.setCreatedUsername(confirmation.getCreatedUser().getUsername()); - this.setModifiedTime(confirmation.getModifiedTime()); - this.setModifiedUsername(confirmation.getModifiedUser().getUsername()); - } + @Data + @EqualsAndHashCode(callSuper = true) + public static final class DetailItem extends SaveItem { + private String targetName; + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + + public DetailItem(Confirmation confirmation) { + this.setId(confirmation.getId()); + this.setTargetId(confirmation.getTarget().getId()); + this.setTargetName(confirmation.getTarget().getName()); + this.setDescription(confirmation.getDescription()); + this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new)); + this.setCreatedTime(confirmation.getCreatedTime()); + this.setCreatedUsername(confirmation.getCreatedUser().getUsername()); + this.setModifiedTime(confirmation.getModifiedTime()); + this.setModifiedUsername(confirmation.getModifiedUser().getUsername()); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataFileController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataFileController.java index c406259..3b4ce67 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataFileController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataFileController.java @@ -41,179 +41,179 @@ import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping("/upload") public class DataFileController { - private final HostConfiguration hostConfiguration; - private final DataFileService dataFileService; - private final String uploadFolderPath; - private final String cacheFolderPath; - private final String sliceFolderPath; + private final HostConfiguration hostConfiguration; + private final DataFileService dataFileService; + private final String uploadFolderPath; + private final String cacheFolderPath; + private final String sliceFolderPath; - public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) { - this.hostConfiguration = hostConfiguration; - this.dataFileService = dataFileService; + public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) { + this.hostConfiguration = hostConfiguration; + this.dataFileService = dataFileService; - this.uploadFolderPath = uploadConfiguration.getUploadPath(); - this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath); - this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath); + this.uploadFolderPath = uploadConfiguration.getUploadPath(); + this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath); + this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath); + } + + @PostMapping("") + public AmisResponse upload(@RequestParam("file") MultipartFile file) throws IOException { + String filename = file.getOriginalFilename(); + Long id = dataFileService.initialDataFile(filename); + String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id); + byte[] bytes = file.getBytes(); + String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes)); + File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5)); + if (targetFile.exists()) { + dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType()); + return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url)); } - - @PostMapping("") - public AmisResponse upload(@RequestParam("file") MultipartFile file) throws IOException { - String filename = file.getOriginalFilename(); - Long id = dataFileService.initialDataFile(filename); - String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id); - byte[] bytes = file.getBytes(); - String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes)); - File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5)); - if (targetFile.exists()) { - dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType()); - return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url)); - } - File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id)); - cacheFile = FileUtil.writeBytes(bytes, cacheFile); - String targetMd5 = SecureUtil.md5(cacheFile); - if (!StrUtil.equals(originMd5, targetMd5)) { - throw new RuntimeException("文件上传失败,校验不匹配"); - } - FileUtil.move(cacheFile, targetFile, true); - dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType()); - return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url)); + File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id)); + cacheFile = FileUtil.writeBytes(bytes, cacheFile); + String targetMd5 = SecureUtil.md5(cacheFile); + if (!StrUtil.equals(originMd5, targetMd5)) { + throw new RuntimeException("文件上传失败,校验不匹配"); } + FileUtil.move(cacheFile, targetFile, true); + dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType()); + return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url)); + } - @GetMapping("/download/{id}") - public void download(@PathVariable Long id, HttpServletResponse response) throws IOException { - DataFile dataFile = dataFileService.downloadFile(id); - File targetFile = new File(dataFile.getPath()); - response.setHeader("Access-Control-Expose-Headers", "Content-Type"); - response.setHeader("Content-Type", dataFile.getType()); - response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); - response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename())); - IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream()); + @GetMapping("/download/{id}") + public void download(@PathVariable Long id, HttpServletResponse response) throws IOException { + DataFile dataFile = dataFileService.downloadFile(id); + File targetFile = new File(dataFile.getPath()); + response.setHeader("Access-Control-Expose-Headers", "Content-Type"); + response.setHeader("Content-Type", dataFile.getType()); + response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); + response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename())); + IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream()); + } + + @PostMapping("/start") + public AmisResponse start(@RequestBody StartRequest request) { + log.info("Request: {}", request); + Long id = dataFileService.initialDataFile(request.filename); + return AmisResponse.responseSuccess(new StartResponse(id.toString())); + } + + @PostMapping("/slice") + public AmisResponse slice( + @RequestParam("uploadId") + Long uploadId, + @RequestParam("partNumber") + Integer sequence, + @RequestParam("partSize") + Long size, + @RequestParam("file") + MultipartFile file + ) throws IOException { + byte[] bytes = file.getBytes(); + String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes)); + String targetFilename = StrUtil.format("{}-{}", sequence, md5); + String targetFilePath = sliceFilePath(uploadId, targetFilename); + FileUtil.mkParentDirs(targetFilePath); + FileUtil.writeBytes(bytes, targetFilePath); + return AmisResponse.responseSuccess(new SliceResponse(targetFilename)); + } + + private String sliceFilePath(Long uploadId, String sliceFilename) { + return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename); + } + + @PostMapping("finish") + public AmisResponse finish(@RequestBody FinishRequest request) { + if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) { + throw new RuntimeException("文件校验失败,请重新上传"); } - - @PostMapping("/start") - public AmisResponse start(@RequestBody StartRequest request) { - log.info("Request: {}", request); - Long id = dataFileService.initialDataFile(request.filename); - return AmisResponse.responseSuccess(new StartResponse(id.toString())); - } - - @PostMapping("/slice") - public AmisResponse slice( - @RequestParam("uploadId") - Long uploadId, - @RequestParam("partNumber") - Integer sequence, - @RequestParam("partSize") - Long size, - @RequestParam("file") - MultipartFile file - ) throws IOException { - byte[] bytes = file.getBytes(); - String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes)); - String targetFilename = StrUtil.format("{}-{}", sequence, md5); - String targetFilePath = sliceFilePath(uploadId, targetFilename); - FileUtil.mkParentDirs(targetFilePath); - FileUtil.writeBytes(bytes, targetFilePath); - return AmisResponse.responseSuccess(new SliceResponse(targetFilename)); - } - - private String sliceFilePath(Long uploadId, String sliceFilename) { - return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename); - } - - @PostMapping("finish") - public AmisResponse finish(@RequestBody FinishRequest request) { - if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) { - throw new RuntimeException("文件校验失败,请重新上传"); - } - try { - File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId)); - FileUtil.mkParentDirs(cacheFile); - if (cacheFile.createNewFile()) { - try (FileOutputStream fos = new FileOutputStream(cacheFile)) { - try (FileChannel fosChannel = fos.getChannel()) { - for (FinishRequest.Part part : request.partList) { - File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag)); - try (FileInputStream fis = new FileInputStream(sliceFile)) { - try (FileChannel fisChannel = fis.getChannel()) { - fisChannel.transferTo(0, fisChannel.size(), fosChannel); - } - } - } - } + try { + File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId)); + FileUtil.mkParentDirs(cacheFile); + if (cacheFile.createNewFile()) { + try (FileOutputStream fos = new FileOutputStream(cacheFile)) { + try (FileChannel fosChannel = fos.getChannel()) { + for (FinishRequest.Part part : request.partList) { + File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag)); + try (FileInputStream fis = new FileInputStream(sliceFile)) { + try (FileChannel fisChannel = fis.getChannel()) { + fisChannel.transferTo(0, fisChannel.size(), fosChannel); } - String md5 = SecureUtil.md5(cacheFile); - File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5)); - if (!targetFile.exists()) { - FileUtil.move(cacheFile, targetFile, true); - } - String absolutePath = FileUtil.getAbsolutePath(targetFile); - dataFileService.updateDataFile( - request.uploadId, - absolutePath, - FileUtil.size(targetFile), - SecureUtil.md5(targetFile), - FileUtil.getMimeType(absolutePath) - ); - return AmisResponse.responseSuccess(new FinishResponse( - request.uploadId, - request.filename, - request.uploadId.toString(), - StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId) - )); - } else { - throw new RuntimeException("合并文件失败"); + } } - } catch (Throwable throwable) { - throw new RuntimeException(throwable); - } finally { - FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId)); - FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId)); + } } - } - - @Data - public static final class StartRequest { - private String name; - private String filename; - } - - @Data - @NoArgsConstructor - @AllArgsConstructor - public static final class StartResponse { - private String uploadId; - } - - @Data - @NoArgsConstructor - @AllArgsConstructor - public static final class SliceResponse { - @JsonProperty("eTag") - private String eTag; - } - - @Data - public static final class FinishRequest { - private String filename; - private Long uploadId; - private ImmutableList partList; - - @Data - public static final class Part { - private Integer partNumber; - @JsonProperty("eTag") - private String eTag; + String md5 = SecureUtil.md5(cacheFile); + File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5)); + if (!targetFile.exists()) { + FileUtil.move(cacheFile, targetFile, true); } + String absolutePath = FileUtil.getAbsolutePath(targetFile); + dataFileService.updateDataFile( + request.uploadId, + absolutePath, + FileUtil.size(targetFile), + SecureUtil.md5(targetFile), + FileUtil.getMimeType(absolutePath) + ); + return AmisResponse.responseSuccess(new FinishResponse( + request.uploadId, + request.filename, + request.uploadId.toString(), + StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId) + )); + } else { + throw new RuntimeException("合并文件失败"); + } + } catch (Throwable throwable) { + throw new RuntimeException(throwable); + } finally { + FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId)); + FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId)); } + } + + @Data + public static final class StartRequest { + private String name; + private String filename; + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static final class StartResponse { + private String uploadId; + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static final class SliceResponse { + @JsonProperty("eTag") + private String eTag; + } + + @Data + public static final class FinishRequest { + private String filename; + private Long uploadId; + private ImmutableList partList; @Data - @NoArgsConstructor - @AllArgsConstructor - public static final class FinishResponse { - private Long id; - private String filename; - private String value; - private String url; + public static final class Part { + private Integer partNumber; + @JsonProperty("eTag") + private String eTag; } + } + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static final class FinishResponse { + private Long id; + private String filename; + private String value; + private String url; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataResourceController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataResourceController.java index 2ce8df8..6f1969e 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataResourceController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/DataResourceController.java @@ -47,262 +47,262 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/data_resource") public class DataResourceController extends SimpleControllerSupport { - private final ObjectMapper mapper; - private final DataResourceService dataResourceService; - private final DataFileService dataFileService; + private final ObjectMapper mapper; + private final DataResourceService dataResourceService; + private final DataFileService dataFileService; - public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) { - super(dataResourceService); - this.dataResourceService = dataResourceService; - this.dataFileService = dataFileService; - this.mapper = builder.build(); - } + public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) { + super(dataResourceService); + this.dataResourceService = dataResourceService; + this.dataFileService = dataFileService; + this.mapper = builder.build(); + } - @GetMapping(LIST + "_no_confirmation") - public AmisResponse> listNoConfirmation() { - return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> { - try { - return toListItem(entity); - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } + @GetMapping(LIST + "_no_confirmation") + public AmisResponse> listNoConfirmation() { + return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> { + try { + return toListItem(entity); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + } - @GetMapping(LIST + "_no_authentication") - public AmisResponse> listNoAuthentication() { - return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> { - try { - return toListItem(entity); - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } + @GetMapping(LIST + "_no_authentication") + public AmisResponse> listNoAuthentication() { + return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> { + try { + return toListItem(entity); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + } - @GetMapping(LIST + "_no_ware") - public AmisResponse> listNoWare() { - return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> { - try { - return toListItem(entity); - } catch (Exception e) { - throw new RuntimeException(e); - } - })); - } + @GetMapping(LIST + "_no_ware") + public AmisResponse> listNoWare() { + return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> { + try { + return toListItem(entity); + } catch (Exception e) { + throw new RuntimeException(e); + } + })); + } - @Override - protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException { - ResourceType type = generateResourceType(item); - ResourceFormat format = generateResourceFormat(item); - DataResource dataResource = new DataResource(); - dataResource.setId(item.getId()); - dataResource.setName(item.getName()); - dataResource.setDescription(item.getDescription()); - dataResource.setType(type); - dataResource.setFormat(format); - if (ObjectUtil.isNotNull(item.getExampleFile())) { - dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue())); - } - return dataResource; + @Override + protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException { + ResourceType type = generateResourceType(item); + ResourceFormat format = generateResourceFormat(item); + DataResource dataResource = new DataResource(); + dataResource.setId(item.getId()); + dataResource.setName(item.getName()); + dataResource.setDescription(item.getDescription()); + dataResource.setType(type); + dataResource.setFormat(format); + if (ObjectUtil.isNotNull(item.getExampleFile())) { + dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue())); } + return dataResource; + } - @Override - protected ListItem toListItem(DataResource dataResource) { - ListItem item = new ListItem(); - item.setId(dataResource.getId()); - item.setName(dataResource.getName()); - item.setDescription(dataResource.getDescription()); - item.setType(dataResource.getType().getResourceType().name()); - item.setFormat(dataResource.getFormat().getFormatType().name()); - if (ObjectUtil.isNotNull(dataResource.getConfirmation())) { - item.setConfirmationId(dataResource.getConfirmation().getId()); - item.setConfirmationState(dataResource.getConfirmation().getState()); - } else { - item.setConfirmationState(Confirmation.State.NONE); - } - item.setCreatedUser(dataResource.getCreatedUser().getUsername()); - item.setCreatedTime(dataResource.getCreatedTime()); - return item; + @Override + protected ListItem toListItem(DataResource dataResource) { + ListItem item = new ListItem(); + item.setId(dataResource.getId()); + item.setName(dataResource.getName()); + item.setDescription(dataResource.getDescription()); + item.setType(dataResource.getType().getResourceType().name()); + item.setFormat(dataResource.getFormat().getFormatType().name()); + if (ObjectUtil.isNotNull(dataResource.getConfirmation())) { + item.setConfirmationId(dataResource.getConfirmation().getId()); + item.setConfirmationState(dataResource.getConfirmation().getState()); + } else { + item.setConfirmationState(Confirmation.State.NONE); } + item.setCreatedUser(dataResource.getCreatedUser().getUsername()); + item.setCreatedTime(dataResource.getCreatedTime()); + return item; + } - @Override - protected DetailItem toDetailItem(DataResource dataResource) throws Exception { - DetailItem item = new DetailItem(); - item.setId(dataResource.getId()); - item.setResourceTypeId(dataResource.getType().getId()); - item.setResourceFormatId(dataResource.getFormat().getId()); - item.setName(dataResource.getName()); - item.setDescription(dataResource.getDescription()); - item.setResourceType(dataResource.getType().getResourceType()); - switch (dataResource.getType().getResourceType()) { - case API: - ApiResourceType apiType = (ApiResourceType) dataResource.getType(); - item.setApiUrl(apiType.getUrl()); - item.setApiUsername(apiType.getUsername()); - item.setApiPassword(apiType.getPassword()); - break; - case FILE: - FileResourceType fileType = (FileResourceType) dataResource.getType(); - item.setFile(new FileInfo(fileType.getFile())); - break; - case DATABASE: - DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType(); - item.setDatabaseType(databaseType.getDatabaseType().name()); - item.setDatabaseJdbc(databaseType.getJdbc()); - item.setDatabaseUsername(databaseType.getUsername()); - item.setDatabasePassword(databaseType.getPassword()); - break; - case HDFS: - HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType(); - item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite())); - item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite())); - break; - case FTP: - FtpResourceType ftpType = (FtpResourceType) dataResource.getType(); - item.setFtpUrl(ftpType.getUrl()); - item.setFtpUsername(ftpType.getUsername()); - item.setFtpPassword(ftpType.getPassword()); - item.setFtpPath(ftpType.getPath()); - item.setFtpRegexFilter(ftpType.getRegexFilter()); - break; - } - item.setFormatType(dataResource.getFormat().getFormatType()); - switch (dataResource.getFormat().getFormatType()) { - case NONE: - case LINE: - break; - case JSON: - JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat(); - item.setJsonSchemaText(jsonFormat.getSchema()); - item.setJsonSchema(mapper.readValue(jsonFormat.getSchema(), Map.class)); - break; - case JSON_LINE: - JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat(); - item.setJsonLineSchemaText(jsonLineFormat.getSchema()); - item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getSchema(), Map.class)); - break; - case CSV: - CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat(); - item.setCsvSchemaText(csvFormat.getSchema()); - item.setCsvSchema(mapper.readValue(csvFormat.getSchema(), Map.class)); - break; - } - if (ObjectUtil.isNotNull(dataResource.getExample())) { - item.setExampleFile(new FileInfo(dataResource.getExample())); - } - item.setCreatedUsername(dataResource.getCreatedUser().getUsername()); - item.setCreatedTime(dataResource.getCreatedTime()); - item.setModifiedUsername(dataResource.getModifiedUser().getUsername()); - item.setModifiedTime(dataResource.getModifiedTime()); - return item; + @Override + protected DetailItem toDetailItem(DataResource dataResource) throws Exception { + DetailItem item = new DetailItem(); + item.setId(dataResource.getId()); + item.setResourceTypeId(dataResource.getType().getId()); + item.setResourceFormatId(dataResource.getFormat().getId()); + item.setName(dataResource.getName()); + item.setDescription(dataResource.getDescription()); + item.setResourceType(dataResource.getType().getResourceType()); + switch (dataResource.getType().getResourceType()) { + case API: + ApiResourceType apiType = (ApiResourceType) dataResource.getType(); + item.setApiUrl(apiType.getUrl()); + item.setApiUsername(apiType.getUsername()); + item.setApiPassword(apiType.getPassword()); + break; + case FILE: + FileResourceType fileType = (FileResourceType) dataResource.getType(); + item.setFile(new FileInfo(fileType.getFile())); + break; + case DATABASE: + DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType(); + item.setDatabaseType(databaseType.getDatabaseType().name()); + item.setDatabaseJdbc(databaseType.getJdbc()); + item.setDatabaseUsername(databaseType.getUsername()); + item.setDatabasePassword(databaseType.getPassword()); + break; + case HDFS: + HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType(); + item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite())); + item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite())); + break; + case FTP: + FtpResourceType ftpType = (FtpResourceType) dataResource.getType(); + item.setFtpUrl(ftpType.getUrl()); + item.setFtpUsername(ftpType.getUsername()); + item.setFtpPassword(ftpType.getPassword()); + item.setFtpPath(ftpType.getPath()); + item.setFtpRegexFilter(ftpType.getRegexFilter()); + break; } + item.setFormatType(dataResource.getFormat().getFormatType()); + switch (dataResource.getFormat().getFormatType()) { + case NONE: + case LINE: + break; + case JSON: + JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat(); + item.setJsonSchemaText(jsonFormat.getSchema()); + item.setJsonSchema(mapper.readValue(jsonFormat.getSchema(), Map.class)); + break; + case JSON_LINE: + JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat(); + item.setJsonLineSchemaText(jsonLineFormat.getSchema()); + item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getSchema(), Map.class)); + break; + case CSV: + CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat(); + item.setCsvSchemaText(csvFormat.getSchema()); + item.setCsvSchema(mapper.readValue(csvFormat.getSchema(), Map.class)); + break; + } + if (ObjectUtil.isNotNull(dataResource.getExample())) { + item.setExampleFile(new FileInfo(dataResource.getExample())); + } + item.setCreatedUsername(dataResource.getCreatedUser().getUsername()); + item.setCreatedTime(dataResource.getCreatedTime()); + item.setModifiedUsername(dataResource.getModifiedUser().getUsername()); + item.setModifiedTime(dataResource.getModifiedTime()); + return item; + } - private ResourceType generateResourceType(SaveItem item) { - ResourceType type = null; - switch (item.getResourceType()) { - case API: - type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword()); - break; - case FILE: - DataFile dataFile = dataFileService.detail(item.getFile().getValue()); - type = new FileResourceType(dataFile); - break; - case DATABASE: - type = new DatabaseResourceType( - item.getDatabaseJdbc(), - item.getDatabaseUsername(), - item.getDatabasePassword(), - EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType()) - ); - break; - case HDFS: - type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue())); - break; - case FTP: - type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter()); - break; - } - type.setId(item.getResourceTypeId()); - return type; + private ResourceType generateResourceType(SaveItem item) { + ResourceType type = null; + switch (item.getResourceType()) { + case API: + type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword()); + break; + case FILE: + DataFile dataFile = dataFileService.detail(item.getFile().getValue()); + type = new FileResourceType(dataFile); + break; + case DATABASE: + type = new DatabaseResourceType( + item.getDatabaseJdbc(), + item.getDatabaseUsername(), + item.getDatabasePassword(), + EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType()) + ); + break; + case HDFS: + type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue())); + break; + case FTP: + type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter()); + break; } + type.setId(item.getResourceTypeId()); + return type; + } - private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException { - ResourceFormat format = null; - switch (item.getFormatType()) { - case NONE: - format = new NoneResourceFormat(); - break; - case LINE: - format = new LineResourceFormat(); - break; - case JSON: - format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema())); - break; - case JSON_LINE: - format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema())); - break; - case CSV: - format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema())); - break; - } - format.setId(item.getResourceFormatId()); - return format; + private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException { + ResourceFormat format = null; + switch (item.getFormatType()) { + case NONE: + format = new NoneResourceFormat(); + break; + case LINE: + format = new LineResourceFormat(); + break; + case JSON: + format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema())); + break; + case JSON_LINE: + format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema())); + break; + case CSV: + format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema())); + break; } + format.setId(item.getResourceFormatId()); + return format; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static class SaveItem extends SimpleSaveItem { - private String name; - private String description; - private Long resourceTypeId; - private ResourceType.Type resourceType; - private String apiUrl; - private String apiUsername; - private String apiPassword; - private FileInfo file; - private String databaseType; - private String databaseJdbc; - private String databaseUsername; - private String databasePassword; - private FileInfo coreSiteFile; - private FileInfo hdfsSiteFile; - private String ftpUrl; - private String ftpUsername; - private String ftpPassword; - private String ftpPath; - private String ftpRegexFilter; - private Long resourceFormatId; - private ResourceFormat.Type formatType; - private Map jsonSchema; - private String jsonSchemaText; - private Map jsonLineSchema; - private String jsonLineSchemaText; - private Map csvSchema; - private String csvSchemaText; - private FileInfo exampleFile; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static class SaveItem extends SimpleSaveItem { + private String name; + private String description; + private Long resourceTypeId; + private ResourceType.Type resourceType; + private String apiUrl; + private String apiUsername; + private String apiPassword; + private FileInfo file; + private String databaseType; + private String databaseJdbc; + private String databaseUsername; + private String databasePassword; + private FileInfo coreSiteFile; + private FileInfo hdfsSiteFile; + private String ftpUrl; + private String ftpUsername; + private String ftpPassword; + private String ftpPath; + private String ftpRegexFilter; + private Long resourceFormatId; + private ResourceFormat.Type formatType; + private Map jsonSchema; + private String jsonSchemaText; + private Map jsonLineSchema; + private String jsonLineSchemaText; + private Map csvSchema; + private String csvSchemaText; + private FileInfo exampleFile; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static final class ListItem extends SimpleListItem { - private Long id; - private String name; - private String description; - private String type; - private String format; - private Long confirmationId; - private Confirmation.State confirmationState; - private String createdUser; - private LocalDateTime createdTime; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static final class ListItem extends SimpleListItem { + private Long id; + private String name; + private String description; + private String type; + private String format; + private Long confirmationId; + private Confirmation.State confirmationState; + private String createdUser; + private LocalDateTime createdTime; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static final class DetailItem extends SaveItem { - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static final class DetailItem extends SaveItem { + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserController.java index 3aa5026..8abeaac 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserController.java @@ -23,54 +23,54 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user") public class UserController { - private static final Logger logger = LoggerFactory.getLogger(UserController.class); + private static final Logger logger = LoggerFactory.getLogger(UserController.class); - private final UserService userService; + private final UserService userService; - public UserController(UserService userService) { - this.userService = userService; + public UserController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/state") + public AmisResponse state() { + return AmisResponse.responseSuccess(userService.state()); + } + + @PostMapping("/register") + public void register(@RequestBody RegisterRequest request) { + logger.info("Register request: {}", request); + userService.register(request.username, request.password, request.role); + } + + @PostMapping("/login") + public AmisResponse login(@RequestBody LoginRequest request) { + logger.info("Login request: {}", request); + return AmisResponse.responseSuccess(userService.login(request.username, request.password)); + } + + @GetMapping("/logout") + public void logout() { + userService.logout(); + } + + @GetMapping("/exists_username/{username}") + public void existsUsername(@PathVariable("username") String username) { + if (userService.exitsUsername(username)) { + throw new RuntimeException(StrUtil.format("{} 已存在", username)); } + } - @GetMapping("/state") - public AmisResponse state() { - return AmisResponse.responseSuccess(userService.state()); - } + @Data + public static final class LoginRequest { + private String username; + private String password; + private String checkCode; + } - @PostMapping("/register") - public void register(@RequestBody RegisterRequest request) { - logger.info("Register request: {}", request); - userService.register(request.username, request.password, request.role); - } - - @PostMapping("/login") - public AmisResponse login(@RequestBody LoginRequest request) { - logger.info("Login request: {}", request); - return AmisResponse.responseSuccess(userService.login(request.username, request.password)); - } - - @GetMapping("/logout") - public void logout() { - userService.logout(); - } - - @GetMapping("/exists_username/{username}") - public void existsUsername(@PathVariable("username") String username) { - if (userService.exitsUsername(username)) { - throw new RuntimeException(StrUtil.format("{} 已存在", username)); - } - } - - @Data - public static final class LoginRequest { - private String username; - private String password; - private String checkCode; - } - - @Data - public static final class RegisterRequest { - private String username; - private String password; - private User.Role role; - } + @Data + public static final class RegisterRequest { + private String username; + private String password; + private User.Role role; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserManagementController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserManagementController.java index 5023478..d42ee6e 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserManagementController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/UserManagementController.java @@ -25,112 +25,112 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user_management") public class UserManagementController { - private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class); + private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class); - private final UserService userService; + private final UserService userService; - public UserManagementController(UserService userService) { - this.userService = userService; + public UserManagementController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/list") + public AmisListResponse list() { + return AmisListResponse.responseListData(userService.list().collect(UserListItem::new)); + } + + @GetMapping("/detail/{username}") + public AmisResponse detail(@PathVariable String username) { + return AmisResponse.responseSuccess(new UserDetail(userService.detail(username))); + } + + @PostMapping("/register") + public void register(@RequestBody RegisterRequest request) { + logger.info("Register request: {}", request); + userService.registerFromAdministrator(request.username, request.password, request.role); + } + + @PostMapping("/change_password") + public AmisResponse changePassword(@RequestBody ChangePasswordRequest request) { + userService.changePassword(request.oldPassword, request.newPassword); + return AmisResponse.responseSuccess(); + } + + @GetMapping("/disable/{username}") + public AmisResponse disable(@PathVariable String username) { + userService.disable(username); + return AmisResponse.responseSuccess(); + } + + @GetMapping("/enable/{username}") + public AmisResponse enable(@PathVariable String username) { + userService.enable(username); + return AmisResponse.responseSuccess(); + } + + @GetMapping("/check/{username}") + public AmisResponse check(@PathVariable String username) { + userService.check(username); + return AmisResponse.responseSuccess(); + } + + @Data + public static final class ChangePasswordRequest { + private String oldPassword; + private String newPassword; + } + + @Data + public static final class RegisterRequest { + private String username; + private String password; + private User.Role role; + } + + @Data + public static final class UserListItem { + private Long id; + private String username; + private User.Role role; + private User.State state; + private LocalDateTime lastLoginTime; + private LocalDateTime createdTime; + + public UserListItem(User user) { + this.id = user.getId(); + this.username = user.getUsername(); + this.role = user.getRole(); + this.state = user.getState(); + this.lastLoginTime = user.getLastLoginTime(); + this.createdTime = user.getCreatedTime(); } + } - @GetMapping("/list") - public AmisListResponse list() { - return AmisListResponse.responseListData(userService.list().collect(UserListItem::new)); - } - - @GetMapping("/detail/{username}") - public AmisResponse detail(@PathVariable String username) { - return AmisResponse.responseSuccess(new UserDetail(userService.detail(username))); - } - - @PostMapping("/register") - public void register(@RequestBody RegisterRequest request) { - logger.info("Register request: {}", request); - userService.registerFromAdministrator(request.username, request.password, request.role); - } - - @PostMapping("/change_password") - public AmisResponse changePassword(@RequestBody ChangePasswordRequest request) { - userService.changePassword(request.oldPassword, request.newPassword); - return AmisResponse.responseSuccess(); - } - - @GetMapping("/disable/{username}") - public AmisResponse disable(@PathVariable String username) { - userService.disable(username); - return AmisResponse.responseSuccess(); - } - - @GetMapping("/enable/{username}") - public AmisResponse enable(@PathVariable String username) { - userService.enable(username); - return AmisResponse.responseSuccess(); - } - - @GetMapping("/check/{username}") - public AmisResponse check(@PathVariable String username) { - userService.check(username); - return AmisResponse.responseSuccess(); - } - - @Data - public static final class ChangePasswordRequest { - private String oldPassword; - private String newPassword; - } - - @Data - public static final class RegisterRequest { - private String username; - private String password; - private User.Role role; - } - - @Data - public static final class UserListItem { - private Long id; - private String username; - private User.Role role; - private User.State state; - private LocalDateTime lastLoginTime; - private LocalDateTime createdTime; - - public UserListItem(User user) { - this.id = user.getId(); - this.username = user.getUsername(); - this.role = user.getRole(); - this.state = user.getState(); - this.lastLoginTime = user.getLastLoginTime(); - this.createdTime = user.getCreatedTime(); - } - } - - @Data - public static final class UserDetail { - private String username; - private User.Role role; - private User.State state; - private LocalDateTime lastLoginTime; - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - private LocalDateTime checkedTime; - private String checkedUsername; - - public UserDetail(User user) { - this.username = user.getUsername(); - this.role = user.getRole(); - this.state = user.getState(); - this.lastLoginTime = user.getLastLoginTime(); - this.createdTime = user.getCreatedTime(); - this.createdUsername = user.getCreatedUser().getUsername(); - this.modifiedTime = user.getModifiedTime(); - this.modifiedUsername = user.getModifiedUser().getUsername(); - if (ObjectUtil.isNotNull(user.getCheckedUser())) { - this.checkedTime = user.getCheckedTime(); - this.checkedUsername = user.getCheckedUser().getUsername(); - } - } + @Data + public static final class UserDetail { + private String username; + private User.Role role; + private User.State state; + private LocalDateTime lastLoginTime; + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + private LocalDateTime checkedTime; + private String checkedUsername; + + public UserDetail(User user) { + this.username = user.getUsername(); + this.role = user.getRole(); + this.state = user.getState(); + this.lastLoginTime = user.getLastLoginTime(); + this.createdTime = user.getCreatedTime(); + this.createdUsername = user.getCreatedUser().getUsername(); + this.modifiedTime = user.getModifiedTime(); + this.modifiedUsername = user.getModifiedUser().getUsername(); + if (ObjectUtil.isNotNull(user.getCheckedUser())) { + this.checkedTime = user.getCheckedTime(); + this.checkedUsername = user.getCheckedUser().getUsername(); + } } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/WareController.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/WareController.java index 0539c76..13732c4 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/WareController.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/controller/WareController.java @@ -29,108 +29,108 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("ware") public class WareController extends SimpleControllerSupport { - private final HostConfiguration hostConfiguration; - private final WareService wareService; - private final DataResourceService dataResourceService; - private final DataFileService dataFileService; + private final HostConfiguration hostConfiguration; + private final WareService wareService; + private final DataResourceService dataResourceService; + private final DataFileService dataFileService; - public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) { - super(service); - this.hostConfiguration = hostConfiguration; - this.wareService = service; - this.dataResourceService = dataResourceService; - this.dataFileService = dataFileService; - } + public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) { + super(service); + this.hostConfiguration = hostConfiguration; + this.wareService = service; + this.dataResourceService = dataResourceService; + this.dataFileService = dataFileService; + } - @GetMapping(LIST + "_public") - public AmisResponse> listPublic() { - return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem)); - } + @GetMapping(LIST + "_public") + public AmisResponse> listPublic() { + return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem)); + } - @GetMapping("/submit/{id}") - public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { - wareService.submit(id); - return AmisResponse.responseSuccess(); - } + @GetMapping("/submit/{id}") + public AmisResponse submit(@PathVariable Long id) throws JsonProcessingException { + wareService.submit(id); + return AmisResponse.responseSuccess(); + } - @GetMapping("/retract/{id}") - public AmisResponse retract(@PathVariable Long id) { - wareService.retract(id); - return AmisResponse.responseSuccess(); - } + @GetMapping("/retract/{id}") + public AmisResponse retract(@PathVariable Long id) { + wareService.retract(id); + return AmisResponse.responseSuccess(); + } - @Override - protected Ware fromSaveItem(SaveItem saveItem) { - Ware ware = new Ware(); - ware.setId(saveItem.getId()); - ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId())); - ware.setName(saveItem.getName()); - ware.setDescription(saveItem.getDescription()); - ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId())); - ware.setContent(saveItem.getContent()); - return ware; - } + @Override + protected Ware fromSaveItem(SaveItem saveItem) { + Ware ware = new Ware(); + ware.setId(saveItem.getId()); + ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId())); + ware.setName(saveItem.getName()); + ware.setDescription(saveItem.getDescription()); + ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId())); + ware.setContent(saveItem.getContent()); + return ware; + } - @Override - protected ListItem toListItem(Ware entity) { - ListItem item = new ListItem(); - item.setId(entity.getId()); - item.setName(entity.getName()); - item.setDescription(entity.getDescription()); - item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId())); - item.setState(entity.getState().name()); - item.setResourceId(entity.getResource().getId()); - item.setCreatedTime(entity.getCreatedTime()); - item.setCreatedUsername(entity.getCreatedUser().getUsername()); - return item; - } + @Override + protected ListItem toListItem(Ware entity) { + ListItem item = new ListItem(); + item.setId(entity.getId()); + item.setName(entity.getName()); + item.setDescription(entity.getDescription()); + item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId())); + item.setState(entity.getState().name()); + item.setResourceId(entity.getResource().getId()); + item.setCreatedTime(entity.getCreatedTime()); + item.setCreatedUsername(entity.getCreatedUser().getUsername()); + return item; + } - @Override - protected DetailItem toDetailItem(Ware entity) { - DetailItem item = new DetailItem(); - item.setId(entity.getId()); - item.setResourceId(entity.getResource().getId()); - item.setResourceName(entity.getResource().getName()); - item.setName(entity.getName()); - item.setDescription(entity.getDescription()); - item.setIconId(entity.getIcon().getId()); - item.setContent(entity.getContent()); - item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId())); - item.setCreatedTime(entity.getCreatedTime()); - item.setCreatedUsername(entity.getCreatedUser().getUsername()); - item.setModifiedTime(entity.getModifiedTime()); - item.setModifiedUsername(entity.getModifiedUser().getUsername()); - return item; - } + @Override + protected DetailItem toDetailItem(Ware entity) { + DetailItem item = new DetailItem(); + item.setId(entity.getId()); + item.setResourceId(entity.getResource().getId()); + item.setResourceName(entity.getResource().getName()); + item.setName(entity.getName()); + item.setDescription(entity.getDescription()); + item.setIconId(entity.getIcon().getId()); + item.setContent(entity.getContent()); + item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId())); + item.setCreatedTime(entity.getCreatedTime()); + item.setCreatedUsername(entity.getCreatedUser().getUsername()); + item.setModifiedTime(entity.getModifiedTime()); + item.setModifiedUsername(entity.getModifiedUser().getUsername()); + return item; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static class SaveItem extends SimpleSaveItem { - private Long resourceId; - private String name; - private String description; - private Long iconId; - private String content; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static class SaveItem extends SimpleSaveItem { + private Long resourceId; + private String name; + private String description; + private Long iconId; + private String content; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static class ListItem extends SimpleListItem { - private String name; - private String description; - private String state; - private String icon; - private Long resourceId; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static class ListItem extends SimpleListItem { + private String name; + private String description; + private String state; + private String icon; + private Long resourceId; + } - @Data - @EqualsAndHashCode(callSuper = true) - public static class DetailItem extends SaveItem { - private String icon; - private String resourceName; - private LocalDateTime createdTime; - private String createdUsername; - private LocalDateTime modifiedTime; - private String modifiedUsername; - } + @Data + @EqualsAndHashCode(callSuper = true) + public static class DetailItem extends SaveItem { + private String icon; + private String resourceName; + private LocalDateTime createdTime; + private String createdUsername; + private LocalDateTime modifiedTime; + private String modifiedUsername; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Authentication.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Authentication.java index 8e55da3..bad1a44 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Authentication.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Authentication.java @@ -41,33 +41,33 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @EntityListeners(AuditingEntityListener.class) @Table(name = Constants.TABLE_PREFIX + "authentication") @NamedEntityGraph(name = "authentication.list", attributeNodes = { - @NamedAttributeNode(value = "target"), - @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "target"), + @NamedAttributeNode(value = "createdUser"), }) @NamedEntityGraph(name = "authentication.detail", attributeNodes = { - @NamedAttributeNode(value = "target"), - @NamedAttributeNode(value = "evidences"), - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "target"), + @NamedAttributeNode(value = "evidences"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "authentication" + " set deleted = true where id = ?") @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) public class Authentication extends CheckingNeededEntity { - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private DataResource target; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private Set evidences; - /** - * 生效时间 - */ - @Column(nullable = false) - private LocalDateTime activeTime = LocalDateTime.now(); - /** - * 过期时间 - */ - @Column(nullable = false) - private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1); + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private DataResource target; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private Set evidences; + /** + * 生效时间 + */ + @Column(nullable = false) + private LocalDateTime activeTime = LocalDateTime.now(); + /** + * 过期时间 + */ + @Column(nullable = false) + private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/CheckOrder.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/CheckOrder.java index 1e90f38..77e9ffb 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/CheckOrder.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/CheckOrder.java @@ -34,97 +34,97 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @EntityListeners(AuditingEntityListener.class) @Table(name = Constants.TABLE_PREFIX + "check_order") @NamedEntityGraph(name = "check_order.list", attributeNodes = { - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @NamedEntityGraph(name = "check_order.detail", attributeNodes = { - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @NoArgsConstructor public class CheckOrder extends SimpleEntity { - @Column(nullable = false) - private String keyword; - @Column(nullable = false) - private String description; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private Type type; - /** - * JSON 结构 Map - */ - @Column(nullable = false) - private String parameters; + @Column(nullable = false) + private String keyword; + @Column(nullable = false) + private String description; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private Type type; + /** + * JSON 结构 Map + */ + @Column(nullable = false) + private String parameters; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private Target target; - @Column(nullable = false) - private String targetClass; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private User targetUser; - @Enumerated(EnumType.STRING) - private User.Role targetRole; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private Target target; + @Column(nullable = false) + private String targetClass; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private User targetUser; + @Enumerated(EnumType.STRING) + private User.Role targetRole; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private State state = State.CHECKING; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private State state = State.CHECKING; - public CheckOrder( - String keyword, - String description, - Type type, - String parameters, - String targetClass, - User targetUser - ) { - this.keyword = keyword; - this.description = description; - this.type = type; - this.parameters = parameters; - this.target = Target.USER; - this.targetClass = targetClass; - this.targetUser = targetUser; - } + public CheckOrder( + String keyword, + String description, + Type type, + String parameters, + String targetClass, + User targetUser + ) { + this.keyword = keyword; + this.description = description; + this.type = type; + this.parameters = parameters; + this.target = Target.USER; + this.targetClass = targetClass; + this.targetUser = targetUser; + } - public CheckOrder( - String keyword, - String description, - Type type, - String parameters, - String targetClass, - User.Role targetRole - ) { - this.keyword = keyword; - this.description = description; - this.type = type; - this.parameters = parameters; - this.target = Target.ROLE; - this.targetClass = targetClass; - this.targetRole = targetRole; - } + public CheckOrder( + String keyword, + String description, + Type type, + String parameters, + String targetClass, + User.Role targetRole + ) { + this.keyword = keyword; + this.description = description; + this.type = type; + this.parameters = parameters; + this.target = Target.ROLE; + this.targetClass = targetClass; + this.targetRole = targetRole; + } - public enum Operation { - APPLY, - REJECT, - } + public enum Operation { + APPLY, + REJECT, + } - public enum Type { - CONFIRMATION, - AUTHENTICATION, - MARKET, - } + public enum Type { + CONFIRMATION, + AUTHENTICATION, + MARKET, + } - public enum Target { - USER, - ROLE, - } + public enum Target { + USER, + ROLE, + } - public enum State { - CHECKING, - RETRACT, - OVER, - } + public enum State { + CHECKING, + RETRACT, + OVER, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Confirmation.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Confirmation.java index 9c7d5c1..1922487 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Confirmation.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Confirmation.java @@ -39,23 +39,23 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @EntityListeners(AuditingEntityListener.class) @Table(name = Constants.TABLE_PREFIX + "confirmation") @NamedEntityGraph(name = "confirmation.list", attributeNodes = { - @NamedAttributeNode(value = "target"), - @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "target"), + @NamedAttributeNode(value = "createdUser"), }) @NamedEntityGraph(name = "confirmation.detail", attributeNodes = { - @NamedAttributeNode(value = "target"), - @NamedAttributeNode(value = "evidences"), - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "target"), + @NamedAttributeNode(value = "evidences"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "confirmation" + " set deleted = true where id = ?") @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) public class Confirmation extends CheckingNeededEntity { - @OneToOne(fetch = FetchType.EAGER) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private DataResource target; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private Set evidences; + @OneToOne(fetch = FetchType.EAGER) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private DataResource target; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private Set evidences; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataFile.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataFile.java index 2f5611c..80e1c53 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataFile.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataFile.java @@ -26,9 +26,9 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_file" + " set deleted = true where id = ?") @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) public class DataFile extends LogicDeleteEntity { - private String filename; - private Long size; - private String md5; - private String path; - private String type; + private String filename; + private Long size; + private String md5; + private String path; + private String type; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataResource.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataResource.java index 992a939..57e4d4b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataResource.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/DataResource.java @@ -34,44 +34,44 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @DynamicUpdate @Table(name = Constants.TABLE_PREFIX + "data_resource") @NamedEntityGraph(name = "data_resource.list", attributeNodes = { - @NamedAttributeNode(value = "type"), - @NamedAttributeNode(value = "format"), - @NamedAttributeNode(value = "confirmation"), - @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "type"), + @NamedAttributeNode(value = "format"), + @NamedAttributeNode(value = "confirmation"), + @NamedAttributeNode(value = "createdUser"), }) @NamedEntityGraph(name = "data_resource.detail", attributeNodes = { - @NamedAttributeNode(value = "type"), - @NamedAttributeNode(value = "format"), - @NamedAttributeNode(value = "example"), - @NamedAttributeNode(value = "confirmation"), - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "type"), + @NamedAttributeNode(value = "format"), + @NamedAttributeNode(value = "example"), + @NamedAttributeNode(value = "confirmation"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_resource" + " set deleted = true where id = ?") @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) public class DataResource extends LogicDeleteEntity { - @Column(nullable = false) - private String name; - private String description; - @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private ResourceType type; - @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private ResourceFormat format; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private DataFile example; - @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target") - @ToString.Exclude - private Confirmation confirmation; - @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target") - @ToString.Exclude - private Set authentications; - @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "resource") - @ToString.Exclude - private Ware ware; + @Column(nullable = false) + private String name; + private String description; + @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private ResourceType type; + @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private ResourceFormat format; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private DataFile example; + @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target") + @ToString.Exclude + private Confirmation confirmation; + @OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target") + @ToString.Exclude + private Set authentications; + @OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "resource") + @ToString.Exclude + private Ware ware; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/User.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/User.java index a19ee6f..a691696 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/User.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/User.java @@ -33,98 +33,98 @@ import org.hibernate.annotations.DynamicUpdate; @DynamicUpdate @Table(name = Constants.TABLE_PREFIX + "user") @NamedEntityGraph(name = "user.list", attributeNodes = { - @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "createdUser"), }) @NamedEntityGraph(name = "user.detail", attributeNodes = { - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), - @NamedAttributeNode(value = "checkedUser"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "checkedUser"), }) public class User extends SimpleEntity { - @Column(unique = true, nullable = false) - private String username; - @Column(nullable = false) - private String password; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private Role role; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private State state = State.CHECKING; - private LocalDateTime lastLoginTime; - private LocalDateTime checkedTime; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private User checkedUser; + @Column(unique = true, nullable = false) + private String username; + @Column(nullable = false) + private String password; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private Role role; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private State state = State.CHECKING; + private LocalDateTime lastLoginTime; + private LocalDateTime checkedTime; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private User checkedUser; - public static boolean isAdministrator(User user) { - return Role.ADMINISTRATOR.equals(user.role); - } + public static boolean isAdministrator(User user) { + return Role.ADMINISTRATOR.equals(user.role); + } - public static boolean isNotAdministrator(User user) { - return !isAdministrator(user); - } + public static boolean isNotAdministrator(User user) { + return !isAdministrator(user); + } - public static boolean isChecker(User user) { - return Role.CHECKER.equals(user.role); - } + public static boolean isChecker(User user) { + return Role.CHECKER.equals(user.role); + } - public static boolean isNotChecker(User user) { - return !isChecker(user); - } + public static boolean isNotChecker(User user) { + return !isChecker(user); + } - public static boolean isProvider(User user) { - return Role.PROVIDER.equals(user.role); - } + public static boolean isProvider(User user) { + return Role.PROVIDER.equals(user.role); + } - public static boolean isNotProvider(User user) { - return !isProvider(user); - } + public static boolean isNotProvider(User user) { + return !isProvider(user); + } - public static boolean isCustomer(User user) { - return Role.CUSTOMER.equals(user.role); - } + public static boolean isCustomer(User user) { + return Role.CUSTOMER.equals(user.role); + } - public static boolean isNotCustomer(User user) { - return !isCustomer(user); - } + public static boolean isNotCustomer(User user) { + return !isCustomer(user); + } - public static boolean isUser(User user) { - return isProvider(user) || isCustomer(user); - } + public static boolean isUser(User user) { + return isProvider(user) || isCustomer(user); + } - public enum State { - /** - * 审查中 - */ - CHECKING, - /** - * 正常 - */ - NORMAL, - /** - * 禁用 - */ - DISABLED, - } + public enum State { + /** + * 审查中 + */ + CHECKING, + /** + * 正常 + */ + NORMAL, + /** + * 禁用 + */ + DISABLED, + } - public enum Role { - /** - * 数据提供方 - */ - PROVIDER, - /** - * 数据使用方 - */ - CUSTOMER, - /** - * 数据监管方 - */ - CHECKER, - /** - * 系统管理员 - */ - ADMINISTRATOR, - } + public enum Role { + /** + * 数据提供方 + */ + PROVIDER, + /** + * 数据使用方 + */ + CUSTOMER, + /** + * 数据监管方 + */ + CHECKER, + /** + * 系统管理员 + */ + ADMINISTRATOR, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Ware.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Ware.java index 350c6a0..4c1943c 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Ware.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/Ware.java @@ -39,33 +39,33 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; @DynamicUpdate @Table(name = Constants.TABLE_PREFIX + "ware") @NamedEntityGraph(name = "ware.list", attributeNodes = { - @NamedAttributeNode(value = "icon"), - @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "icon"), + @NamedAttributeNode(value = "createdUser"), }) @NamedEntityGraph(name = "ware.detail", attributeNodes = { - @NamedAttributeNode(value = "icon"), - @NamedAttributeNode(value = "content"), - @NamedAttributeNode(value = "createdUser"), - @NamedAttributeNode(value = "modifiedUser"), + @NamedAttributeNode(value = "icon"), + @NamedAttributeNode(value = "content"), + @NamedAttributeNode(value = "createdUser"), + @NamedAttributeNode(value = "modifiedUser"), }) @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "ware" + " set deleted = true where id = ?") @Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE) public class Ware extends CheckingNeededEntity { - @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private DataResource resource; - @Column(nullable = false) - private String name; - @Column(nullable = false) - private String description; - @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY) - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - @ToString.Exclude - private DataFile icon; - @Lob - @Basic(fetch = FetchType.LAZY) - @ToString.Exclude - @Column(nullable = false) - private String content; + @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private DataResource resource; + @Column(nullable = false) + private String name; + @Column(nullable = false) + private String description; + @OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY) + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + @ToString.Exclude + private DataFile icon; + @Lob + @Basic(fetch = FetchType.LAZY) + @ToString.Exclude + @Column(nullable = false) + private String content; } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/CsvResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/CsvResourceFormat.java index 0a8ef63..5e278bf 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/CsvResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/CsvResourceFormat.java @@ -28,10 +28,10 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class CsvResourceFormat extends ResourceFormat { - private String schema; + private String schema; - @Override - public Type getFormatType() { - return Type.CSV; - } + @Override + public Type getFormatType() { + return Type.CSV; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonLineResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonLineResourceFormat.java index bf57e10..a19d70c 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonLineResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonLineResourceFormat.java @@ -28,10 +28,10 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class JsonLineResourceFormat extends ResourceFormat { - private String schema; + private String schema; - @Override - public Type getFormatType() { - return Type.JSON_LINE; - } + @Override + public Type getFormatType() { + return Type.JSON_LINE; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonResourceFormat.java index 18207f2..35a7cfa 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/JsonResourceFormat.java @@ -28,10 +28,10 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class JsonResourceFormat extends ResourceFormat { - private String schema; + private String schema; - @Override - public Type getFormatType() { - return Type.JSON; - } + @Override + public Type getFormatType() { + return Type.JSON; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/LineResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/LineResourceFormat.java index 46a8e55..066c668 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/LineResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/LineResourceFormat.java @@ -24,8 +24,8 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class LineResourceFormat extends ResourceFormat { - @Override - public Type getFormatType() { - return Type.LINE; - } + @Override + public Type getFormatType() { + return Type.LINE; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/NoneResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/NoneResourceFormat.java index c26eed2..52a5cd9 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/NoneResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/NoneResourceFormat.java @@ -24,8 +24,8 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class NoneResourceFormat extends ResourceFormat { - @Override - public Type getFormatType() { - return Type.NONE; - } + @Override + public Type getFormatType() { + return Type.NONE; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/ResourceFormat.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/ResourceFormat.java index a23643d..a8b5456 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/ResourceFormat.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/format/ResourceFormat.java @@ -27,13 +27,13 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public abstract class ResourceFormat extends LogicDeleteIdOnlyEntity { - public abstract Type getFormatType(); + public abstract Type getFormatType(); - public enum Type { - NONE, - LINE, - JSON, - JSON_LINE, - CSV, - } + public enum Type { + NONE, + LINE, + JSON, + JSON_LINE, + CSV, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ApiResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ApiResourceType.java index 5f5e21c..e26ba1f 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ApiResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ApiResourceType.java @@ -23,13 +23,13 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_api" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class ApiResourceType extends ResourceType { - @Column(nullable = false) - private String url; - private String username; - private String password; + @Column(nullable = false) + private String url; + private String username; + private String password; - @Override - public Type getResourceType() { - return Type.API; - } + @Override + public Type getResourceType() { + return Type.API; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/DatabaseResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/DatabaseResourceType.java index ac9d328..25d4954 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/DatabaseResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/DatabaseResourceType.java @@ -25,22 +25,22 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_database" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class DatabaseResourceType extends ResourceType { - @Column(nullable = false) - private String jdbc; - private String username; - private String password; - @Column(nullable = false) - @Enumerated(EnumType.STRING) - private DatabaseType databaseType; + @Column(nullable = false) + private String jdbc; + private String username; + private String password; + @Column(nullable = false) + @Enumerated(EnumType.STRING) + private DatabaseType databaseType; - @Override - public Type getResourceType() { - return Type.DATABASE; - } + @Override + public Type getResourceType() { + return Type.DATABASE; + } - public enum DatabaseType { - MYSQL, - POSTGRESQL, - ORACLE, - } + public enum DatabaseType { + MYSQL, + POSTGRESQL, + ORACLE, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FileResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FileResourceType.java index cf8d266..2159606 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FileResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FileResourceType.java @@ -27,12 +27,12 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_file" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class FileResourceType extends ResourceType { - @OneToOne - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private DataFile file; + @OneToOne + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private DataFile file; - @Override - public Type getResourceType() { - return Type.FILE; - } + @Override + public Type getResourceType() { + return Type.FILE; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FtpResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FtpResourceType.java index 0661bba..424691b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FtpResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/FtpResourceType.java @@ -23,15 +23,15 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_ftp" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class FtpResourceType extends ResourceType { - @Column(nullable = false) - private String url; - private String username; - private String password; - private String path; - private String regexFilter; + @Column(nullable = false) + private String url; + private String username; + private String password; + private String path; + private String regexFilter; - @Override - public Type getResourceType() { - return Type.FTP; - } + @Override + public Type getResourceType() { + return Type.FTP; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/HDFSResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/HDFSResourceType.java index 781c7af..0632d46 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/HDFSResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/HDFSResourceType.java @@ -27,15 +27,15 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_hdfs" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public class HDFSResourceType extends ResourceType { - @OneToOne - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private DataFile coreSite; - @OneToOne - @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) - private DataFile hdfsSite; + @OneToOne + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private DataFile coreSite; + @OneToOne + @JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT)) + private DataFile hdfsSite; - @Override - public Type getResourceType() { - return Type.HDFS; - } + @Override + public Type getResourceType() { + return Type.HDFS; + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ResourceType.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ResourceType.java index 26774ab..c717fbc 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ResourceType.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/entity/type/ResourceType.java @@ -27,13 +27,13 @@ import org.hibernate.annotations.Where; @SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type" + " set deleted = true where id = ?") @Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE) public abstract class ResourceType extends LogicDeleteIdOnlyEntity { - public abstract Type getResourceType(); + public abstract Type getResourceType(); - public enum Type { - API, - DATABASE, - FILE, - FTP, - HDFS, - } + public enum Type { + API, + DATABASE, + FILE, + FTP, + HDFS, + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/AuthenticationRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/AuthenticationRepository.java index 8bb7004..36db649 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/AuthenticationRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/AuthenticationRepository.java @@ -16,15 +16,15 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface AuthenticationRepository extends SimpleRepository { - @Override - @EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification); + @Override + @EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification); - @Override - @EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification, Sort sort); + @Override + @EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification, Sort sort); - @Override - @EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findOne(Specification specification); + @Override + @EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findOne(Specification specification); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/CheckOrderRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/CheckOrderRepository.java index 87d345d..e95fd31 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/CheckOrderRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/CheckOrderRepository.java @@ -20,20 +20,20 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface CheckOrderRepository extends SimpleRepository { - @Override - @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification); + @Override + @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification); - @Override - @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification, Sort sort); + @Override + @EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification, Sort sort); - @Override - @EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findOne(Specification specification); + @Override + @EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findOne(Specification specification); - @Transactional - @Modifying - @Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1") - void overById(Long id, CheckOrder.State state, User modifiedUser); + @Transactional + @Modifying + @Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1") + void overById(Long id, CheckOrder.State state, User modifiedUser); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/ConfirmationRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/ConfirmationRepository.java index 813464d..e62f06b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/ConfirmationRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/ConfirmationRepository.java @@ -16,17 +16,17 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface ConfirmationRepository extends SimpleRepository { - @Override - @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification); + @Override + @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification); - @Override - @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification, Sort sort); + @Override + @EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification, Sort sort); - @Override - @EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findOne(Specification specification); + @Override + @EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findOne(Specification specification); - Boolean existsByTarget_Id(Long id); + Boolean existsByTarget_Id(Long id); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/DataResourceRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/DataResourceRepository.java index 7871f0f..9aedef5 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/DataResourceRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/DataResourceRepository.java @@ -12,18 +12,18 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface DataResourceRepository extends SimpleRepository { - @Override - @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification); + @Override + @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification); - @Override - @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification, Sort sort); + @Override + @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification, Sort sort); - @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) - List findAllByConfirmationIsNull(); + @EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH) + List findAllByConfirmationIsNull(); - @Override - @EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findOne(Specification specification); + @Override + @EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findOne(Specification specification); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/UserRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/UserRepository.java index 7760c91..b2a5562 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/UserRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/UserRepository.java @@ -16,12 +16,12 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface UserRepository extends SimpleRepository { - @Override - @EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(); + @Override + @EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(); - Boolean existsByUsername(String username); + Boolean existsByUsername(String username); - @EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findByUsername(String username); + @EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findByUsername(String username); } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/WareRepository.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/WareRepository.java index 0a225f9..681228d 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/WareRepository.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/repository/WareRepository.java @@ -12,15 +12,15 @@ import org.springframework.stereotype.Repository; @SuppressWarnings("NullableProblems") @Repository public interface WareRepository extends SimpleRepository { - @Override - @EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification); + @Override + @EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification); - @Override - @EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH) - List findAll(Specification specification, Sort sort); + @Override + @EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH) + List findAll(Specification specification, Sort sort); - @Override - @EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH) - Optional findOne(Specification specification); + @Override + @EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH) + Optional findOne(Specification specification); } \ No newline at end of file diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/AuthenticationService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/AuthenticationService.java index 6a4daa4..b1f120b 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/AuthenticationService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/AuthenticationService.java @@ -34,120 +34,120 @@ import org.springframework.stereotype.Service; @Slf4j @Service("com.eshore.gringotts.web.domain.service.AuthenticationService") public class AuthenticationService extends LogicDeleteService implements CheckingService { - private final AuthenticationRepository authenticationRepository; - private final UserService userService; - private final CheckOrderService checkOrderService; - private final ObjectMapper mapper; + private final AuthenticationRepository authenticationRepository; + private final UserService userService; + private final CheckOrderService checkOrderService; + private final ObjectMapper mapper; - public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { - super(repository, userService, manager); - this.authenticationRepository = repository; - this.userService = userService; - this.checkOrderService = checkOrderService; - this.mapper = builder.build(); + public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { + super(repository, userService, manager); + this.authenticationRepository = repository; + this.userService = userService; + this.checkOrderService = checkOrderService; + this.mapper = builder.build(); + } + + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User loginUser = userService.currentLoginUser(); + if (User.isAdministrator(loginUser)) { + return Lists.immutable.empty(); } + return Lists.immutable.of(builder.or( + builder.equal(root.get(Authentication_.createdUser), loginUser), + builder.and( + builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE), + builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetRole), loginUser.getRole()) + ), + builder.and( + builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.USER), + builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetUser), loginUser) + ) + )); + } - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User loginUser = userService.currentLoginUser(); - if (User.isAdministrator(loginUser)) { - return Lists.immutable.empty(); + @Override + public Long save(Authentication entity) { + if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne( + (root, query, criteriaBuilder) -> { + // TODO 同一个资源的授权时间是否重合 + // 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请 + return criteriaBuilder.and( + criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()), + criteriaBuilder.equal(root.get("target"), entity.getTarget()) + ); } - return Lists.immutable.of(builder.or( - builder.equal(root.get(Authentication_.createdUser), loginUser), - builder.and( - builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE), - builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetRole), loginUser.getRole()) - ), - builder.and( - builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.USER), - builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetUser), loginUser) - ) - )); + ).isPresent()) { + throw new AuthenticationDuplicatedException(); } + return super.save(entity); + } - @Override - public Long save(Authentication entity) { - if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne( - (root, query, criteriaBuilder) -> { - // TODO 同一个资源的授权时间是否重合 - // 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请 - return criteriaBuilder.and( - criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()), - criteriaBuilder.equal(root.get("target"), entity.getTarget()) - ); - } - ).isPresent()) { - throw new AuthenticationDuplicatedException(); - } - return super.save(entity); + @Transactional(rollbackOn = Throwable.class) + public void submit(Long id) throws JsonProcessingException { + Authentication authentication = detailOrThrow(id); + authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING); + Long orderId = checkOrderService.save(new CheckOrder( + "authentication_owner_check", + StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()), + CheckOrder.Type.AUTHENTICATION, + mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())), + "com.eshore.gringotts.web.domain.service.AuthenticationService", + authentication.getCreatedUser() + )); + CheckOrder order = checkOrderService.detailOrThrow(orderId); + authentication.setOrder(order); + save(authentication); + } + + @Transactional(rollbackOn = Throwable.class) + public void retract(Long id) { + Authentication authentication = detailOrThrow(id); + authentication.setState(Authentication.State.DRAFT); + save(authentication); + + CheckOrder order = authentication.getOrder(); + order.setState(CheckOrder.State.RETRACT); + checkOrderService.save(order); + } + + @Override + @Transactional(rollbackOn = Throwable.class) + public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { + Long id = (Long) parameters.get("authenticationId"); + Authentication authentication = detailOrThrow(id); + if (StrUtil.equals(order.getKeyword(), "authentication_owner_check")) { + switch (operation) { + case APPLY: + authentication.setState(Authentication.State.CHECKING); + order.setKeyword("authentication_checker_check"); + order.setTarget(CheckOrder.Target.ROLE); + order.setTargetRole(User.Role.CHECKER); + break; + case REJECT: + authentication.setState(Authentication.State.DRAFT); + order.setState(CheckOrder.State.OVER); + break; + } + } else if (StrUtil.equals(order.getKeyword(), "authentication_checker_check")) { + switch (operation) { + case APPLY: + authentication.setState(Authentication.State.NORMAL); + order.setState(CheckOrder.State.OVER); + break; + case REJECT: + authentication.setState(Authentication.State.DRAFT); + order.setState(CheckOrder.State.OVER); + break; + } } + save(authentication); + checkOrderService.save(order); + } - @Transactional(rollbackOn = Throwable.class) - public void submit(Long id) throws JsonProcessingException { - Authentication authentication = detailOrThrow(id); - authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING); - Long orderId = checkOrderService.save(new CheckOrder( - "authentication_owner_check", - StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()), - CheckOrder.Type.AUTHENTICATION, - mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())), - "com.eshore.gringotts.web.domain.service.AuthenticationService", - authentication.getCreatedUser() - )); - CheckOrder order = checkOrderService.detailOrThrow(orderId); - authentication.setOrder(order); - save(authentication); - } - - @Transactional(rollbackOn = Throwable.class) - public void retract(Long id) { - Authentication authentication = detailOrThrow(id); - authentication.setState(Authentication.State.DRAFT); - save(authentication); - - CheckOrder order = authentication.getOrder(); - order.setState(CheckOrder.State.RETRACT); - checkOrderService.save(order); - } - - @Override - @Transactional(rollbackOn = Throwable.class) - public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { - Long id = (Long) parameters.get("authenticationId"); - Authentication authentication = detailOrThrow(id); - if (StrUtil.equals(order.getKeyword(), "authentication_owner_check")) { - switch (operation) { - case APPLY: - authentication.setState(Authentication.State.CHECKING); - order.setKeyword("authentication_checker_check"); - order.setTarget(CheckOrder.Target.ROLE); - order.setTargetRole(User.Role.CHECKER); - break; - case REJECT: - authentication.setState(Authentication.State.DRAFT); - order.setState(CheckOrder.State.OVER); - break; - } - } else if (StrUtil.equals(order.getKeyword(), "authentication_checker_check")) { - switch (operation) { - case APPLY: - authentication.setState(Authentication.State.NORMAL); - order.setState(CheckOrder.State.OVER); - break; - case REJECT: - authentication.setState(Authentication.State.DRAFT); - order.setState(CheckOrder.State.OVER); - break; - } - } - save(authentication); - checkOrderService.save(order); - } - - public static final class AuthenticationDuplicatedException extends RuntimeException { - public AuthenticationDuplicatedException() { - super("数据资源已绑定该账号的授权申请,无法再次申请"); - } + public static final class AuthenticationDuplicatedException extends RuntimeException { + public AuthenticationDuplicatedException() { + super("数据资源已绑定该账号的授权申请,无法再次申请"); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/CheckOrderService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/CheckOrderService.java index e6e66e6..70714df 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/CheckOrderService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/CheckOrderService.java @@ -30,53 +30,53 @@ import org.springframework.stereotype.Service; @Slf4j @Service public class CheckOrderService extends SimpleServiceSupport { - private final ApplicationContext applicationContext; - private final ObjectMapper mapper; - private final CheckOrderRepository checkOrderRepository; - private final UserService userService; + private final ApplicationContext applicationContext; + private final ObjectMapper mapper; + private final CheckOrderRepository checkOrderRepository; + private final UserService userService; - public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) { - super(repository, userService); - this.applicationContext = applicationContext; - this.mapper = builder.build(); - this.checkOrderRepository = repository; - this.userService = userService; - } + public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) { + super(repository, userService); + this.applicationContext = applicationContext; + this.mapper = builder.build(); + this.checkOrderRepository = repository; + this.userService = userService; + } - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User user = userService.currentLoginUser(); - if (User.isAdministrator(user)) { - return Lists.immutable.empty(); - } - return Lists.immutable.of(builder.or( - builder.equal(root.get(CheckOrder_.createdUser), user), - builder.and( - builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.USER), - builder.equal(root.get(CheckOrder_.targetUser), user) - ), - builder.and( - builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.ROLE), - builder.equal(root.get(CheckOrder_.targetRole), user.getRole()) - ) - )); + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User user = userService.currentLoginUser(); + if (User.isAdministrator(user)) { + return Lists.immutable.empty(); } + return Lists.immutable.of(builder.or( + builder.equal(root.get(CheckOrder_.createdUser), user), + builder.and( + builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.USER), + builder.equal(root.get(CheckOrder_.targetUser), user) + ), + builder.and( + builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.ROLE), + builder.equal(root.get(CheckOrder_.targetRole), user.getRole()) + ) + )); + } - public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException { - CheckOrder order = detailOrThrow(id); - CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class); - if (ObjectUtil.isNull(service)) { - throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass())); - } - ImmutableMap parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {}); - service.onChecked(order, operation, parameters); + public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException { + CheckOrder order = detailOrThrow(id); + CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class); + if (ObjectUtil.isNull(service)) { + throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass())); } + ImmutableMap parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {}); + service.onChecked(order, operation, parameters); + } - public void retract(Long id) { - checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser()); - } + public void retract(Long id) { + checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser()); + } - public void over(Long id) { - checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser()); - } + public void over(Long id) { + checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser()); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/ConfirmationService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/ConfirmationService.java index 267dbfb..825d901 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/ConfirmationService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/ConfirmationService.java @@ -35,102 +35,102 @@ import org.springframework.stereotype.Service; @Slf4j @Service("com.eshore.gringotts.web.domain.service.ConfirmationService") public class ConfirmationService extends SimpleServiceSupport implements CheckingService { - private final ConfirmationRepository confirmationRepository; - private final CheckOrderService checkOrderService; - private final ObjectMapper mapper; + private final ConfirmationRepository confirmationRepository; + private final CheckOrderService checkOrderService; + private final ObjectMapper mapper; - public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { - super(confirmationRepository, userService); - this.confirmationRepository = confirmationRepository; - this.checkOrderService = checkOrderService; - this.mapper = builder.build(); + public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { + super(confirmationRepository, userService); + this.confirmationRepository = confirmationRepository; + this.checkOrderService = checkOrderService; + this.mapper = builder.build(); + } + + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User loginUser = userService.currentLoginUser(); + if (User.isAdministrator(loginUser)) { + return Lists.immutable.empty(); } - - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User loginUser = userService.currentLoginUser(); - if (User.isAdministrator(loginUser)) { - return Lists.immutable.empty(); - } - Join orderJoin = root.join(Confirmation_.order, JoinType.LEFT); - return Lists.immutable.of(builder.or( - builder.equal(root.get(Confirmation_.createdUser), loginUser), + Join orderJoin = root.join(Confirmation_.order, JoinType.LEFT); + return Lists.immutable.of(builder.or( + builder.equal(root.get(Confirmation_.createdUser), loginUser), + builder.and( + builder.isNotNull(orderJoin), + builder.or( builder.and( - builder.isNotNull(orderJoin), - builder.or( - builder.and( - builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE), - builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole()) - ), - builder.and( - builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER), - builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser) - ) - ) + builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE), + builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole()) + ), + builder.and( + builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER), + builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser) ) - )); - } + ) + ) + )); + } - @Override - public Long save(Confirmation entity) { - if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) { - throw new ConfirmationDuplicatedException(); - } - return super.save(entity); + @Override + public Long save(Confirmation entity) { + if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) { + throw new ConfirmationDuplicatedException(); } + return super.save(entity); + } - @Transactional(rollbackOn = Throwable.class) - public void submit(Long id) throws JsonProcessingException { - Confirmation confirmation = detailOrThrow(id); - confirmation.setState(Confirmation.State.CHECKING); - Long orderId = checkOrderService.save(new CheckOrder( - "confirmation_check", - StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()), - CheckOrder.Type.CONFIRMATION, - mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())), - "com.eshore.gringotts.web.domain.service.ConfirmationService", - User.Role.CHECKER - )); - CheckOrder order = checkOrderService.detailOrThrow(orderId); - confirmation.setOrder(order); - save(confirmation); + @Transactional(rollbackOn = Throwable.class) + public void submit(Long id) throws JsonProcessingException { + Confirmation confirmation = detailOrThrow(id); + confirmation.setState(Confirmation.State.CHECKING); + Long orderId = checkOrderService.save(new CheckOrder( + "confirmation_check", + StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()), + CheckOrder.Type.CONFIRMATION, + mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())), + "com.eshore.gringotts.web.domain.service.ConfirmationService", + User.Role.CHECKER + )); + CheckOrder order = checkOrderService.detailOrThrow(orderId); + confirmation.setOrder(order); + save(confirmation); + } + + @Transactional(rollbackOn = Throwable.class) + public void retract(Long id) { + Confirmation confirmation = detailOrThrow(id); + confirmation.setState(CheckingNeededEntity.State.DRAFT); + save(confirmation); + + CheckOrder order = confirmation.getOrder(); + order.setState(CheckOrder.State.RETRACT); + checkOrderService.save(order); + } + + @Override + @Transactional(rollbackOn = Throwable.class) + public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { + if (StrUtil.equals(order.getKeyword(), "confirmation_check")) { + Long id = (Long) parameters.get("confirmationId"); + Confirmation confirmation = detailOrThrow(id); + switch (operation) { + case APPLY: + confirmation.setState(Confirmation.State.NORMAL); + order.setState(CheckOrder.State.OVER); + break; + case REJECT: + confirmation.setState(Confirmation.State.DRAFT); + order.setState(CheckOrder.State.OVER); + break; + } + save(confirmation); + checkOrderService.save(order); } + } - @Transactional(rollbackOn = Throwable.class) - public void retract(Long id) { - Confirmation confirmation = detailOrThrow(id); - confirmation.setState(CheckingNeededEntity.State.DRAFT); - save(confirmation); - - CheckOrder order = confirmation.getOrder(); - order.setState(CheckOrder.State.RETRACT); - checkOrderService.save(order); - } - - @Override - @Transactional(rollbackOn = Throwable.class) - public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { - if (StrUtil.equals(order.getKeyword(), "confirmation_check")) { - Long id = (Long) parameters.get("confirmationId"); - Confirmation confirmation = detailOrThrow(id); - switch (operation) { - case APPLY: - confirmation.setState(Confirmation.State.NORMAL); - order.setState(CheckOrder.State.OVER); - break; - case REJECT: - confirmation.setState(Confirmation.State.DRAFT); - order.setState(CheckOrder.State.OVER); - break; - } - save(confirmation); - checkOrderService.save(order); - } - } - - public static final class ConfirmationDuplicatedException extends RuntimeException { - public ConfirmationDuplicatedException() { - super("数据资源已绑定确权申请,无法再次申请"); - } + public static final class ConfirmationDuplicatedException extends RuntimeException { + public ConfirmationDuplicatedException() { + super("数据资源已绑定确权申请,无法再次申请"); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataFileService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataFileService.java index 7c41744..9c3ee98 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataFileService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataFileService.java @@ -29,75 +29,75 @@ import org.springframework.stereotype.Service; @Slf4j @Service public class DataFileService extends SimpleServiceSupport { - private final DataFileRepository dataFileRepository; - private final UserService userService; + private final DataFileRepository dataFileRepository; + private final UserService userService; - public DataFileService(DataFileRepository dataFileRepository, UserService userService) { - super(dataFileRepository, userService); - this.dataFileRepository = dataFileRepository; - this.userService = userService; + public DataFileService(DataFileRepository dataFileRepository, UserService userService) { + super(dataFileRepository, userService); + this.dataFileRepository = dataFileRepository; + this.userService = userService; + } + + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User loginUser = userService.currentLoginUser(); + if (User.isAdministrator(loginUser)) { + return Lists.immutable.empty(); } - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User loginUser = userService.currentLoginUser(); - if (User.isAdministrator(loginUser)) { - return Lists.immutable.empty(); - } + Subquery confirmationSubquery = query.subquery(Confirmation.class); + Root confirmationRoot = confirmationSubquery.from(Confirmation.class); + confirmationSubquery.select(confirmationRoot) + .where( + builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)), + EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser) + ); - Subquery confirmationSubquery = query.subquery(Confirmation.class); - Root confirmationRoot = confirmationSubquery.from(Confirmation.class); - confirmationSubquery.select(confirmationRoot) - .where( - builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)), - EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser) - ); + Subquery authenticationSubquery = query.subquery(Authentication.class); + Root authenticationRoot = authenticationSubquery.from(Authentication.class); + authenticationSubquery.select(authenticationRoot) + .where( + builder.isMember(root, authenticationRoot.get(Authentication_.evidences)), + EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) + ); - Subquery authenticationSubquery = query.subquery(Authentication.class); - Root authenticationRoot = authenticationSubquery.from(Authentication.class); - authenticationSubquery.select(authenticationRoot) - .where( - builder.isMember(root, authenticationRoot.get(Authentication_.evidences)), - EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) - ); + return Lists.immutable.of(builder.or( + builder.equal(root.get(DataFile_.createdUser), loginUser), + builder.exists(confirmationSubquery), + builder.exists(authenticationSubquery) + )); + } - return Lists.immutable.of(builder.or( - builder.equal(root.get(DataFile_.createdUser), loginUser), - builder.exists(confirmationSubquery), - builder.exists(authenticationSubquery) - )); + public DataFile downloadFile(Long id) { + return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new); + } + + public Long initialDataFile(String filename) { + DataFile dataFile = new DataFile(); + dataFile.setFilename(filename); + return dataFileRepository.save(dataFile).getId(); + } + + public void updateDataFile(Long id, String path, Long size, String md5, String type) { + DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new); + dataFile.setSize(size); + dataFile.setMd5(md5); + dataFile.setPath(path); + dataFile.setType(type); + User loginUser = userService.currentLoginUser(); + dataFile.setModifiedUser(loginUser); + dataFileRepository.save(dataFile); + } + + public static final class DataFileNotFoundException extends RuntimeException { + public DataFileNotFoundException() { + super("文件未找到,请重新上传"); } + } - public DataFile downloadFile(Long id) { - return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new); - } - - public Long initialDataFile(String filename) { - DataFile dataFile = new DataFile(); - dataFile.setFilename(filename); - return dataFileRepository.save(dataFile).getId(); - } - - public void updateDataFile(Long id, String path, Long size, String md5, String type) { - DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new); - dataFile.setSize(size); - dataFile.setMd5(md5); - dataFile.setPath(path); - dataFile.setType(type); - User loginUser = userService.currentLoginUser(); - dataFile.setModifiedUser(loginUser); - dataFileRepository.save(dataFile); - } - - public static final class DataFileNotFoundException extends RuntimeException { - public DataFileNotFoundException() { - super("文件未找到,请重新上传"); - } - } - - public static final class UpdateDataFileFailedException extends RuntimeException { - public UpdateDataFileFailedException() { - super("更新文件信息失败,请重新上传"); - } + public static final class UpdateDataFileFailedException extends RuntimeException { + public UpdateDataFileFailedException() { + super("更新文件信息失败,请重新上传"); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataResourceService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataResourceService.java index 6e540a3..4538185 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataResourceService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/DataResourceService.java @@ -35,103 +35,103 @@ import org.springframework.stereotype.Service; @Slf4j @Service public class DataResourceService extends SimpleServiceSupport { - private final DataResourceRepository dataResourceRepository; - private final ResourceTypeRepository resourceTypeRepository; - private final ResourceFormatRepository resourceFormatRepository; - private final UserService userService; + private final DataResourceRepository dataResourceRepository; + private final ResourceTypeRepository resourceTypeRepository; + private final ResourceFormatRepository resourceFormatRepository; + private final UserService userService; - public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) { - super(repository, userService); - this.dataResourceRepository = repository; - this.resourceTypeRepository = resourceTypeRepository; - this.resourceFormatRepository = resourceFormatRepository; - this.userService = userService; + public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) { + super(repository, userService); + this.dataResourceRepository = repository; + this.resourceTypeRepository = resourceTypeRepository; + this.resourceFormatRepository = resourceFormatRepository; + this.userService = userService; + } + + @Override + protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { + User loginUser = userService.currentLoginUser(); + if (User.isAdministrator(loginUser)) { + return Lists.immutable.empty(); } - @Override - protected ImmutableList listPredicate(Root root, CriteriaQuery query, CriteriaBuilder builder) { - User loginUser = userService.currentLoginUser(); - if (User.isAdministrator(loginUser)) { - return Lists.immutable.empty(); + Subquery confirmationSubquery = query.subquery(Confirmation.class); + Root confirmationRoot = confirmationSubquery.from(Confirmation.class); + confirmationSubquery.select(confirmationRoot) + .where( + builder.equal(confirmationRoot.get(Confirmation_.target), root), + EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser) + ); + + Subquery authenticationSubquery = query.subquery(Authentication.class); + Root authenticationRoot = authenticationSubquery.from(Authentication.class); + authenticationSubquery.select(authenticationRoot) + .where( + builder.equal(authenticationRoot.get(Authentication_.target), root), + EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) + ); + + return Lists.immutable.of(builder.or( + builder.equal(root.get(DataResource_.createdUser), loginUser), + builder.exists(confirmationSubquery), + builder.exists(authenticationSubquery) + )); + } + + public ImmutableList listNoConfirmation() { + return Lists.immutable.ofAll(dataResourceRepository.findAll( + (root, query, builder) -> { + Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); + return builder.and( + builder.isNull(confirmationJoin.get(Confirmation_.id)), + builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) + ); } + )); + } - Subquery confirmationSubquery = query.subquery(Confirmation.class); - Root confirmationRoot = confirmationSubquery.from(Confirmation.class); - confirmationSubquery.select(confirmationRoot) - .where( - builder.equal(confirmationRoot.get(Confirmation_.target), root), - EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser) - ); + public ImmutableList listNoAuthentication() { + return Lists.immutable.ofAll(dataResourceRepository.findAll( + (root, query, builder) -> { + Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); + confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL)); - Subquery authenticationSubquery = query.subquery(Authentication.class); - Root authenticationRoot = authenticationSubquery.from(Authentication.class); - authenticationSubquery.select(authenticationRoot) - .where( - builder.equal(authenticationRoot.get(Authentication_.target), root), - EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser) - ); + Subquery authenticationSubquery = query.subquery(Authentication.class); + Root authenticationRoot = authenticationSubquery.from(Authentication.class); + authenticationSubquery.select(authenticationRoot) + .where( + builder.equal(authenticationRoot.get(Authentication_.target), root), + builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser()) + ); + return builder.and( + builder.exists(authenticationSubquery).not(), + builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) + ); + } + )); + } - return Lists.immutable.of(builder.or( - builder.equal(root.get(DataResource_.createdUser), loginUser), - builder.exists(confirmationSubquery), - builder.exists(authenticationSubquery) - )); - } + public ImmutableList listNoWare() { + return Lists.immutable.ofAll(dataResourceRepository.findAll( + (root, query, builder) -> { + Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); + Join wareJoin = root.join(DataResource_.ware, JoinType.LEFT); + return builder.and( + builder.isNotNull(confirmationJoin), + builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL), + builder.isNull(wareJoin), + builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) + ); + } + )); + } - public ImmutableList listNoConfirmation() { - return Lists.immutable.ofAll(dataResourceRepository.findAll( - (root, query, builder) -> { - Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); - return builder.and( - builder.isNull(confirmationJoin.get(Confirmation_.id)), - builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) - ); - } - )); - } - - public ImmutableList listNoAuthentication() { - return Lists.immutable.ofAll(dataResourceRepository.findAll( - (root, query, builder) -> { - Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); - confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL)); - - Subquery authenticationSubquery = query.subquery(Authentication.class); - Root authenticationRoot = authenticationSubquery.from(Authentication.class); - authenticationSubquery.select(authenticationRoot) - .where( - builder.equal(authenticationRoot.get(Authentication_.target), root), - builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser()) - ); - return builder.and( - builder.exists(authenticationSubquery).not(), - builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) - ); - } - )); - } - - public ImmutableList listNoWare() { - return Lists.immutable.ofAll(dataResourceRepository.findAll( - (root, query, builder) -> { - Join confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT); - Join wareJoin = root.join(DataResource_.ware, JoinType.LEFT); - return builder.and( - builder.isNotNull(confirmationJoin), - builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL), - builder.isNull(wareJoin), - builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser()) - ); - } - )); - } - - @Override - public Long save(DataResource entity) { - ResourceType type = resourceTypeRepository.save(entity.getType()); - ResourceFormat format = resourceFormatRepository.save(entity.getFormat()); - entity.setType(type); - entity.setFormat(format); - return super.save(entity); - } + @Override + public Long save(DataResource entity) { + ResourceType type = resourceTypeRepository.save(entity.getType()); + ResourceFormat format = resourceFormatRepository.save(entity.getFormat()); + entity.setType(type); + entity.setFormat(format); + return super.save(entity); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/UserService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/UserService.java index b3e4546..57842d4 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/UserService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/UserService.java @@ -25,252 +25,252 @@ import org.springframework.transaction.annotation.Transactional; */ @Service public class UserService { - private static final Logger logger = LoggerFactory.getLogger(UserService.class); + private static final Logger logger = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; + private final UserRepository userRepository; - public UserService(UserRepository userRepository) { - this.userRepository = userRepository; + public UserService(UserRepository userRepository) { + this.userRepository = userRepository; + } + + private static String encryptPassword(String password) { + String salt = "tY2gNdkt7x%%HcCAFc"; + return SecureUtil.sha256(StrUtil.format("{}{}", salt, password)); + } + + /** + * 当数据库里没有用户的时候,增加一个默认的系统管理员 + */ + public void initial() { + if (userRepository.count() == 0) { + User user = new User(); + user.setUsername("administrator@eshore.com"); + user.setPassword(encryptPassword("administrator")); + user.setRole(User.Role.ADMINISTRATOR); + user.setState(User.State.NORMAL); + user.setCheckedUser(user); + user.setCheckedTime(LocalDateTime.now()); + user.setCreatedUser(user); + user.setModifiedUser(user); + userRepository.save(user); + } + } + + /** + * 获取当前登陆账号状态 + */ + public UserInformation state() { + try { + long id = StpUtil.getLoginIdAsLong(); + User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new); + // User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new); + StpUtil.login(user.getId()); + return new UserInformation(user, StpUtil.getTokenInfo()); + } catch (NotLoginException e) { + throw new LoginNotFoundException(e); + } + } + + public User currentLoginUser() { + return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new); + } + + public Optional currentLoginUserOptional() { + try { + return userRepository.findById(StpUtil.getLoginIdAsLong()); + } catch (Throwable throwable) { + return Optional.empty(); + } + } + + private User findUserByUsername(String username) { + return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new); + } + + /** + * 登陆操作 + */ + public UserInformation login(String username, String password) { + User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new); + if (user.getState() == User.State.CHECKING) { + throw new LoginFailureByCheckingException(); + } else if (user.getState() == User.State.DISABLED) { + throw new LoginFailureByDisabledException(); + } else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) { + throw new LoginFailureException(); + } else { + StpUtil.login(user.getId()); + user.setLastLoginTime(LocalDateTime.now()); + userRepository.save(user); + return new UserInformation(user, StpUtil.getTokenInfo()); + } + } + + /** + * 登出操作 + */ + public void logout() { + StpUtil.logout(); + } + + /** + * 注册操作 + */ + public void register(String username, String password, User.Role role) { + // 不允许通过这个入口注册管理员 + if (User.Role.ADMINISTRATOR.equals(role)) { + throw new RegisterFailureException(); + } + User user = new User(); + user.setUsername(username); + user.setPassword(encryptPassword(password)); + user.setRole(role); + user.setCreatedUser(user); + user.setModifiedUser(user); + userRepository.save(user); + } + + /** + * 管理员注册操作 + * 直接成功 + */ + public void registerFromAdministrator(String username, String password, User.Role role) { + User loginUser = currentLoginUser(); + User user = new User(); + user.setUsername(username); + user.setPassword(encryptPassword(password)); + user.setRole(role); + user.setState(User.State.NORMAL); + user.setCheckedUser(loginUser); + user.setCheckedTime(LocalDateTime.now()); + userRepository.save(user); + } + + /** + * 是否存在用户名 + */ + public boolean exitsUsername(String username) { + return userRepository.existsByUsername(username); + } + + /** + * 禁用账号 + */ + @Transactional + public void disable(String username) { + User loginUser = currentLoginUser(); + User user = findUserByUsername(username); + user.setState(User.State.DISABLED); + user.setModifiedUser(loginUser); + userRepository.save(user); + } + + /** + * 启用账号 + */ + @Transactional + public void enable(String username) { + User loginUser = currentLoginUser(); + User user = findUserByUsername(username); + user.setState(User.State.NORMAL); + user.setModifiedUser(loginUser); + userRepository.save(user); + } + + @Transactional + public void check(String username) { + User loginUser = currentLoginUser(); + User user = findUserByUsername(username); + user.setState(User.State.NORMAL); + user.setCheckedUser(loginUser); + user.setCheckedTime(LocalDateTime.now()); + user.setModifiedUser(loginUser); + userRepository.save(user); + } + + public ImmutableList list() { + return Lists.immutable.ofAll(userRepository.findAll()); + } + + @Transactional + public void changePassword(String oldPassword, String newPassword) { + long id = StpUtil.getLoginIdAsLong(); + User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new); + if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) { + user.setPassword(encryptPassword(newPassword)); + user.setModifiedUser(user); + userRepository.save(user); + } else { + throw new ChangePasswordFailureException(); + } + } + + public User detail(String username) { + return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new); + } + + public static class UserNotFoundException extends RuntimeException { + public UserNotFoundException() { + super("账号不存在"); + } + } + + public static class RegisterFailureException extends RuntimeException { + public RegisterFailureException() { + super("不允许注册的用户类型"); + } + } + + public static class LoginFailureException extends RuntimeException { + public LoginFailureException() { + super("邮箱或密码错误"); + } + } + + public static class LoginFailureByCheckingException extends RuntimeException { + public LoginFailureByCheckingException() { + super("账号正在审查中"); + } + } + + public static class LoginFailureByDisabledException extends RuntimeException { + public LoginFailureByDisabledException() { + super("账号已被禁用"); + } + } + + public static class LogoutFailureException extends RuntimeException { + public LogoutFailureException() { + super("账号登出失败"); + } + } + + public static class LoginNotFoundException extends RuntimeException { + public LoginNotFoundException() { + super("账号未登陆"); } - private static String encryptPassword(String password) { - String salt = "tY2gNdkt7x%%HcCAFc"; - return SecureUtil.sha256(StrUtil.format("{}{}", salt, password)); + public LoginNotFoundException(Exception exception) { + super("账号未登陆", exception); } + } - /** - * 当数据库里没有用户的时候,增加一个默认的系统管理员 - */ - public void initial() { - if (userRepository.count() == 0) { - User user = new User(); - user.setUsername("administrator@eshore.com"); - user.setPassword(encryptPassword("administrator")); - user.setRole(User.Role.ADMINISTRATOR); - user.setState(User.State.NORMAL); - user.setCheckedUser(user); - user.setCheckedTime(LocalDateTime.now()); - user.setCreatedUser(user); - user.setModifiedUser(user); - userRepository.save(user); - } + public static class ChangePasswordFailureException extends RuntimeException { + public ChangePasswordFailureException() { + super("原密码不正确"); } + } - /** - * 获取当前登陆账号状态 - */ - public UserInformation state() { - try { - long id = StpUtil.getLoginIdAsLong(); - User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new); - // User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new); - StpUtil.login(user.getId()); - return new UserInformation(user, StpUtil.getTokenInfo()); - } catch (NotLoginException e) { - throw new LoginNotFoundException(e); - } - } - - public User currentLoginUser() { - return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new); - } - - public Optional currentLoginUserOptional() { - try { - return userRepository.findById(StpUtil.getLoginIdAsLong()); - } catch (Throwable throwable) { - return Optional.empty(); - } - } - - private User findUserByUsername(String username) { - return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new); - } - - /** - * 登陆操作 - */ - public UserInformation login(String username, String password) { - User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new); - if (user.getState() == User.State.CHECKING) { - throw new LoginFailureByCheckingException(); - } else if (user.getState() == User.State.DISABLED) { - throw new LoginFailureByDisabledException(); - } else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) { - throw new LoginFailureException(); - } else { - StpUtil.login(user.getId()); - user.setLastLoginTime(LocalDateTime.now()); - userRepository.save(user); - return new UserInformation(user, StpUtil.getTokenInfo()); - } - } - - /** - * 登出操作 - */ - public void logout() { - StpUtil.logout(); - } - - /** - * 注册操作 - */ - public void register(String username, String password, User.Role role) { - // 不允许通过这个入口注册管理员 - if (User.Role.ADMINISTRATOR.equals(role)) { - throw new RegisterFailureException(); - } - User user = new User(); - user.setUsername(username); - user.setPassword(encryptPassword(password)); - user.setRole(role); - user.setCreatedUser(user); - user.setModifiedUser(user); - userRepository.save(user); - } - - /** - * 管理员注册操作 - * 直接成功 - */ - public void registerFromAdministrator(String username, String password, User.Role role) { - User loginUser = currentLoginUser(); - User user = new User(); - user.setUsername(username); - user.setPassword(encryptPassword(password)); - user.setRole(role); - user.setState(User.State.NORMAL); - user.setCheckedUser(loginUser); - user.setCheckedTime(LocalDateTime.now()); - userRepository.save(user); - } - - /** - * 是否存在用户名 - */ - public boolean exitsUsername(String username) { - return userRepository.existsByUsername(username); - } - - /** - * 禁用账号 - */ - @Transactional - public void disable(String username) { - User loginUser = currentLoginUser(); - User user = findUserByUsername(username); - user.setState(User.State.DISABLED); - user.setModifiedUser(loginUser); - userRepository.save(user); - } - - /** - * 启用账号 - */ - @Transactional - public void enable(String username) { - User loginUser = currentLoginUser(); - User user = findUserByUsername(username); - user.setState(User.State.NORMAL); - user.setModifiedUser(loginUser); - userRepository.save(user); - } - - @Transactional - public void check(String username) { - User loginUser = currentLoginUser(); - User user = findUserByUsername(username); - user.setState(User.State.NORMAL); - user.setCheckedUser(loginUser); - user.setCheckedTime(LocalDateTime.now()); - user.setModifiedUser(loginUser); - userRepository.save(user); - } - - public ImmutableList list() { - return Lists.immutable.ofAll(userRepository.findAll()); - } - - @Transactional - public void changePassword(String oldPassword, String newPassword) { - long id = StpUtil.getLoginIdAsLong(); - User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new); - if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) { - user.setPassword(encryptPassword(newPassword)); - user.setModifiedUser(user); - userRepository.save(user); - } else { - throw new ChangePasswordFailureException(); - } - } - - public User detail(String username) { - return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new); - } - - public static class UserNotFoundException extends RuntimeException { - public UserNotFoundException() { - super("账号不存在"); - } - } - - public static class RegisterFailureException extends RuntimeException { - public RegisterFailureException() { - super("不允许注册的用户类型"); - } - } - - public static class LoginFailureException extends RuntimeException { - public LoginFailureException() { - super("邮箱或密码错误"); - } - } - - public static class LoginFailureByCheckingException extends RuntimeException { - public LoginFailureByCheckingException() { - super("账号正在审查中"); - } - } - - public static class LoginFailureByDisabledException extends RuntimeException { - public LoginFailureByDisabledException() { - super("账号已被禁用"); - } - } - - public static class LogoutFailureException extends RuntimeException { - public LogoutFailureException() { - super("账号登出失败"); - } - } - - public static class LoginNotFoundException extends RuntimeException { - public LoginNotFoundException() { - super("账号未登陆"); - } - - public LoginNotFoundException(Exception exception) { - super("账号未登陆", exception); - } - } - - public static class ChangePasswordFailureException extends RuntimeException { - public ChangePasswordFailureException() { - super("原密码不正确"); - } - } - - @Data - public static class UserInformation { - private String username; - private User.Role role; - private String token; - - public UserInformation(User user, SaTokenInfo token) { - this.username = user.getUsername(); - this.role = user.getRole(); - this.token = token.getTokenValue(); - } + @Data + public static class UserInformation { + private String username; + private User.Role role; + private String token; + + public UserInformation(User user, SaTokenInfo token) { + this.username = user.getUsername(); + this.role = user.getRole(); + this.token = token.getTokenValue(); } + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/WareService.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/WareService.java index 1ebd1c7..f91b6b1 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/WareService.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/domain/service/WareService.java @@ -25,69 +25,69 @@ import org.springframework.stereotype.Service; @Slf4j @Service("com.eshore.gringotts.web.domain.service.WareService") public class WareService extends SimpleServiceSupport implements CheckingService { - private final WareRepository wareRepository; - private final CheckOrderService checkOrderService; - private final ObjectMapper mapper; + private final WareRepository wareRepository; + private final CheckOrderService checkOrderService; + private final ObjectMapper mapper; - public WareService(WareRepository repository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { - super(repository, userService); - this.wareRepository = repository; - this.checkOrderService = checkOrderService; - this.mapper = builder.build(); + public WareService(WareRepository repository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) { + super(repository, userService); + this.wareRepository = repository; + this.checkOrderService = checkOrderService; + this.mapper = builder.build(); + } + + public ImmutableList listPublic() { + return Lists.immutable.ofAll( + wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL)) + ); + } + + @Transactional(rollbackOn = Throwable.class) + @Override + public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { + if (StrUtil.equals(order.getKeyword(), "ware_check")) { + Long wareId = (Long) parameters.get("wareId"); + Ware ware = detailOrThrow(wareId); + switch (operation) { + case APPLY: + ware.setState(Ware.State.NORMAL); + order.setState(CheckOrder.State.OVER); + break; + case REJECT: + ware.setState(Ware.State.DRAFT); + order.setState(CheckOrder.State.OVER); + break; + } + save(ware); + checkOrderService.save(order); } + } - public ImmutableList listPublic() { - return Lists.immutable.ofAll( - wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL)) - ); - } + @Transactional(rollbackOn = Throwable.class) + public void submit(Long id) throws JsonProcessingException { + Ware ware = detailOrThrow(id); + ware.setState(Ware.State.CHECKING); + Long orderId = checkOrderService.save(new CheckOrder( + "ware_check", + StrUtil.format("数据资源「{}」的上架申请", ware.getName()), + CheckOrder.Type.MARKET, + mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())), + "com.eshore.gringotts.web.domain.service.WareService", + User.Role.CHECKER + )); + CheckOrder order = checkOrderService.detailOrThrow(orderId); + ware.setOrder(order); + save(ware); + } - @Transactional(rollbackOn = Throwable.class) - @Override - public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap parameters) { - if (StrUtil.equals(order.getKeyword(), "ware_check")) { - Long wareId = (Long) parameters.get("wareId"); - Ware ware = detailOrThrow(wareId); - switch (operation) { - case APPLY: - ware.setState(Ware.State.NORMAL); - order.setState(CheckOrder.State.OVER); - break; - case REJECT: - ware.setState(Ware.State.DRAFT); - order.setState(CheckOrder.State.OVER); - break; - } - save(ware); - checkOrderService.save(order); - } - } + @Transactional(rollbackOn = Throwable.class) + public void retract(Long id) { + Ware ware = detailOrThrow(id); + ware.setState(Ware.State.DRAFT); + save(ware); - @Transactional(rollbackOn = Throwable.class) - public void submit(Long id) throws JsonProcessingException { - Ware ware = detailOrThrow(id); - ware.setState(Ware.State.CHECKING); - Long orderId = checkOrderService.save(new CheckOrder( - "ware_check", - StrUtil.format("数据资源「{}」的上架申请", ware.getName()), - CheckOrder.Type.MARKET, - mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())), - "com.eshore.gringotts.web.domain.service.WareService", - User.Role.CHECKER - )); - CheckOrder order = checkOrderService.detailOrThrow(orderId); - ware.setOrder(order); - save(ware); - } - - @Transactional(rollbackOn = Throwable.class) - public void retract(Long id) { - Ware ware = detailOrThrow(id); - ware.setState(Ware.State.DRAFT); - save(ware); - - CheckOrder order = ware.getOrder(); - order.setState(CheckOrder.State.RETRACT); - checkOrderService.save(order); - } + CheckOrder order = ware.getOrder(); + order.setState(CheckOrder.State.RETRACT); + checkOrderService.save(order); + } } diff --git a/gringotts-web/src/main/java/com/eshore/gringotts/web/helper/EntityHelper.java b/gringotts-web/src/main/java/com/eshore/gringotts/web/helper/EntityHelper.java index f640156..3df6380 100644 --- a/gringotts-web/src/main/java/com/eshore/gringotts/web/helper/EntityHelper.java +++ b/gringotts-web/src/main/java/com/eshore/gringotts/web/helper/EntityHelper.java @@ -19,23 +19,23 @@ import org.springframework.data.jpa.repository.JpaRepository; * @date 2024-11-25 */ public class EntityHelper { - public static void deleteIfUpdateNeeded(JpaRepository repository, Supplier getter, E target) { - E old = getter.get(); - if (ObjectUtil.notEqual(old, target)) { - repository.delete(old); - } + public static void deleteIfUpdateNeeded(JpaRepository repository, Supplier getter, E target) { + E old = getter.get(); + if (ObjectUtil.notEqual(old, target)) { + repository.delete(old); } + } - public static Predicate checkNeededEntityPrediction(Root root, CriteriaBuilder builder, User loginUser) { - return builder.or( - builder.and( - builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE), - builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole()) - ), - builder.and( - builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER), - builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser) - ) - ); - } + public static Predicate checkNeededEntityPrediction(Root root, CriteriaBuilder builder, User loginUser) { + return builder.or( + builder.and( + builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE), + builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole()) + ), + builder.and( + builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER), + builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser) + ) + ); + } } diff --git a/gringotts-web/src/test/java/com/eshore/gringotts/web/TestQueryParse.java b/gringotts-web/src/test/java/com/eshore/gringotts/web/TestQueryParse.java index 962203a..df16d47 100644 --- a/gringotts-web/src/test/java/com/eshore/gringotts/web/TestQueryParse.java +++ b/gringotts-web/src/test/java/com/eshore/gringotts/web/TestQueryParse.java @@ -11,58 +11,58 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; * @date 2024-12-03 */ public class TestQueryParse { - public static void main(String[] args) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new EclipseCollectionsModule()); - mapper.registerModule(new JavaTimeModule()); - // language=JSON - System.out.println(mapper.readValue("{}", Query.class)); - // language=JSON - System.out.println(mapper.readValue("{\n" + - " \"query\": {\n" + - " \"equal\": {\n" + - " \"name\": \"lanyuanxiaoyao\"\n" + - " }\n" + - " }\n" + - "}", Query.class)); - // language=JSON - System.out.println(mapper.readValue("{\n" + - " \"query\": {\n" + - " \"equal\": {\n" + - " \"name\": \"lanyuanxiaoyao\"\n" + - " },\n" + - " \"notEqual\": {\n" + - " \"username\": \"lanyuanxiaoyao@qq.com\",\n" + - " \"password\": \"mingland87\"\n" + - " },\n" + - " \"great\": {\n" + - " \"age\": 12,\n" + - " \"createTime\": \"2020-10-12 00:00:00\"\n" + - " },\n" + - " \"in\": {\n" + - " \"age\": [\n" + - " 15,\n" + - " 18,\n" + - " 20\n" + - " ]\n" + - " },\n" + - " \"between\": {\n" + - " \"createTime\": {\n" + - " \"start\": \"2024-12-03 00:00:00\",\n" + - " \"end\": \"2024-12-03 00:00:00\"\n" + - " }\n" + - " }\n" + - " },\n" + - " \"sort\": [\n" + - " {\n" + - " \"column\": \"createTime\",\n" + - " \"direction\": \"ASC\"\n" + - " }\n" + - " ],\n" + - " \"page\": {\n" + - " \"size\": 10,\n" + - " \"page\": 1\n" + - " }\n" + - "}", Query.class)); - } + public static void main(String[] args) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new EclipseCollectionsModule()); + mapper.registerModule(new JavaTimeModule()); + // language=JSON + System.out.println(mapper.readValue("{}", Query.class)); + // language=JSON + System.out.println(mapper.readValue("{\n" + + " \"query\": {\n" + + " \"equal\": {\n" + + " \"name\": \"lanyuanxiaoyao\"\n" + + " }\n" + + " }\n" + + "}", Query.class)); + // language=JSON + System.out.println(mapper.readValue("{\n" + + " \"query\": {\n" + + " \"equal\": {\n" + + " \"name\": \"lanyuanxiaoyao\"\n" + + " },\n" + + " \"notEqual\": {\n" + + " \"username\": \"lanyuanxiaoyao@qq.com\",\n" + + " \"password\": \"mingland87\"\n" + + " },\n" + + " \"great\": {\n" + + " \"age\": 12,\n" + + " \"createTime\": \"2020-10-12 00:00:00\"\n" + + " },\n" + + " \"in\": {\n" + + " \"age\": [\n" + + " 15,\n" + + " 18,\n" + + " 20\n" + + " ]\n" + + " },\n" + + " \"between\": {\n" + + " \"createTime\": {\n" + + " \"start\": \"2024-12-03 00:00:00\",\n" + + " \"end\": \"2024-12-03 00:00:00\"\n" + + " }\n" + + " }\n" + + " },\n" + + " \"sort\": [\n" + + " {\n" + + " \"column\": \"createTime\",\n" + + " \"direction\": \"ASC\"\n" + + " }\n" + + " ],\n" + + " \"page\": {\n" + + " \"size\": 10,\n" + + " \"page\": 1\n" + + " }\n" + + "}", Query.class)); + } }