提交 c7abe26b 编写于 作者: ibizdev's avatar ibizdev

ibizdev提交

上级 cd7bdad7
*2020-4-29* ## v7.0.0-alpha.2 [2020-5-7]
### Bug修复
分页导航栏添加图标配置
### 功能新增及优化
#### 模板
表格文件上传信息显示
批添加、批删除
实体工作流动态视图
实体工作流动态导航表格视图
富文本信息模式
更新默认值
#### 基础文件
表格文件上传信息显示
实体工作流动态视图
实体工作流动态导航表格视图
## v7.0.0-alpha.1 [2020-4-29]
初始化文件 初始化文件
...@@ -26,94 +26,112 @@ const tinymceCode:any = tinymce; ...@@ -26,94 +26,112 @@ const tinymceCode:any = tinymce;
@Component({}) @Component({})
export default class AppRichTextEditor extends Vue { export default class AppRichTextEditor extends Vue {
/** /**
* 传入值 * 传入值
*
* @type {*}
* @memberof AppRichTextEditor
*/ */
@Prop() value?: any; @Prop() value?: any;
/**
* 监听value值
*/
@Watch('value', { immediate: true, deep: true })
oncurrentContent(newval: any, val: any) {
if (newval) {
if(this.editor){
tinymceCode.remove('#' + this.id);
}
this.init(newval);
}
}
/** /**
* 输入name * 输入name
*
* @type {string}
* @memberof AppRichTextEditor
*/ */
@Prop() name?: string; @Prop() name?: string;
/** /**
* 输入高度 * 输入高度
*
* @type {*}
* @memberof AppRichTextEditor
*/ */
@Prop() height?: any; @Prop() height?: any;
/** /**
* 是否禁用 * 是否禁用
*
* @type {boolean}
* @memberof AppRichTextEditor
*/ */
@Prop() disabled?: any; @Prop() disabled?: boolean;
/**
* 当前语言,默认中文
*/
public langu: any = localStorage.getItem('local') ? localStorage.getItem('local') : 'zh_CN' ;
/** /**
* 监听语言变化 * 表单状态
*/ *
@Watch('$i18n.locale') * @type {Subject<any>}
onLocaleChange(newval: any, val: any) { * @memberof AppRichTextEditor
console.log("语言变更"+newval)
this.langu = newval;
if(this.editor){
tinymceCode.remove('#' + this.id);
}
this.init('');
}
/**
* 语言映射文件
*/ */
public languMap:any = { @Prop() public formState?: Subject<any>;
'zh-CN': 'zh_CN',
'en-US': 'en_US',
};
/** /**
* 上传文件路径 * 上传文件路径
*
* @type {string}
* @memberof AppRichTextEditor
*/ */
public uploadUrl = Environment.BaseUrl + Environment.UploadFile; public uploadUrl = Environment.BaseUrl + Environment.UploadFile;
/** /**
* 下载路径 * 下载路径
*
* @type {string}
* @memberof AppRichTextEditor
*/ */
public downloadUrl = Environment.BaseUrl + Environment.ExportFile; public downloadUrl = Environment.BaseUrl + Environment.ExportFile;
/** /**
* 当前富文本 * 当前富文本
*
* @type {*}
* @memberof AppRichTextEditor
*/ */
public editor: any = null; public editor: any = null;
/** /**
* 当前富文本id * 当前富文本id
*
* @type {string}
* @memberof AppRichTextEditor
*/ */
id: string = this.$util.createUUID(); public id: string = this.$util.createUUID();
/** /**
* 表单状态 * 当前语言,默认中文
* *
* @type {Subject<any>} * @type {*}
* @memberof AppRichTextEditor * @memberof AppRichTextEditor
*/ */
@Prop() public formState?: Subject<any>; public langu: any = localStorage.getItem('local') ? localStorage.getItem('local') : 'zh_CN' ;
/**
* 语言映射文件
*
* @type {*}
* @memberof AppRichTextEditor
*/
public languMap:any = {
'zh-CN': 'zh_CN',
'en-US': 'en_US',
};
/**
* 是否处于激活状态
*
* @type {boolean}
* @memberof AppRichTextEditor
*/
public isActived:boolean = true;
/**
* 是否需要初始化
*
* @type {boolean}
* @memberof AppRichTextEditor
*/
public isNeedInit:boolean = false;
/** /**
* 生命周期 * 生命周期
...@@ -125,10 +143,7 @@ export default class AppRichTextEditor extends Vue { ...@@ -125,10 +143,7 @@ export default class AppRichTextEditor extends Vue {
this.formState.subscribe(({ type, data }) => { this.formState.subscribe(({ type, data }) => {
if (Object.is('load', type)) { if (Object.is('load', type)) {
if (!this.value) { if (!this.value) {
if(this.editor){ this.init();
tinymceCode.remove('#' + this.id);
}
this.init(this.value);
} }
} }
}); });
...@@ -136,29 +151,84 @@ export default class AppRichTextEditor extends Vue { ...@@ -136,29 +151,84 @@ export default class AppRichTextEditor extends Vue {
} }
/** /**
* 初始化富文本 * 生命周期:激活
*
* @memberof AppRichTextEditor
*/
public activated(){
this.isActived = true;
if(this.isNeedInit){
this.init();
this.isNeedInit = false;
}
}
/**
* 生命周期:缓存
*
* @memberof AppRichTextEditor
*/
public deactivated(){
this.isActived = false;
}
/**
* 生命周期:初始化富文本
*
* @memberof AppRichTextEditor
*/ */
public mounted() { public mounted() {
this.init(''); this.init();
} }
/** /**
* 销毁富文本 * 生命周期:销毁富文本
*
* @memberof AppRichTextEditor
*/ */
public destoryed(){ public destoryed(){
tinymceCode.remove(this.editor); if(this.editor){
tinymceCode.remove('#' + this.id);
}
}
/**
* 监听value值
*
* @memberof AppRichTextEditor
*/
@Watch('value', { immediate: true, deep: true })
oncurrentContent(newval: any, val: any) {
if (newval) {
this.init();
}
}
/**
* 监听语言变化
*/
@Watch('$i18n.locale')
onLocaleChange(newval: any, val: any) {
this.langu = newval;
if(this.isActived){
this.init();
}else{
this.isNeedInit = true;
}
} }
/** /**
* 初始化富文本 * 初始化富文本
* @param val *
* @memberof AppRichTextEditor
*/ */
public init(val: any) { public init() {
this.destoryed();
let richtexteditor = this; let richtexteditor = this;
tinymceCode.init({ tinymceCode.init({
selector: '#' + this.id, selector: '#' + richtexteditor.id,
width: 'calc( 100% - 2px )', width: 'calc( 100% - 2px )',
height: this.height, height: richtexteditor.height,
min_height: 400, min_height: 400,
branding: false, branding: false,
plugins: ['link', 'paste', 'table', 'image', 'codesample', 'code', 'fullscreen', 'preview'], plugins: ['link', 'paste', 'table', 'image', 'codesample', 'code', 'fullscreen', 'preview'],
...@@ -177,13 +247,13 @@ export default class AppRichTextEditor extends Vue { ...@@ -177,13 +247,13 @@ export default class AppRichTextEditor extends Vue {
paste_data_images: true, paste_data_images: true,
codesample_content_css: 'assets/tinymce/prism.css', codesample_content_css: 'assets/tinymce/prism.css',
skin_url: './assets/tinymce/skins/lightgray', skin_url: './assets/tinymce/skins/lightgray',
language_url: './assets/tinymce/langs/' + this.languMap[this.langu] + '.js', language_url: './assets/tinymce/langs/' + richtexteditor.languMap[richtexteditor.langu] + '.js',
language:this.languMap[this.langu], language:richtexteditor.languMap[richtexteditor.langu],
setup: (editor: any) => { setup: (editor: any) => {
this.editor = editor; richtexteditor.editor = editor;
editor.on('blur', () => { editor.on('blur', () => {
const content = editor.getContent(); const content = editor.getContent();
this.$emit('change', content); richtexteditor.$emit('change', content);
}); });
}, },
images_upload_handler: (bolbinfo: any, success: any, failure: any) => { images_upload_handler: (bolbinfo: any, success: any, failure: any) => {
...@@ -202,13 +272,13 @@ export default class AppRichTextEditor extends Vue { ...@@ -202,13 +272,13 @@ export default class AppRichTextEditor extends Vue {
}); });
}, },
init_instance_callback: (editor: any) => { init_instance_callback: (editor: any) => {
this.editor = editor; richtexteditor.editor = editor;
let value = (this.value && this.value.length > 0) ? this.value : ''; let value = (richtexteditor.value && richtexteditor.value.length > 0) ? richtexteditor.value : '';
if (this.editor) { if (richtexteditor.editor) {
this.editor.setContent(value); richtexteditor.editor.setContent(value);
} }
if (this.disabled) { if (richtexteditor.disabled) {
this.editor.setMode('readonly'); richtexteditor.editor.setMode('readonly');
} }
} }
}); });
...@@ -216,8 +286,10 @@ export default class AppRichTextEditor extends Vue { ...@@ -216,8 +286,10 @@ export default class AppRichTextEditor extends Vue {
/** /**
* 上传文件 * 上传文件
* @param url *
* @param formData * @param url 路径
* @param formData 文件对象
* @memberof AppRichTextEditor
*/ */
public uploadFile(url: string, formData: any) { public uploadFile(url: string, formData: any) {
let _this = this; let _this = this;
......
...@@ -209,51 +209,51 @@ ...@@ -209,51 +209,51 @@
/*** END:多数据视图属性布局 ***/ /*** END:多数据视图属性布局 ***/
// 看板视图,卡片模式 // 看板视图,卡片模式
.view-container.appportalview,.view-container.deportalview,.view-container.deportalview9{ // .view-container.appportalview,.view-container.deportalview,.view-container.deportalview9{
>.view-card>.ivu-card-body>.content-container{ // >.view-card>.ivu-card-body>.content-container{
background: #efefef; // background: #efefef;
} // }
.dashboard{ // .dashboard{
padding: 8px; // padding: 8px;
} // }
.portlet-container{ // .portlet-container{
background: #efefef; // background: #efefef;
} // }
.portlet-container::after{ // .portlet-container::after{
content: ""; // content: "";
clear: both; // clear: both;
} // }
.portlet{ // .portlet{
margin: 8px; // margin: 8px;
height: calc(100% - 16px); // height: calc(100% - 16px);
width: calc(100% - 16px); // width: calc(100% - 16px);
background: #fff; // background: #fff;
border-radius: 4px; // border-radius: 4px;
box-shadow: 0 1px 1px rgba(0,0,0,.05), 0 2px 6px 0 rgba(0,0,0,.045); // box-shadow: 0 1px 1px rgba(0,0,0,.05), 0 2px 6px 0 rgba(0,0,0,.045);
border: 1px solid transparent; // border: 1px solid transparent;
>.portlet-with-title{ // >.portlet-with-title{
margin-bottom: 12px; // margin-bottom: 12px;
height: calc(100% - 64px); // height: calc(100% - 64px);
} // }
>.portlet-without-title{ // >.portlet-without-title{
margin-top: 12px; // margin-top: 12px;
margin-bottom: 12px; // margin-bottom: 12px;
height: calc(100% - 24px); // height: calc(100% - 24px);
} // }
} // }
} // }
// 看板视图,无缝模式 // // 看板视图,无缝模式
.view-container.appportalview.seamless-mode,.view-container.deportalview.seamless-mode,.view-container.deportalview9.seamless-mode{ // .view-container.appportalview.seamless-mode,.view-container.deportalview.seamless-mode,.view-container.deportalview9.seamless-mode{
>.view-card>.ivu-card-body>.content-container{ // >.view-card>.ivu-card-body>.content-container{
background: transparent; // background: transparent;
} // }
.portlet-container{ // .portlet-container{
background: transparent; // background: transparent;
} // }
.portlet{ // .portlet{
background: transparent; // background: transparent;
} // }
} // }
@import './user.less'; @import './user.less';
\ No newline at end of file
...@@ -684,7 +684,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -684,7 +684,7 @@ export default class MainBase extends Vue implements ControlInterface {
* @memberof Main * @memberof Main
*/ */
private onFormLoad(data: any = {},action:string): void { private onFormLoad(data: any = {},action:string): void {
if(Object.is(action,"save") || Object.is(action,"autoSave")) if(Object.is(action,"save") || Object.is(action,"autoSave") || Object.is(action,"submit"))
// 更新context的实体主键 // 更新context的实体主键
if(data.wfgroup){ if(data.wfgroup){
Object.assign(this.context,{wfgroup:data.wfgroup}) Object.assign(this.context,{wfgroup:data.wfgroup})
...@@ -714,6 +714,9 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -714,6 +714,9 @@ export default class MainBase extends Vue implements ControlInterface {
if(Object.is(action,'loadDraft')){ if(Object.is(action,'loadDraft')){
this.createDefault(); this.createDefault();
} }
if(Object.is(action,'load')){
this.updateDefault();
}
this.$nextTick(function () { this.$nextTick(function () {
this.ignorefieldvaluechange = false; this.ignorefieldvaluechange = false;
}) })
...@@ -1257,9 +1260,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1257,9 +1260,7 @@ export default class MainBase extends Vue implements ControlInterface {
protected async wfstart(data: any,localdata?:any): Promise<any> { protected async wfstart(data: any,localdata?:any): Promise<any> {
return new Promise((resolve: any, reject: any) => { return new Promise((resolve: any, reject: any) => {
const _this: any = this; const _this: any = this;
const arg: any = data[0]; const post: Promise<any> = _this.save({},false);
Object.assign(arg,{viewparams:this.viewparams});
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
if(this.viewparams){ if(this.viewparams){
...@@ -1323,6 +1324,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1323,6 +1324,13 @@ export default class MainBase extends Vue implements ControlInterface {
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator); const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
// 保存完成UI处理
this.onFormLoad(arg,'save');
this.$emit('save', arg);
this.$nextTick(() => {
this.formState.next({ type: 'save', data: arg });
});
// 准备提交参数
if(this.viewparams){ if(this.viewparams){
Object.assign(arg,{viewparams:this.viewparams}); Object.assign(arg,{viewparams:this.viewparams});
} }
...@@ -1334,6 +1342,8 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1334,6 +1342,8 @@ export default class MainBase extends Vue implements ControlInterface {
} }
return; return;
} }
this.onFormLoad(arg,'submit');
this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
this.$Notice.info({ title: '', desc: '工作流提交成功' }); this.$Notice.info({ title: '', desc: '工作流提交成功' });
resolve(response); resolve(response);
}).catch((response: any) => { }).catch((response: any) => {
...@@ -1528,6 +1538,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1528,6 +1538,13 @@ export default class MainBase extends Vue implements ControlInterface {
public createDefault(){ public createDefault(){
} }
/**
* 更新默认值
* @memberof Main
*/
public updateDefault(){
}
} }
</script> </script>
......
...@@ -693,7 +693,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -693,7 +693,7 @@ export default class MainBase extends Vue implements ControlInterface {
* @memberof Main * @memberof Main
*/ */
private onFormLoad(data: any = {},action:string): void { private onFormLoad(data: any = {},action:string): void {
if(Object.is(action,"save") || Object.is(action,"autoSave")) if(Object.is(action,"save") || Object.is(action,"autoSave") || Object.is(action,"submit"))
// 更新context的实体主键 // 更新context的实体主键
if(data.wfmember){ if(data.wfmember){
Object.assign(this.context,{wfmember:data.wfmember}) Object.assign(this.context,{wfmember:data.wfmember})
...@@ -723,6 +723,9 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -723,6 +723,9 @@ export default class MainBase extends Vue implements ControlInterface {
if(Object.is(action,'loadDraft')){ if(Object.is(action,'loadDraft')){
this.createDefault(); this.createDefault();
} }
if(Object.is(action,'load')){
this.updateDefault();
}
this.$nextTick(function () { this.$nextTick(function () {
this.ignorefieldvaluechange = false; this.ignorefieldvaluechange = false;
}) })
...@@ -1266,9 +1269,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1266,9 +1269,7 @@ export default class MainBase extends Vue implements ControlInterface {
protected async wfstart(data: any,localdata?:any): Promise<any> { protected async wfstart(data: any,localdata?:any): Promise<any> {
return new Promise((resolve: any, reject: any) => { return new Promise((resolve: any, reject: any) => {
const _this: any = this; const _this: any = this;
const arg: any = data[0]; const post: Promise<any> = _this.save({},false);
Object.assign(arg,{viewparams:this.viewparams});
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
if(this.viewparams){ if(this.viewparams){
...@@ -1332,6 +1333,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1332,6 +1333,13 @@ export default class MainBase extends Vue implements ControlInterface {
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator); const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
// 保存完成UI处理
this.onFormLoad(arg,'save');
this.$emit('save', arg);
this.$nextTick(() => {
this.formState.next({ type: 'save', data: arg });
});
// 准备提交参数
if(this.viewparams){ if(this.viewparams){
Object.assign(arg,{viewparams:this.viewparams}); Object.assign(arg,{viewparams:this.viewparams});
} }
...@@ -1343,6 +1351,8 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1343,6 +1351,8 @@ export default class MainBase extends Vue implements ControlInterface {
} }
return; return;
} }
this.onFormLoad(arg,'submit');
this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
this.$Notice.info({ title: '', desc: '工作流提交成功' }); this.$Notice.info({ title: '', desc: '工作流提交成功' });
resolve(response); resolve(response);
}).catch((response: any) => { }).catch((response: any) => {
...@@ -1537,6 +1547,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1537,6 +1547,13 @@ export default class MainBase extends Vue implements ControlInterface {
public createDefault(){ public createDefault(){
} }
/**
* 更新默认值
* @memberof Main
*/
public updateDefault(){
}
} }
</script> </script>
......
...@@ -798,7 +798,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -798,7 +798,7 @@ export default class MainBase extends Vue implements ControlInterface {
* @memberof Main * @memberof Main
*/ */
private onFormLoad(data: any = {},action:string): void { private onFormLoad(data: any = {},action:string): void {
if(Object.is(action,"save") || Object.is(action,"autoSave")) if(Object.is(action,"save") || Object.is(action,"autoSave") || Object.is(action,"submit"))
// 更新context的实体主键 // 更新context的实体主键
if(data.wfprocessdefinition){ if(data.wfprocessdefinition){
Object.assign(this.context,{wfprocessdefinition:data.wfprocessdefinition}) Object.assign(this.context,{wfprocessdefinition:data.wfprocessdefinition})
...@@ -828,6 +828,9 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -828,6 +828,9 @@ export default class MainBase extends Vue implements ControlInterface {
if(Object.is(action,'loadDraft')){ if(Object.is(action,'loadDraft')){
this.createDefault(); this.createDefault();
} }
if(Object.is(action,'load')){
this.updateDefault();
}
this.$nextTick(function () { this.$nextTick(function () {
this.ignorefieldvaluechange = false; this.ignorefieldvaluechange = false;
}) })
...@@ -1371,9 +1374,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1371,9 +1374,7 @@ export default class MainBase extends Vue implements ControlInterface {
protected async wfstart(data: any,localdata?:any): Promise<any> { protected async wfstart(data: any,localdata?:any): Promise<any> {
return new Promise((resolve: any, reject: any) => { return new Promise((resolve: any, reject: any) => {
const _this: any = this; const _this: any = this;
const arg: any = data[0]; const post: Promise<any> = _this.save({},false);
Object.assign(arg,{viewparams:this.viewparams});
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
if(this.viewparams){ if(this.viewparams){
...@@ -1437,6 +1438,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1437,6 +1438,13 @@ export default class MainBase extends Vue implements ControlInterface {
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator); const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
// 保存完成UI处理
this.onFormLoad(arg,'save');
this.$emit('save', arg);
this.$nextTick(() => {
this.formState.next({ type: 'save', data: arg });
});
// 准备提交参数
if(this.viewparams){ if(this.viewparams){
Object.assign(arg,{viewparams:this.viewparams}); Object.assign(arg,{viewparams:this.viewparams});
} }
...@@ -1448,6 +1456,8 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1448,6 +1456,8 @@ export default class MainBase extends Vue implements ControlInterface {
} }
return; return;
} }
this.onFormLoad(arg,'submit');
this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
this.$Notice.info({ title: '', desc: '工作流提交成功' }); this.$Notice.info({ title: '', desc: '工作流提交成功' });
resolve(response); resolve(response);
}).catch((response: any) => { }).catch((response: any) => {
...@@ -1642,6 +1652,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1642,6 +1652,13 @@ export default class MainBase extends Vue implements ControlInterface {
public createDefault(){ public createDefault(){
} }
/**
* 更新默认值
* @memberof Main
*/
public updateDefault(){
}
} }
</script> </script>
......
...@@ -641,7 +641,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -641,7 +641,7 @@ export default class MainBase extends Vue implements ControlInterface {
* @memberof Main * @memberof Main
*/ */
private onFormLoad(data: any = {},action:string): void { private onFormLoad(data: any = {},action:string): void {
if(Object.is(action,"save") || Object.is(action,"autoSave")) if(Object.is(action,"save") || Object.is(action,"autoSave") || Object.is(action,"submit"))
// 更新context的实体主键 // 更新context的实体主键
if(data.wfuser){ if(data.wfuser){
Object.assign(this.context,{wfuser:data.wfuser}) Object.assign(this.context,{wfuser:data.wfuser})
...@@ -671,6 +671,9 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -671,6 +671,9 @@ export default class MainBase extends Vue implements ControlInterface {
if(Object.is(action,'loadDraft')){ if(Object.is(action,'loadDraft')){
this.createDefault(); this.createDefault();
} }
if(Object.is(action,'load')){
this.updateDefault();
}
this.$nextTick(function () { this.$nextTick(function () {
this.ignorefieldvaluechange = false; this.ignorefieldvaluechange = false;
}) })
...@@ -1214,9 +1217,7 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1214,9 +1217,7 @@ export default class MainBase extends Vue implements ControlInterface {
protected async wfstart(data: any,localdata?:any): Promise<any> { protected async wfstart(data: any,localdata?:any): Promise<any> {
return new Promise((resolve: any, reject: any) => { return new Promise((resolve: any, reject: any) => {
const _this: any = this; const _this: any = this;
const arg: any = data[0]; const post: Promise<any> = _this.save({},false);
Object.assign(arg,{viewparams:this.viewparams});
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
if(this.viewparams){ if(this.viewparams){
...@@ -1280,6 +1281,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1280,6 +1281,13 @@ export default class MainBase extends Vue implements ControlInterface {
const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator); const post: Promise<any> = Object.is(arg.srfuf, '1')?this.service.update(this.updateAction, JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator):this.service.add(this.createAction,JSON.parse(JSON.stringify(this.context)),arg, this.showBusyIndicator);
post.then((response:any) =>{ post.then((response:any) =>{
const arg:any = response.data; const arg:any = response.data;
// 保存完成UI处理
this.onFormLoad(arg,'save');
this.$emit('save', arg);
this.$nextTick(() => {
this.formState.next({ type: 'save', data: arg });
});
// 准备提交参数
if(this.viewparams){ if(this.viewparams){
Object.assign(arg,{viewparams:this.viewparams}); Object.assign(arg,{viewparams:this.viewparams});
} }
...@@ -1291,6 +1299,8 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1291,6 +1299,8 @@ export default class MainBase extends Vue implements ControlInterface {
} }
return; return;
} }
this.onFormLoad(arg,'submit');
this.$store.dispatch('viewaction/datasaved', { viewtag: this.viewtag });
this.$Notice.info({ title: '', desc: '工作流提交成功' }); this.$Notice.info({ title: '', desc: '工作流提交成功' });
resolve(response); resolve(response);
}).catch((response: any) => { }).catch((response: any) => {
...@@ -1485,6 +1495,13 @@ export default class MainBase extends Vue implements ControlInterface { ...@@ -1485,6 +1495,13 @@ export default class MainBase extends Vue implements ControlInterface {
public createDefault(){ public createDefault(){
} }
/**
* 更新默认值
* @memberof Main
*/
public updateDefault(){
}
} }
</script> </script>
......
...@@ -38,11 +38,6 @@ ...@@ -38,11 +38,6 @@
git clone -b master $para2 ibzwf/ git clone -b master $para2 ibzwf/
export NODE_OPTIONS=--max-old-space-size=4096 export NODE_OPTIONS=--max-old-space-size=4096
cd ibzwf/ cd ibzwf/
mvn clean package -Pweb
cd ibzwf-app/ibzwf-app-web
mvn -Pweb docker:build
mvn -Pweb docker:push
docker -H $para1 stack deploy --compose-file=src/main/docker/ibzwf-app-web.yaml ibzlab-rt --with-registry-auth
</command> </command>
</hudson.tasks.Shell> </hudson.tasks.Shell>
</builders> </builders>
......
...@@ -9,6 +9,6 @@ CMD echo "The application will start in ${IBZ_SLEEP}s..." && \ ...@@ -9,6 +9,6 @@ CMD echo "The application will start in ${IBZ_SLEEP}s..." && \
sleep ${IBZ_SLEEP} && \ sleep ${IBZ_SLEEP} && \
java ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom -jar /ibzwf-app-web.jar java ${JAVA_OPTS} -Djava.security.egd=file:/dev/./urandom -jar /ibzwf-app-web.jar
EXPOSE 30003 EXPOSE 8080
ADD ibzwf-app-web.jar /ibzwf-app-web.jar ADD ibzwf-app-web.jar /ibzwf-app-web.jar
...@@ -3,11 +3,9 @@ services: ...@@ -3,11 +3,9 @@ services:
ibzwf-app-web: ibzwf-app-web:
image: registry.cn-shanghai.aliyuncs.com/ibizsys/ibzwf-app-web:latest image: registry.cn-shanghai.aliyuncs.com/ibizsys/ibzwf-app-web:latest
ports: ports:
- "30003:30003" - "8080:8080"
networks: networks:
- agent_network - agent_network
environment:
SPRING_CLOUD_NACOS_DISCOVERY_IP: 172.16.180.237
deploy: deploy:
mode: replicated mode: replicated
replicas: 1 replicas: 1
......
server: server:
port: 30003 port: 8080
\ No newline at end of file \ No newline at end of file
server: server:
port: 30003 port: 8080
#zuul网关路由设置 #zuul网关路由设置
zuul: zuul:
......
...@@ -35,7 +35,7 @@ public class WFGroup extends EntityMP implements Serializable { ...@@ -35,7 +35,7 @@ public class WFGroup extends EntityMP implements Serializable {
/** /**
* 组标识 * 组标识
*/ */
@DEField(isKeyField=true) @DEField(name = "groupid" , isKeyField=true)
@TableId(value= "groupid",type=IdType.UUID) @TableId(value= "groupid",type=IdType.UUID)
@JSONField(name = "id") @JSONField(name = "id")
@JsonProperty("id") @JsonProperty("id")
...@@ -43,6 +43,7 @@ public class WFGroup extends EntityMP implements Serializable { ...@@ -43,6 +43,7 @@ public class WFGroup extends EntityMP implements Serializable {
/** /**
* 组名称 * 组名称
*/ */
@DEField(name = "groupname")
@TableField(value = "groupname") @TableField(value = "groupname")
@JSONField(name = "name") @JSONField(name = "name")
@JsonProperty("name") @JsonProperty("name")
......
...@@ -30,7 +30,7 @@ public class WFProcessInstance extends EntityClient implements Serializable { ...@@ -30,7 +30,7 @@ public class WFProcessInstance extends EntityClient implements Serializable {
/** /**
* 实例标识 * 实例标识
*/ */
@DEField(isKeyField=true) @DEField(name = "instanceid" , isKeyField=true)
@JSONField(name = "id") @JSONField(name = "id")
@JsonProperty("id") @JsonProperty("id")
private String id; private String id;
...@@ -38,6 +38,7 @@ public class WFProcessInstance extends EntityClient implements Serializable { ...@@ -38,6 +38,7 @@ public class WFProcessInstance extends EntityClient implements Serializable {
/** /**
* 实例名称 * 实例名称
*/ */
@DEField(name = "instancename")
@JSONField(name = "name") @JSONField(name = "name")
@JsonProperty("name") @JsonProperty("name")
private String name; private String name;
...@@ -45,6 +46,7 @@ public class WFProcessInstance extends EntityClient implements Serializable { ...@@ -45,6 +46,7 @@ public class WFProcessInstance extends EntityClient implements Serializable {
/** /**
* DefinitionKey * DefinitionKey
*/ */
@DEField(name = "definitionkey")
@JSONField(name = "processDefinitionKey") @JSONField(name = "processDefinitionKey")
@JsonProperty("processDefinitionKey") @JsonProperty("processDefinitionKey")
private String processdefinitionkey; private String processdefinitionkey;
...@@ -52,6 +54,7 @@ public class WFProcessInstance extends EntityClient implements Serializable { ...@@ -52,6 +54,7 @@ public class WFProcessInstance extends EntityClient implements Serializable {
/** /**
* 流程定义名称 * 流程定义名称
*/ */
@DEField(name = "definitionname")
@JSONField(name = "processDefinitionName") @JSONField(name = "processDefinitionName")
@JsonProperty("processDefinitionName") @JsonProperty("processDefinitionName")
private String processdefinitionname; private String processdefinitionname;
......
...@@ -30,7 +30,7 @@ public class WFProcessNode extends EntityClient implements Serializable { ...@@ -30,7 +30,7 @@ public class WFProcessNode extends EntityClient implements Serializable {
/** /**
* 节点标识 * 节点标识
*/ */
@DEField(isKeyField=true) @DEField(name = "nodeid" , isKeyField=true)
@JSONField(name = "userTaskId") @JSONField(name = "userTaskId")
@JsonProperty("userTaskId") @JsonProperty("userTaskId")
private String usertaskid; private String usertaskid;
...@@ -38,6 +38,7 @@ public class WFProcessNode extends EntityClient implements Serializable { ...@@ -38,6 +38,7 @@ public class WFProcessNode extends EntityClient implements Serializable {
/** /**
* 节点名称 * 节点名称
*/ */
@DEField(name = "nodename")
@JSONField(name = "userTaskName") @JSONField(name = "userTaskName")
@JsonProperty("userTaskName") @JsonProperty("userTaskName")
private String usertaskname; private String usertaskname;
...@@ -45,6 +46,7 @@ public class WFProcessNode extends EntityClient implements Serializable { ...@@ -45,6 +46,7 @@ public class WFProcessNode extends EntityClient implements Serializable {
/** /**
* DefinitionKey * DefinitionKey
*/ */
@DEField(name = "definitionkey")
@JSONField(name = "processDefinitionKey") @JSONField(name = "processDefinitionKey")
@JsonProperty("processDefinitionKey") @JsonProperty("processDefinitionKey")
private String processdefinitionkey; private String processdefinitionkey;
...@@ -52,6 +54,7 @@ public class WFProcessNode extends EntityClient implements Serializable { ...@@ -52,6 +54,7 @@ public class WFProcessNode extends EntityClient implements Serializable {
/** /**
* 流程定义名称 * 流程定义名称
*/ */
@DEField(name = "definitionname")
@JSONField(name = "processDefinitionName") @JSONField(name = "processDefinitionName")
@JsonProperty("processDefinitionName") @JsonProperty("processDefinitionName")
private String processdefinitionname; private String processdefinitionname;
......
...@@ -30,7 +30,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -30,7 +30,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* 任务标识 * 任务标识
*/ */
@DEField(isKeyField=true) @DEField(name = "taskid" , isKeyField=true)
@JSONField(name = "id") @JSONField(name = "id")
@JsonProperty("id") @JsonProperty("id")
private String id; private String id;
...@@ -38,6 +38,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -38,6 +38,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* 任务名称 * 任务名称
*/ */
@DEField(name = "taskname")
@JSONField(name = "name") @JSONField(name = "name")
@JsonProperty("name") @JsonProperty("name")
private String name; private String name;
...@@ -45,6 +46,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -45,6 +46,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* DefinitionKey * DefinitionKey
*/ */
@DEField(name = "definitionkey")
@JSONField(name = "processDefinitionKey") @JSONField(name = "processDefinitionKey")
@JsonProperty("processDefinitionKey") @JsonProperty("processDefinitionKey")
private String processdefinitionkey; private String processdefinitionkey;
...@@ -52,6 +54,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -52,6 +54,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* 实例标识 * 实例标识
*/ */
@DEField(name = "instanceid")
@JSONField(name = "processInstanceId") @JSONField(name = "processInstanceId")
@JsonProperty("processInstanceId") @JsonProperty("processInstanceId")
private String processinstanceid; private String processinstanceid;
...@@ -59,6 +62,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -59,6 +62,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* 业务键值 * 业务键值
*/ */
@DEField(name = "businesskey")
@JSONField(name = "processInstanceBusinessKey") @JSONField(name = "processInstanceBusinessKey")
@JsonProperty("processInstanceBusinessKey") @JsonProperty("processInstanceBusinessKey")
private String processinstancebusinesskey; private String processinstancebusinesskey;
...@@ -66,6 +70,7 @@ public class WFTask extends EntityClient implements Serializable { ...@@ -66,6 +70,7 @@ public class WFTask extends EntityClient implements Serializable {
/** /**
* TaskDefinitionKey * TaskDefinitionKey
*/ */
@DEField(name = "taskdefinitionkey")
@JSONField(name = "taskProcessDefinitionKey") @JSONField(name = "taskProcessDefinitionKey")
@JsonProperty("taskProcessDefinitionKey") @JsonProperty("taskProcessDefinitionKey")
private String taskprocessdefinitionkey; private String taskprocessdefinitionkey;
......
...@@ -30,7 +30,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -30,7 +30,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* 路径标识 * 路径标识
*/ */
@DEField(isKeyField=true) @DEField(name = "wayid" , isKeyField=true)
@JSONField(name = "sequenceFlowId") @JSONField(name = "sequenceFlowId")
@JsonProperty("sequenceFlowId") @JsonProperty("sequenceFlowId")
private String sequenceflowid; private String sequenceflowid;
...@@ -45,6 +45,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -45,6 +45,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* TaskDefinitionKey * TaskDefinitionKey
*/ */
@DEField(name = "taskdefinitionkey")
@JSONField(name = "taskProcessDefinitionKey") @JSONField(name = "taskProcessDefinitionKey")
@JsonProperty("taskProcessDefinitionKey") @JsonProperty("taskProcessDefinitionKey")
private String taskprocessdefinitionkey; private String taskprocessdefinitionkey;
...@@ -52,6 +53,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -52,6 +53,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* 实例标识 * 实例标识
*/ */
@DEField(name = "instanceid")
@JSONField(name = "processInstanceId") @JSONField(name = "processInstanceId")
@JsonProperty("processInstanceId") @JsonProperty("processInstanceId")
private String processinstanceid; private String processinstanceid;
...@@ -59,6 +61,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -59,6 +61,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* DefinitionKey * DefinitionKey
*/ */
@DEField(name = "definitionkey")
@JSONField(name = "processDefinitionKey") @JSONField(name = "processDefinitionKey")
@JsonProperty("processDefinitionKey") @JsonProperty("processDefinitionKey")
private String processdefinitionkey; private String processdefinitionkey;
...@@ -66,6 +69,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -66,6 +69,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* 业务键值 * 业务键值
*/ */
@DEField(name = "businesskey")
@JSONField(name = "processInstanceBusinessKey") @JSONField(name = "processInstanceBusinessKey")
@JsonProperty("processInstanceBusinessKey") @JsonProperty("processInstanceBusinessKey")
private String processinstancebusinesskey; private String processinstancebusinesskey;
...@@ -80,6 +84,7 @@ public class WFTaskWay extends EntityClient implements Serializable { ...@@ -80,6 +84,7 @@ public class WFTaskWay extends EntityClient implements Serializable {
/** /**
* 路径标识 * 路径标识
*/ */
@DEField(name = "wayname")
@JSONField(name = "sequenceFlowName") @JSONField(name = "sequenceFlowName")
@JsonProperty("sequenceFlowName") @JsonProperty("sequenceFlowName")
private String sequenceflowname; private String sequenceflowname;
......
...@@ -35,7 +35,7 @@ public class WFUser extends EntityMP implements Serializable { ...@@ -35,7 +35,7 @@ public class WFUser extends EntityMP implements Serializable {
/** /**
* 用户标识 * 用户标识
*/ */
@DEField(isKeyField=true) @DEField(name = "userid" , isKeyField=true)
@TableId(value= "userid",type=IdType.UUID) @TableId(value= "userid",type=IdType.UUID)
@JSONField(name = "id") @JSONField(name = "id")
@JsonProperty("id") @JsonProperty("id")
...@@ -43,6 +43,7 @@ public class WFUser extends EntityMP implements Serializable { ...@@ -43,6 +43,7 @@ public class WFUser extends EntityMP implements Serializable {
/** /**
* 用户全局名 * 用户全局名
*/ */
@DEField(name = "username")
@TableField(value = "username") @TableField(value = "username")
@JSONField(name = "firstname") @JSONField(name = "firstname")
@JsonProperty("firstname") @JsonProperty("firstname")
...@@ -50,6 +51,7 @@ public class WFUser extends EntityMP implements Serializable { ...@@ -50,6 +51,7 @@ public class WFUser extends EntityMP implements Serializable {
/** /**
* 用户名称 * 用户名称
*/ */
@DEField(name = "personname")
@TableField(value = "personname") @TableField(value = "personname")
@JSONField(name = "displayname") @JSONField(name = "displayname")
@JsonProperty("displayname") @JsonProperty("displayname")
......
...@@ -11,6 +11,11 @@ import java.lang.annotation.Target; ...@@ -11,6 +11,11 @@ import java.lang.annotation.Target;
@Target({ ElementType.FIELD}) @Target({ ElementType.FIELD})
public @interface DEField public @interface DEField
{ {
/**
* 属性名称
* @return
*/
String name() default "";
/** /**
* 是否为数据主键 * 是否为数据主键
* @return * @return
......
package cn.ibizlab.util.cache;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import cn.ibizlab.util.cache.cacheManager.CaffeineCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;
/**
* Caffeine缓存配置类
*/
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
@ConditionalOnProperty("ibiz.enableCaffeineCache")
public class CaffeineCacheConfig {
@Autowired
private CacheProperties cacheProperties;
@Autowired
private CaffeineCacheManager caffeineCacheManager;
@Bean
@Primary
public CacheManager cacheManager() {
String specification = cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(specification)) {
caffeineCacheManager.setCaffeineSpec(CaffeineSpec.parse(specification));
}
return caffeineCacheManager;
}
}
\ No newline at end of file
package cn.ibizlab.util.cache;
import com.alibaba.fastjson.parser.ParserConfig;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import cn.ibizlab.util.cache.cacheManager.LayeringCacheManager;
import cn.ibizlab.util.cache.redis.KryoRedisSerializer;
import cn.ibizlab.util.cache.redis.StringRedisSerializer;
import cn.ibizlab.util.enums.RedisChannelTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.util.StringUtils;
/**
* 缓存配置类
* 1级缓存为caffeine
* 2级缓存为redis
*/
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
@ConditionalOnProperty("ibiz.enableRedisCache")
public class RedisCacheConfig {
@Autowired
private RedisCacheWriter redisCacheWriter;
@Autowired
private RedisCacheConfiguration configuration;
@Autowired
LayeringCacheManager layeringCacheManager;
@Autowired
private CacheProperties cacheProperties;
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
return RedisCacheManager.create(connectionFactory);
}
@Bean
public RedisCacheWriter redisCacheWriter(RedisConnectionFactory connectionFactory){
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
return redisCacheWriter;
}
/**
* 重写Redis序列化方式,使用Json方式:
* 当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
* Spring Data JPA为我们提供了下面的Serializer:
* GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
* 在此我们将自己配置RedisTemplate并定义Serializer。
*
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
KryoRedisSerializer<Object> kryoRedisSerializer = new KryoRedisSerializer<>(Object.class);
redisTemplate.setValueSerializer(kryoRedisSerializer);// 设置值(value)的序列化采用KryoRedisSerializer。
redisTemplate.setHashValueSerializer(kryoRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
@Primary
public CacheManager cacheManager() {
setCaffeineCacheConfig(layeringCacheManager);//Caffeine缓存设置
layeringCacheManager.setRedisCacheWriter(redisCacheWriter);
layeringCacheManager.setRedisConfiguration(configuration);
return layeringCacheManager;
}
private void setCaffeineCacheConfig(LayeringCacheManager layeringCacheManager) {
String specification = cacheProperties.getCaffeine().getSpec();
if (StringUtils.hasText(specification)) {
layeringCacheManager.setCaffeineSpec(CaffeineSpec.parse(specification));
}
}
/**
* 监听redis指定频道
* @param redisConnectionFactory
* @param messageListener
* @return
*/
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListener) {
final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
container.addMessageListener(messageListener, RedisChannelTopic.REDIS_CACHE_DELETE_TOPIC.getChannelTopic());
container.addMessageListener(messageListener, RedisChannelTopic.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic());
return container;
}
}
\ No newline at end of file
package cn.ibizlab.util.cache.cache;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
/**
* 自定义的redis缓存
*/
public class CusRedisCache extends RedisCache {
public CusRedisCache(String name, RedisCacheWriter redisCacheWriter, RedisCacheConfiguration configuration) {
super(name, redisCacheWriter, configuration);
}
}
package cn.ibizlab.util.cache.cache;
import cn.ibizlab.util.cache.listener.RedisPublisher;
import cn.ibizlab.util.enums.RedisChannelTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.AbstractValueAdaptingCache;
import org.springframework.cache.support.NullValue;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisOperations;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* 缓存分层类
* 1级缓存为caffeine
* 2级缓存为redis
*/
public class LayeringCache extends AbstractValueAdaptingCache {
Logger logger = LoggerFactory.getLogger(LayeringCache.class);
/**
* 缓存的名称
*/
private final String name;
/**
* redis缓存
*/
private RedisCache redisCache;
/**
* Caffeine缓存
*/
private final CaffeineCache caffeineCache;
/**
* redis消息发布
*/
RedisOperations<? extends Object, ? extends Object> redisOperations;
public LayeringCache(String name ,RedisOperations redisOperations, com.github.benmanes.caffeine.cache.Cache<Object, Object> caffeineCache,
RedisCacheWriter redisCacheWriter, RedisCacheConfiguration configuration) {
super(true);
this.name = name;
this.redisCache = new CusRedisCache(name, redisCacheWriter, configuration);
this.caffeineCache = new CaffeineCache(name, caffeineCache, true);
this.redisOperations=redisOperations;
}
@Override
public String getName() {
return this.name;
}
@Override
public Object getNativeCache() {
return this;
}
@Override
public ValueWrapper get(Object key) {
// 查询一级缓存
ValueWrapper wrapper = caffeineCache.get(key);
logger.debug("查询一级缓存 key:{},value:{}", key,wrapper);
if (wrapper == null) {
// 查询二级缓存
wrapper = redisCache.get(key);
caffeineCache.put(key, wrapper == null ? null : wrapper.get());
logger.debug("查询二级缓存,并将数据放到一级缓存。 key:{}", key);
}
return wrapper;
}
@Override
public <T> T get(Object key, Class<T> type) {
// 查询一级缓存
T value = caffeineCache.get(key, type);
logger.debug("查询一级缓存 key:{}", key);
if (value == null) {
// 查询二级缓存
value = redisCache.get(key, type);
caffeineCache.put(key, value);
logger.debug("查询二级缓存,并将数据放到一级缓存。 key:{}", key);
}
return value;
}
@SuppressWarnings("unchecked")
@Override
public <T> T get(Object key, Callable<T> valueLoader) {
// 查询一级缓存,如果一级缓存没有值则调用getForSecondaryCache(k, valueLoader)查询二级缓存
T value = (T) caffeineCache.getNativeCache().get(key, k -> getSecondCache(k, valueLoader));
if(value==null) {
// 直接查询二级缓存
value = (T) getSecondCache(key, valueLoader);
}
if (value instanceof NullValue) {
return null;
}
return value;
}
@Override
public void put(Object key, Object value) {
caffeineCache.put(key, value);
redisCache.put(key, value);
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
caffeineCache.putIfAbsent(key, value);
return redisCache.putIfAbsent(key, value);
}
@Override
public void evict(Object key) {
redisCache.evict(key); //清除redis中的二级缓存
caffeineCache.evict(key);//清除本机一级缓存
Map<String, Object> message = new HashMap<>();
message.put("cacheName", name);
message.put("key", key);
RedisPublisher redisPublisher = new RedisPublisher(redisOperations, RedisChannelTopic.REDIS_CACHE_DELETE_TOPIC.getChannelTopic());// 创建redis发布者
redisPublisher.publisher(message);//发布消息,清除其它集群机器中的一级缓存
logger.debug(String.format("清除二级缓存数据[%s]", key));
}
@Override
public void clear() {
redisCache.clear(); //清除redis中的二级缓存
caffeineCache.clear();//清除本机一级缓存
Map<String, Object> message = new HashMap<>();
message.put("cacheName", name);
RedisPublisher redisPublisher = new RedisPublisher(redisOperations, RedisChannelTopic.REDIS_CACHE_CLEAR_TOPIC.getChannelTopic());// 创建redis发布者
redisPublisher.publisher(message);//发布消息,清除其它集群机器中的一级缓存
}
@Override
protected Object lookup(Object key) {
Object value = caffeineCache.get(key);
logger.debug("查询一级缓存 key:{}", key);
if (value == null) {
value = redisCache.get(key);
logger.debug("查询二级缓存 key:{}", key);
}
return value;
}
/**
* 查询二级缓存
* @param key
* @param valueLoader
* @return
*/
private <T> Object getSecondCache(Object key, Callable<T> valueLoader) {
T value = redisCache.get(key, valueLoader);
logger.debug("查询二级缓存 key:{}", key);
return toStoreValue(value);
}
/**
* 获取caffeine缓存
* @return
*/
public CaffeineCache getFirstCache() {
return this.caffeineCache;
}
}
package cn.ibizlab.util.cache.cacheManager;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* Caffeine本地缓存
*/
@Data
@Component
@ConditionalOnProperty("ibiz.enableCaffeineCache")
public class CaffeineCacheManager implements CacheManager {
private static final int DEFAULT_EXPIRE_AFTER_WRITE = 1;
private static final int DEFAULT_INITIAL_CAPACITY = 5;
private static final int DEFAULT_MAXIMUM_SIZE = 1_000;
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
/**
* 缓存默认设置
*/
private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
.expireAfterAccess(DEFAULT_EXPIRE_AFTER_WRITE, TimeUnit.HOURS)
.initialCapacity(DEFAULT_INITIAL_CAPACITY)
.maximumSize(DEFAULT_MAXIMUM_SIZE);
/**
* 获取缓存对象
* @param name
* @return
*/
@Override
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null) {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = createCache(name);
this.cacheMap.put(name, cache);
}
}
}
return cache;
}
/**
* 获取缓存名
* @return
*/
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
/**
* 创建缓存
* @param name
* @return
*/
protected Cache createCache(String name) {
return new CaffeineCache(name, this.cacheBuilder.build(), true);
}
/**
* 缓存配置[缓存容量大小、时长等]
* @param caffeineSpec
*/
public void setCaffeineSpec(CaffeineSpec caffeineSpec) {
Caffeine<Object, Object> cacheBuilder = Caffeine.from(caffeineSpec);
if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) {
this.cacheBuilder = cacheBuilder;
refreshKnownCaches();
}
}
/**
* 使用该CacheManager的当前状态重新创建已知的缓存。
*/
private void refreshKnownCaches() {
for (Map.Entry<String, Cache> entry : this.cacheMap.entrySet()) {
entry.setValue(createCache(entry.getKey()));
}
}
}
package cn.ibizlab.util.cache.cacheManager;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.CaffeineSpec;
import lombok.Data;
import cn.ibizlab.util.cache.cache.LayeringCache;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* 缓存分层类
* 1级缓存为caffeine
* 2级缓存为redis
*/
@Data
@Component
@ConditionalOnProperty("ibiz.enableRedisCache")
public class LayeringCacheManager implements CacheManager {
private static final int DEFAULT_EXPIRE_AFTER_WRITE = 1;
private static final int DEFAULT_INITIAL_CAPACITY = 5;
private static final int DEFAULT_MAXIMUM_SIZE = 1_000;
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<String, Cache>(16);
public RedisCacheWriter redisCacheWriter;
public RedisCacheConfiguration redisConfiguration;
public RedisOperations redisOperations;
/**
* 缓存默认设置
*/
private Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
.expireAfterAccess(DEFAULT_EXPIRE_AFTER_WRITE, TimeUnit.HOURS)
.initialCapacity(DEFAULT_INITIAL_CAPACITY)
.maximumSize(DEFAULT_MAXIMUM_SIZE);
public LayeringCacheManager(RedisTemplate<String, Object> redisTemplate) {
this.redisOperations=redisTemplate;
}
/**
* 获取缓存对象
* @param name
* @return
*/
@Override
public Cache getCache(String name) {
Cache cache = this.cacheMap.get(name);
if (cache == null) {
synchronized (this.cacheMap) {
cache = this.cacheMap.get(name);
if (cache == null) {
cache = createCache(name);
this.cacheMap.put(name, cache);
}
}
}
return cache;
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
protected Cache createCache(String name) {
return new LayeringCache(name,this.redisOperations ,this.cacheBuilder.build(),redisCacheWriter,redisConfiguration);
}
/**
* 使用该CacheManager的当前状态重新创建已知的缓存
*/
private void refreshKnownCaches() {
for (Map.Entry<String, Cache> entry : this.cacheMap.entrySet()) {
entry.setValue(createCache(entry.getKey()));
}
}
public void setCaffeineSpec(CaffeineSpec caffeineSpec) {
Caffeine<Object, Object> cacheBuilder = Caffeine.from(caffeineSpec);
if (!ObjectUtils.nullSafeEquals(this.cacheBuilder, cacheBuilder)) {
this.cacheBuilder = cacheBuilder;
refreshKnownCaches();
}
}
}
package cn.ibizlab.util.cache.listener; package cn.ibizlab.util.cache.listener;
import cn.ibizlab.util.cache.cache.LayeringCache;
import cn.ibizlab.util.enums.RedisChannelTopic; import cn.ibizlab.util.enums.RedisChannelTopic;
import cn.ibizlab.util.cache.layering.LayeringCache;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.Map; import java.util.Map;
/** /**
* redis消息的订阅者 * redis消息的订阅者
*/ */
@Profile("prod")
@Component @Component
@ConditionalOnProperty("ibiz.enableRedisCache")
public class RedisMessageListener extends MessageListenerAdapter { public class RedisMessageListener extends MessageListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger(RedisPublisher.class); private static final Logger logger = LoggerFactory.getLogger(RedisPublisher.class);
@Autowired @Autowired
...@@ -38,7 +41,7 @@ public class RedisMessageListener extends MessageListenerAdapter { ...@@ -38,7 +41,7 @@ public class RedisMessageListener extends MessageListenerAdapter {
map= (Map<String, Object>) result; map= (Map<String, Object>) result;
} }
if(StringUtils.isEmpty(map)|| (!map.containsKey("cacheName"))|| (!map.containsKey("key"))){ if(StringUtils.isEmpty(map)|| (!map.containsKey("cacheName"))|| (!map.containsKey("key"))){
logger.info("解析缓存数据失败,无法获取指定值!"); logger.debug("解析缓存数据失败,无法获取指定值!");
return ; return ;
} }
logger.debug("redis消息订阅者接收到频道【{}】发布的消息。消息内容:{}", channelTopic.getChannelTopicStr(), result.toString()); logger.debug("redis消息订阅者接收到频道【{}】发布的消息。消息内容:{}", channelTopic.getChannelTopicStr(), result.toString());
......
...@@ -10,6 +10,7 @@ import org.springframework.cglib.beans.BeanMap; ...@@ -10,6 +10,7 @@ import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.util.AlternativeJdkIdGenerator; import org.springframework.util.AlternativeJdkIdGenerator;
import java.io.Serializable; import java.io.Serializable;
import org.springframework.util.StringUtils;
import java.util.*; import java.util.*;
public class EntityBase implements Serializable { public class EntityBase implements Serializable {
...@@ -68,14 +69,11 @@ public class EntityBase implements Serializable { ...@@ -68,14 +69,11 @@ public class EntityBase implements Serializable {
public Object get(String field) { public Object get(String field) {
field=field.toLowerCase(); String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
Hashtable<String,String> keys=DEFieldCacheMap.getFieldKeys(this.getClass().getName()); if(!StringUtils.isEmpty(fieldRealName))
if(keys.containsKey(field)) return getMap().get(fieldRealName);
return getMap().get(keys.get(field));
else if(keys.containsKey(field.replace("_","")))
return getMap().get(keys.get(field.replace("_","")));
else else
return this.extensionparams.get(field); return this.extensionparams.get(field.toLowerCase());
} }
...@@ -87,13 +85,15 @@ public class EntityBase implements Serializable { ...@@ -87,13 +85,15 @@ public class EntityBase implements Serializable {
@JsonAnySetter @JsonAnySetter
public void set(String field, Object value) { public void set(String field, Object value) {
field=field.toLowerCase(); field=field.toLowerCase();
Hashtable<String,String> keys=DEFieldCacheMap.getFieldKeys(this.getClass().getName()); String fieldRealName=DEFieldCacheMap.getFieldRealName(this.getClass(),field);
if(keys.containsKey(field)) if(!StringUtils.isEmpty(fieldRealName)) {
getMap().put(keys.get(field),value); if (value == null)
else if(keys.containsKey(field.replace("_",""))) getMap().put(fieldRealName, null);
getMap().put(keys.get(field.replace("_","")),value); else
getMap().put(fieldRealName, DEFieldCacheMap.fieldValueOf(this.getClass(), fieldRealName, value));
}
else else
this.extensionparams.put(field,value); this.extensionparams.put(field.toLowerCase(),value);
} }
} }
\ No newline at end of file
package cn.ibizlab.util.filter; package cn.ibizlab.util.filter;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
...@@ -9,6 +10,8 @@ import lombok.extern.slf4j.Slf4j; ...@@ -9,6 +10,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
...@@ -48,13 +51,15 @@ public class QueryWrapperContext<T> extends SearchContextBase implements ISearch ...@@ -48,13 +51,15 @@ public class QueryWrapperContext<T> extends SearchContextBase implements ISearch
if(ObjectUtils.isEmpty(it_sort)) if(ObjectUtils.isEmpty(it_sort))
return page; return page;
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
Class<T> type = (Class<T>)parameterizedType.getActualTypeArguments()[0];
while (it_sort.hasNext()) { while (it_sort.hasNext()) {
Sort.Order sort_order = it_sort.next(); Sort.Order sort_order = it_sort.next();
if(sort_order.getDirection()== Sort.Direction.ASC){ if(sort_order.getDirection()== Sort.Direction.ASC){
asc_fieldList.add(sort_order.getProperty()); asc_fieldList.add(DEFieldCacheMap.getFieldColumnName(type,sort_order.getProperty()));
} }
else if(sort_order.getDirection()== Sort.Direction.DESC){ else if(sort_order.getDirection()== Sort.Direction.DESC){
desc_fieldList.add(sort_order.getProperty()); desc_fieldList.add(DEFieldCacheMap.getFieldColumnName(type,sort_order.getProperty()));
} }
} }
......
package cn.ibizlab.util.helper; package cn.ibizlab.util.helper;
import cn.ibizlab.util.annotation.DEField;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Iterator;
import java.util.List; import java.util.List;
/** /**
...@@ -17,103 +20,138 @@ public class DEFieldCacheMap { ...@@ -17,103 +20,138 @@ public class DEFieldCacheMap {
private static Hashtable<String, Hashtable<String,String>> cacheKey = new Hashtable<>(); private static Hashtable<String, Hashtable<String,String>> cacheKey = new Hashtable<>();
private static Object objLock1=new Object(); private static Object objLock1=new Object();
private static Object objLock2=new Object();
private static Object objLock3=new Object();
/** /**
* 将实体对象中的属性存入缓存中 * 将实体对象中的属性存入缓存中
* @param className * @param
* @return * @return
*/ */
public static Hashtable<String,Field> getFieldMap(String className) { public static <T> Hashtable<String,Field> getFieldMap(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) if(className.indexOf("_$")>0)
className=className.substring(0, className.lastIndexOf("_$")); className=className.substring(0, className.lastIndexOf("_$"));
if(cacheMap.containsKey(className)) if(cacheMap.containsKey(className))
return cacheMap.get(className); return cacheMap.get(className);
synchronized (objLock1) { synchronized (objLock1) {
if(cacheMap.containsKey(className)) if(cacheMap.containsKey(className))
return cacheMap.get(className); return cacheMap.get(className);
Hashtable<String,Field> result = new Hashtable<String,Field>();
List<Field> list=new ArrayList<Field>();
Hashtable<String,String> keys=new Hashtable<String,String>();
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields){
result.put(field.getName(),field);
list.add(field);
keys.put(field.getName().toLowerCase(),field.getName());
}
cacheMap.put(className, result);
cacheList.put(className,list);
cacheKey.put(className,keys);
return result;
}
}
public static Hashtable<String,Field> getFieldMap(String className) {
if(className.indexOf("_$")>0)
className=className.substring(0, className.lastIndexOf("_$"));
if(cacheMap.containsKey(className))
return cacheMap.get(className);
Class clazz = null; Class clazz = null;
try { try {
clazz = Class.forName(className); clazz = Class.forName(className);
return getFieldMap(clazz);
} }
catch (Exception ex) { catch (Exception ex) {
cacheMap.put(className, new Hashtable<String,Field>()); cacheMap.put(className, new Hashtable<String,Field>());
return cacheMap.get(className); return cacheMap.get(className);
} }
Hashtable<String,Field> result = cacheMap.get(className);
if (result == null) {
result=new Hashtable<String,Field>();
Field[] fields=clazz.getDeclaredFields();
for(Field field:fields){
result.put(field.getName(),field);
}
cacheMap.put(className, result);
}
return result;
}
} }
/** /**
* 从缓存中查询实体对象属性列表 * 从缓存中查询实体对象属性列表
* @param className * @param
* @return * @return
*/ */
public static List<Field> getFields(String className) { public static <T> List<Field> getFields(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) if(className.indexOf("_$")>0)
className=className.substring(0, className.lastIndexOf("_$")); className=className.substring(0, className.lastIndexOf("_$"));
if(cacheList.containsKey(className)) if(cacheList.containsKey(className))
return cacheList.get(className); return cacheList.get(className);
else{
synchronized (objLock2) { DEFieldCacheMap.getFieldMap(clazz);
if (cacheList.containsKey(className))
return cacheList.get(className); return cacheList.get(className);
Hashtable<String,Field> fieldmap=DEFieldCacheMap.getFieldMap(className);
Iterator it = fieldmap.keySet().iterator();
List<Field> list=new ArrayList<Field>();
while(it.hasNext()) {
Object key = it.next();
if(fieldmap.get(key.toString())!=null)
list.add(fieldmap.get(key.toString()));
} }
cacheList.put(className,list); }
return list;
public static List<Field> getFields(String className) {
if(className.indexOf("_$")>0)
className=className.substring(0, className.lastIndexOf("_$"));
if(cacheList.containsKey(className))
return cacheList.get(className);
else{
DEFieldCacheMap.getFieldMap(className);
return cacheList.get(className);
} }
} }
/** /**
* 从缓存中查询实体对象属性列表 * 从缓存中查询实体对象属性列表
* @param className * @param
* @return * @return
*/ */
public static Hashtable<String,String> getFieldKeys(String className) { public static <T> Hashtable<String,String> getFieldKeys(Class<T> clazz) {
String className=clazz.getName();
if(className.indexOf("_$")>0) if(className.indexOf("_$")>0)
className=className.substring(0, className.lastIndexOf("_$")); className=className.substring(0, className.lastIndexOf("_$"));
if(cacheKey.containsKey(className)) if(cacheKey.containsKey(className))
return cacheKey.get(className); return cacheKey.get(className);
else{
synchronized (objLock3) { DEFieldCacheMap.getFieldMap(clazz);
if (cacheKey.containsKey(className))
return cacheKey.get(className); return cacheKey.get(className);
Hashtable<String,Field> fieldmap=DEFieldCacheMap.getFieldMap(className);
Iterator it = fieldmap.keySet().iterator();
Hashtable<String,String> list=new Hashtable<String,String>();
while(it.hasNext()) {
Object key = it.next();
list.put(key.toString().toLowerCase(),key.toString());
} }
cacheKey.put(className,list);
return list;
} }
public static <T> String getFieldRealName(Class<T> clazz,String fieldname) {
fieldname=fieldname.toLowerCase();
Hashtable<String,String> keys=DEFieldCacheMap.getFieldKeys(clazz);
if(keys.containsKey(fieldname))
return keys.get(fieldname);
else if(keys.containsKey(fieldname.replace("_","")))
return keys.get(fieldname.replace("_",""));
else
return "";
}
public static <T> Field getField(Class<T> clazz,String fieldname) {
String fieldRealName=DEFieldCacheMap.getFieldRealName(clazz,fieldname);
if(!StringUtils.isEmpty(fieldRealName))
return DEFieldCacheMap.getFieldMap(clazz).get(fieldRealName);
else
return null;
}
public static <T> String getFieldColumnName(Class<T> clazz,String fieldname) {
Field field = DEFieldCacheMap.getField(clazz,fieldname);
if(field!=null) {
DEField deField=field.getAnnotation(DEField.class);
if(deField!=null&&deField.name()!=null)
return deField.name();
}
return fieldname;
} }
public static <T> Object fieldValueOf(Class<T> clazz,String fieldname,Object fieldValue) {
if(fieldValue==null)
return null;
Object resultValue=fieldValue;
Field field = DEFieldCacheMap.getField(clazz,fieldname);
if(field!=null) {
Class<?> type=field.getType();
resultValue = DataObject.objectValueOf(type,fieldValue);
}
return resultValue;
}
} }
\ No newline at end of file
package cn.ibizlab.util.helper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DataObject {
final static public DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final static public DateFormat datetimeFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
final static public DateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
final static public String getStringValue(Object objValue, String strDefault) {
if (objValue == null) return strDefault;
if (objValue instanceof String) return (String) objValue;
if (objValue instanceof java.sql.Timestamp||objValue instanceof java.sql.Date||objValue instanceof java.util.Date) {
String rt=datetimeFormat.format(objValue);
if(rt.endsWith(" 00:00:00"))
rt=dayFormat.format(objValue);
else if(rt.endsWith(":00"))
rt=datetimeFormat2.format(objValue);
return rt;
}
return objValue.toString();
}
public static <T> Object objectValueOf(Class<T> type,Object fieldValue) {
if(fieldValue==null)
return null;
Object resultValue=fieldValue;
String targetType=type.getSimpleName();
if(targetType.equalsIgnoreCase(fieldValue.getClass().getSimpleName()))
return resultValue;
if(targetType.equals("Boolean")){
resultValue=getBooleanValue(fieldValue,false);
}
else if(targetType.equals("Character")){
resultValue=getCharacterValue(fieldValue,null);
}
else if(targetType.equals("Byte")){
resultValue=getBinaryValue(fieldValue,null);
}
else if(targetType.equals("Short")){
resultValue=Short.valueOf(fieldValue.toString());
}
else if(targetType.equals("Integer")){
resultValue= getIntegerValue(fieldValue,null);
}
else if(targetType.equals("Long")){
resultValue=getLongValue(fieldValue,null);
}
else if(targetType.equals("Float")){
resultValue= getFloatValue(fieldValue,null);
}
else if(targetType.equals("Double")){
resultValue= getDoubleValue(fieldValue,null);
}
else if(targetType.equals("BigDecimal")){
resultValue= getBigDecimalValue(fieldValue,null);
}
else if(targetType.equals("BigInteger")){
resultValue= getBigIntegerValue(fieldValue,null);
}
else if(targetType.equals("Timestamp")){
resultValue= getTimestampValue(fieldValue,null);
}
else if(targetType.equals("String")) {
resultValue= getStringValue(fieldValue,null);
}
if(resultValue==null)
return null;
return resultValue;
}
public static <T> T valueOf(Class<T> type,Object fieldValue) {
return (T)objectValueOf(type,fieldValue);
}
final static public JSONObject getJSONObjectValue(Object objValue, JSONObject jDefault) {
if (objValue == null) {
return jDefault;
}
if(objValue instanceof JSONObject)
return (JSONObject)objValue;
String strValue = objValue.toString();
try {
return JSONObject.parseObject(strValue);
}
catch (Exception ex)
{
return jDefault;
}
}
final static public JSONArray getJSONArrayValue(Object objValue, JSONArray jDefault) {
if (objValue == null) {
return jDefault;
}
if(objValue instanceof JSONArray)
return (JSONArray)objValue;
String strValue = objValue.toString();
try {
return JSONArray.parseArray(strValue);
}
catch (Exception ex)
{
return jDefault;
}
}
final static public List<String> getListValue(Object objValue) {
if (objValue == null) {
return new ArrayList<String>();
}
JSONArray arr=(getJSONArrayValue(objValue,null));
if(arr!=null)
{
List<String> chk1=new ArrayList<>();
for(int i=0;i<arr.size();i++)
{
if(arr.get(i) instanceof String)
chk1.add(arr.getString(i));
}
return chk1;
}
else
{
return new ArrayList<String>();
}
}
final static public Boolean getBooleanValue(Object objValue,Boolean bDefault) {
if (objValue == null) return bDefault;
if (objValue instanceof Boolean) {
return (Boolean) objValue;
}
return objValue.toString().equalsIgnoreCase("true")||objValue.toString().equals("1")||objValue.toString().equals("y");
}
final static public char[] getCharacterValue(Object objValue,char[] cDefault) {
if (objValue == null) return cDefault;
return objValue.toString().toCharArray();
}
final static public Double getDoubleValue(Object objValue,Double dDefault) {
if (objValue == null) return dDefault;
if (objValue instanceof Double) {
return (Double) objValue;
}
String strValue = objValue.toString();
if (StringUtils.isEmpty(strValue)) return null;
strValue = strValue.replace(",", "");
return Double.parseDouble(strValue);
}
final static public int getIntegerValue( Object objValue, Integer nDefault) {
if (objValue == null) {
return nDefault;
}
if(objValue instanceof Integer)
return (Integer)objValue;
if (objValue instanceof Double) {
return ((Double) objValue).intValue();
}
if (objValue instanceof BigDecimal) {
return ((BigDecimal) objValue).intValue();
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue))
return nDefault;
strValue = strValue.replace(",", "");
return Integer.parseInt(strValue);
}
final static public Float getFloatValue( Object objValue, Float fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof Float)
return (Float)objValue;
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue))
return fDefault;
strValue = strValue.replace(",", "");
return Float.parseFloat(strValue);
} catch (Exception ex) {
return fDefault;
}
}
final static public BigDecimal getBigDecimalValue( Object objValue, BigDecimal fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof BigDecimal){
return (BigDecimal)(objValue);
}
if(objValue instanceof Double){
return BigDecimal.valueOf((Double)objValue);
}
if(objValue instanceof Long){
return BigDecimal.valueOf((Long)objValue);
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue))
return fDefault;
strValue = strValue.replace(",", "");
return BigDecimal.valueOf(Double.parseDouble(strValue));
} catch (Exception ex) {
return fDefault;
}
}
final static public BigInteger getBigIntegerValue( Object objValue, BigInteger fDefault) {
if (objValue == null) {
return fDefault;
}
try {
if(objValue instanceof BigInteger){
return (BigInteger)(objValue);
}
else {
Long l=getLongValue(objValue,null);
if(l!=null)
return BigInteger.valueOf(l);
}
} catch (Exception ex) {
}
return fDefault;
}
final static public Long getLongValue( Object objValue, Long nDefault) {
if (objValue == null) {
return nDefault;
}
try {
if (objValue instanceof Long) return (Long) objValue;
if (objValue instanceof Integer) {
return ((Integer) objValue).longValue();
}
if (objValue instanceof Double) {
return ((Double) objValue).longValue();
}
if (objValue instanceof BigDecimal) {
return ((BigDecimal) objValue).longValue();
}
String strValue = objValue.toString();
if(StringUtils.isEmpty(strValue))
return nDefault;
strValue = strValue.replace(",", "");
return Long.parseLong(strValue);
} catch (Exception ex) {
return nDefault;
}
}
final static public byte[] getBinaryValue(Object objValue, byte[] def) {
if (objValue == null) return def;
if(objValue instanceof byte[]){
return (byte[])objValue;
}
if (objValue instanceof String){
return Base64.getDecoder().decode((String) objValue);
}
return def;
}
/**
* 转换对象值到时间值
*
* @param objValue
* @return
* @
*/
final static public java.sql.Timestamp getTimestampValue(Object objValue,java.sql.Timestamp tDefault) {
if (objValue == null) return tDefault;
if (objValue instanceof java.sql.Timestamp) {
java.sql.Timestamp ti = (java.sql.Timestamp) objValue;
return ti;
}
if (objValue instanceof java.sql.Date) {
java.sql.Date date = (java.sql.Date) objValue;
return new java.sql.Timestamp(date.getTime());
}
if (objValue instanceof java.util.Date) {
java.util.Date date = (java.util.Date) objValue;
return new java.sql.Timestamp(date.getTime());
}
if (objValue instanceof String) {
String strValue = (String) objValue;
strValue = strValue.trim();
if (StringUtils.isEmpty(strValue)) return null;
try {
java.util.Date date = parse((String) objValue);
return new java.sql.Timestamp(date.getTime());
}
catch (Exception ex)
{
return tDefault;
}
}
if(objValue instanceof Long)
{
Long lValue = (Long)objValue;
return new java.sql.Timestamp(lValue);
}
if(objValue instanceof Integer)
{
int lValue = (int)objValue;
return new java.sql.Timestamp(lValue);
}
return tDefault;
}
public static Object testDateTime(String strInput) throws Exception{
return testDateTime(strInput, null);
}
/**
* 转换文本值到日期时间
*
* @param strInput
* @param timeZone
* @return
* @
*/
public static Object testDateTime(String strInput, TimeZone timeZone) throws Exception{
if (StringUtils.isEmpty(strInput)) return null;
Date dtDate = parse(strInput, timeZone);
java.sql.Timestamp retDate = new java.sql.Timestamp(dtDate.getTime());
return retDate;
}
/**
* 转换字符串到时间对象
*
* @param strTimeString
* @return
* @throws ParseException
* @
*/
public static Date parse(String strTimeString) throws ParseException, Exception {
return parse(strTimeString, null);
}
/**
* 分析时间串
*
* @param strTimeString MM/dd/yy yy-MM-dd HH:mm:ss 格式
* @param timeZone
* @return
* @throws ParseException
* @
*/
public static Date parse(String strTimeString, TimeZone timeZone) throws ParseException, Exception {
strTimeString = strTimeString.trim();
if(StringUtils.isEmpty(strTimeString)){
throw new Exception("unknown date(time) string");
}
if(strTimeString.indexOf("Z")!=-1){
//有时区
String[] parts = strTimeString.split("[Z]");
if(parts.length>=1){
strTimeString = parts[0];
}
if(parts.length>=2){
if(timeZone == null){
if(!StringUtils.isEmpty(parts[1])){
timeZone = TimeZone.getTimeZone(parts[1]);
}
}
}
}
// 判断是长数据还是短数据
String strPart[] = null;
if(strTimeString.indexOf("T")!=-1){
strPart = strTimeString.split("[T]");
}
else
strPart = strTimeString.split(" ");
if (strPart.length == 2) {
// 两个部分
String strDate = "";
String strTime = "";
if (strPart[0].indexOf(":") != -1) {
strTime = strPart[0];
strDate = strPart[1];
} else {
strTime = strPart[1];
strDate = strPart[0];
}
strDate = strDate.trim();
strTime = strTime.trim();
strDate = getFormatDateString(strDate);
strTime = getFormatTimeString(strTime);
DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strDate + " " + strTime);
} else {
// 一个部分
if (strTimeString.indexOf(":") != -1) {
// 时间
strTimeString = getFormatTimeString(strTimeString);
DateFormat dtFormat = new SimpleDateFormat("HH:mm:ss");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strTimeString);
} else {
// 作为日期处理
strTimeString = getFormatDateString(strTimeString);
DateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd");
if (timeZone != null) {
dtFormat.setTimeZone(timeZone);
}
return dtFormat.parse(strTimeString);
}
}
}
/**
* 获取时间格式化串
*
* @param strOrigin
* @return
*/
private static String getFormatTimeString(String strOrigin) {
int nDotPos = strOrigin.indexOf(".");
if (nDotPos != -1) {
strOrigin = strOrigin.substring(0, nDotPos);
}
Object Time[] = new Object[3];
Time[0] = 0;
Time[1] = 0;
Time[2] = 0;
String timepart[] = strOrigin.split(":");
int nTimePartLength = timepart.length;
if (nTimePartLength > 3) {
nTimePartLength = 3;
}
for (int i = 0; i < nTimePartLength; i++) {
Time[i] = Integer.parseInt(timepart[i]);
}
return String.format("%1$02d:%2$02d:%3$02d", Time);
}
/**
* 获取时日期格式化串
*
* @param strOrigin
* @return
* @
*/
private static String getFormatDateString(String strOrigin) throws Exception{
return getFormatDateString(strOrigin, true);
}
/**
* 获取时日期格式化串
*
* @param strOrigin
* @param bAdv
* @return
* @
*/
private static String getFormatDateString(String strOrigin, boolean bAdv) throws Exception{
Object Date[] = new Object[3];
Date[0] = 1970;
Date[1] = 1;
Date[2] = 1;
if (strOrigin.indexOf("-") != -1) {
String datePart[] = strOrigin.split("-");
if (datePart.length >= 1) {
Date[0] = Integer.parseInt(datePart[0]);
}
if (datePart.length >= 2) {
Date[1] = Integer.parseInt(datePart[1]);
}
if (datePart.length >= 3) {
Date[2] = Integer.parseInt(datePart[2]);
}
}
else if (strOrigin.indexOf("/") != -1) {
String datePart[] = strOrigin.split("/");
if (datePart.length >= 1) {
Date[1] = Integer.parseInt(datePart[0]);
}
if (datePart.length >= 2) {
Date[2] = Integer.parseInt(datePart[1]);
}
if (datePart.length >= 3) {
Date[0] = Integer.parseInt(datePart[2]);
}
} else {
if (bAdv) {
strOrigin = strOrigin.replace(".", "-");
strOrigin = strOrigin.replace("日", "");
strOrigin = strOrigin.replace("天", "");
strOrigin = strOrigin.replace("年", "-");
strOrigin = strOrigin.replace("月", "-");
return getFormatDateString(strOrigin, false);
} else
throw new Exception("无法识别的时间字符串,"+strOrigin);
}
return String.format("%1$04d-%2$02d-%3$02d", Date);
}
public static Timestamp getBeginDate()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
cl.set(1900,1,1);
return new Timestamp(cl.getTime().getTime());
}
public static Timestamp getEndDate()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
cl.set(2100,12,31,23,59,59);
return new Timestamp(cl.getTime().getTime());
}
public static Timestamp getNow()
{
Calendar cl=Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
return new Timestamp(cl.getTime().getTime());
}
}
...@@ -32,7 +32,7 @@ public class PermissionSyncJob implements ApplicationRunner { ...@@ -32,7 +32,7 @@ public class PermissionSyncJob implements ApplicationRunner {
@Value("${ibiz.enablePermissionValid:false}") @Value("${ibiz.enablePermissionValid:false}")
boolean enablePermissionValid; //是否开启权限校验 boolean enablePermissionValid; //是否开启权限校验
@Value("${ibiz.systemid:0A91C1B1-3B67-4EDA-9572-5DB491871FEE}") @Value("${ibiz.systemid:2C40DFCD-0DF5-47BF-91A5-C45F810B0001}")
private String systemId; private String systemId;
@Override @Override
......
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册