文件管理
controler层:
package com.yss.fsip.lifecycle.web.controller.archive;
import com.github.pagehelper.PageInfo;
import com.yss.fsip.common.FSIPRuntimeException;
import com.yss.fsip.common.util.DateUtil;
import com.yss.fsip.common.util.StringUtil;
import com.yss.fsip.lifecycle.api.vo.SearchParam;
import com.yss.fsip.lifecycle.api.vo.archive.ArchiveFileVO;
import com.yss.fsip.lifecycle.web.common.constant.FileSourceEnum;
import com.yss.fsip.lifecycle.web.common.constant.FileSystemEnum;
import com.yss.fsip.lifecycle.web.common.constant.ParamterConstant;
import com.yss.fsip.lifecycle.web.common.constant.SysParaConstant;
import com.yss.fsip.lifecycle.web.context.FSIPContextFactory;
import com.yss.fsip.lifecycle.web.dto.archive.FileInfo;
import com.yss.fsip.lifecycle.web.entity.ArchiveFile;
import com.yss.fsip.lifecycle.web.factory.IDGeneratorFactory;
import com.yss.fsip.lifecycle.web.service.archive.ArchiveFileService;
import com.yss.fsip.lifecycle.web.service.parameter.SystemParamterService;
import com.yss.fsip.lifecycle.web.service.util.NextIdService;
import com.yss.fsip.lifecycle.web.util.FileUtil;
import io.swagger.annotations.;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
/**
- 文档管理中的文件管理
- @author luoyuke
*/
@Api(value="/archive/file",tags=“文档管理”)
@Controller
@RequestMapping("/archive/file")
public class ArchiveFileController {
private static Logger logger = LoggerFactory.getLogger(ArchiveFileController.class);
@Autowired
private ArchiveFileService fileService;
@Autowired
private NextIdService nextIdService;
@Autowired
private SystemParamterService sysParaService;
/**
* 通用文件上传
* @param multipart 文件附件
* @param fileType 文件类型
* @param bizType 文件关联业务类型
* @param bizKey 文件管理业务信息
* @return
*/
@RequestMapping(method= {RequestMethod.POST},value = "/upload")
@ApiOperation(value="通用附件上传接口", notes="只支持单个文件上传")
@ResponseBody
public ArchiveFile upload(@RequestParam("file") @ApiParam(name="file",value="上传附件")MultipartFile multipart,
@RequestParam @ApiParam(name="fileType",value="文件类型") String fileType,
@RequestParam @ApiParam(name="bizType",value="关联业务类型,暂定product表示产品,customer为客户") String bizType,
@RequestParam @ApiParam(name="bizKey",value="关联业务数据") String bizKey) {
try {
if(multipart.getSize() == 0) {
throw new FSIPRuntimeException("附件内容不能为空");
}
Date date=Calendar.getInstance().getTime();
String fileName=multipart.getOriginalFilename();
String suffix=fileName.indexOf(".")>0?fileName.substring(fileName.lastIndexOf(".")):"";
ArchiveFile file=new ArchiveFile();
file.setId(IDGeneratorFactory.getIDGenerator().nextId());
file.setFileName(fileName);
file.setFileSize(multipart.getSize());
file.setMimeType(multipart.getContentType());
file.setSource(FileSourceEnum.upload.getCode());
file.setBizKey(bizKey);
file.setBizType(bizType);
file.setFileType(fileType);
String fileStore=String.format("%s/%s%s",DateUtil.dateToString(date,ParamterConstant.PATH_DATE_FORMAT),
file.getId(),suffix);
file.setFileStore(fileStore);
file.setDeleted(Boolean.FALSE);
file.setCreated(date);
file.setCreator(FSIPContextFactory.getContext().getUserId());
int nextId=nextIdService.getNextId();
file.setFileNo(FileUtil.getFileNo(file.getCreated(),FileSystemEnum.lifecycle.getCode(),nextId));
file.setExtObjName(sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE,SysParaConstant.ARCHIVE_OBJ_NAME));
//前端进行对重复文件进行重新命名
return fileService.save(file, multipart.getInputStream());
} catch (Exception e) {
logger.error("上传附件后台处理异常",e);
throw new FSIPRuntimeException("上传附件后台处理异常",e);
}
}
/**
* 通用文件删除
*
* @param fileId 文件ID
* @param bizType 文件关联业务类型
* @param bizKey 文件管理业务信息
* @return
*/
@RequestMapping(method= {RequestMethod.POST},value = "/cleanFile")
@ApiOperation(value="通用附件删除接口", notes="只支持单个文件删除")
@ResponseBody
public int cleanFile(
@RequestParam @ApiParam(name="fileId",value="文件ID") String fileId,
@RequestParam @ApiParam(name="bizType",value="关联业务类型,暂定product表示产品,customer为客户") String bizType,
@RequestParam @ApiParam(name="bizKey",value="关联业务数据,例如产品ID") String bizKey) {
try {
ArchiveFile file=new ArchiveFile();
file.setId(fileId);
file.setBizType(bizType);
file.setBizKey(bizKey);
return fileService.deleteFile(file);
} catch (Exception e) {
logger.error("删除附件后台处理异常",e);
throw new FSIPRuntimeException("删除附件后台处理异常",e);
}
}
/**
* 文件通用下载接口,
* 当预览时传输target=pdf表示下载pdf文件,后台会将非pdf文件转化为pdf后返回
* @param id 文件ID
* @param response
* @throws IOException
*/
@RequestMapping(method= {RequestMethod.GET},value = "/download")
@ApiOperation(value="通用附件下载接口", notes="只支持单个文件下载")
public void download(@RequestParam @ApiParam(name="id",value="文件ID") String id,
@ApiParam(name="target",value="目标文件类型") String target,
HttpServletResponse response) throws IOException{
OutputStream outputStream=null;
InputStream inputStream=null;
try {
FileInfo file=this.fileService.getFile(id,target,Boolean.TRUE,Boolean.TRUE);
if(file!=null) {
outputStream = response.getOutputStream();
inputStream=file.getStream();
if(StringUtil.isNotEmpty(file.getFile().getMimeType())) {
response.setContentType(file.getFile().getMimeType());
}else {
response.setContentType(ParamterConstant.DEFAULT_CONTENT_TYPE);
}
response.addHeader("Content-Disposition","attachment;fileName="+new String( file.getFile().getFileName().getBytes("gb2312"), "ISO8859-1" ));
IOUtils.copy(inputStream,response.getOutputStream());
}
} catch (Exception e) {
logger.error("下载附件[{}]时异常",id,e);
throw new FSIPRuntimeException("下载附件异常",e);
}finally {
try {
if(inputStream!=null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("下载附件关闭InputStream时异常",e);
}
if(outputStream!=null) {
try {
outputStream.flush();
} catch (IOException e) {
logger.error("下载附件刷新outputStream数据时异常",e);
}
try {
outputStream.close();
} catch (IOException e) {
logger.error("下载附件关闭outputStream时异常",e);
}
}
}
}
/**
* 文件信息分页查询
* @param pageNo 页数
* @param pageSize 每页个数
* @param params 查询条件
* @return
*/
@RequestMapping(method= {RequestMethod.POST},value = "/queryFilePage")
@ApiOperation(value="分页查询档案信息", notes="查询参数封装在params中")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNo", value = "当前页", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = true, dataType = "Integer"),
@ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "String")
})
@ResponseBody
public PageInfo<ArchiveFileVO> queryFilePage(@RequestBody SearchParam<ArchiveFileVO> acctQryReq) {
PageInfo<ArchiveFileVO> result = this.fileService.queryFilePage(acctQryReq);
return result;
}
}
serviceImpl层:
package com.yss.fsip.lifecycle.web.service.archive.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.yss.fsip.common.FSIPRuntimeException;
import com.yss.fsip.common.util.StringUtil;
import com.yss.fsip.lifecycle.api.vo.SearchParam;
import com.yss.fsip.lifecycle.api.vo.archive.ArchiveFileVO;
import com.yss.fsip.lifecycle.web.common.constant.FileSourceEnum;
import com.yss.fsip.lifecycle.web.common.constant.FileSystemEnum;
import com.yss.fsip.lifecycle.web.common.constant.ParamterConstant;
import com.yss.fsip.lifecycle.web.common.constant.SysParaConstant;
import com.yss.fsip.lifecycle.web.context.FSIPContextFactory;
import com.yss.fsip.lifecycle.web.dto.UserProductDataAuth;
import com.yss.fsip.lifecycle.web.dto.archive.FileInfo;
import com.yss.fsip.lifecycle.web.entity.ArchiveFile;
import com.yss.fsip.lifecycle.web.factory.IDGeneratorFactory;
import com.yss.fsip.lifecycle.web.mapper.dao.ArchiveFileMapper;
import com.yss.fsip.lifecycle.web.service.archive.ArchiveFileService;
import com.yss.fsip.lifecycle.web.service.archive.FileStore;
import com.yss.fsip.lifecycle.web.service.parameter.ProductService;
import com.yss.fsip.lifecycle.web.service.parameter.SystemParamterService;
import com.yss.fsip.lifecycle.web.service.sunyard.EcmDocService;
import com.yss.fsip.lifecycle.web.service.util.NextIdService;
import com.yss.fsip.lifecycle.web.util.BeanUtil;
import com.yss.fsip.lifecycle.web.util.FileUtil;
import com.yss.fsip.lifecycle.web.util.idmapping.IdMappingUtil;
import com.yss.fsip.lifecycle.web.util.openoffice.OfficeToPDF;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
/**
- 文档管理中文件管理
- @author luoyuke
*/
@Service
public class ArchiveFileServiceImpl implements ArchiveFileService {
private static Logger logger = LoggerFactory.getLogger(ArchiveFileServiceImpl.class);
@Autowired
private ArchiveFileMapper fileMapper;
@Autowired
private SystemParamterService sysParaService;
@Autowired
private NextIdService nextIdService;
@Autowired
private EcmDocService docService;
@Autowired
private ProductService productService;
private FileStore fileStore;
private String root;
private String store;
private String objName;
/**
* 将本地一个文件上传保存
*
* @throws FileNotFoundException
*/
@Override
public ArchiveFile save(String fileType, String bizType, String bizKey, String source, String filePath,
String creator, String id, String fName) throws IOException {
this.init();
File sourceFile = new File(filePath);
if (!sourceFile.exists()) {
logger.error("上传的文件[{}]不存在", filePath);
return null;
}
Date date = Calendar.getInstance().getTime();
ArchiveFile file = new ArchiveFile(fileType, bizType, bizKey, source);
file.setId(id);
file.setFileName(fName);
file.setMimeType(FileUtil.getMimeType(file.getFileName()));
String fileName = file.getFileName();
String suffix = fileName.indexOf(".") >= 0 ? fileName.substring(fileName.lastIndexOf(".")) : "";
String filestore = FileUtil.getFileStore(date, file.getId(), suffix);
file.setFileSize(sourceFile.length());
file.setFileStore(filestore);
file.setDeleted(Boolean.FALSE);
file.setCreator(creator);
file.setCreated(date);
int nextId=nextIdService.getNextId();
file.setFileNo(FileUtil.getFileNo(file.getCreated(),FileSystemEnum.lifecycle.getCode(),nextId));
file.setExtObjName(this.objName);
this.fileStore.saveContent(file, new FileInputStream(sourceFile));
this.fileMapper.insertSelective(file);
return file;
}
public ArchiveFile save(MultipartFile multipart,String fileType,String bizType,String bizKey) throws IOException {
this.init();
Date date = Calendar.getInstance().getTime();
String fileName = multipart.getOriginalFilename();
String suffix = fileName.indexOf(".") > 0 ? fileName.substring(fileName.lastIndexOf(".")) : "";
ArchiveFile file = new ArchiveFile();
file.setId(IDGeneratorFactory.getIDGenerator().nextId());
file.setFileNo(file.getId());
file.setFileName(fileName);
file.setFileSize(multipart.getSize());
file.setMimeType(multipart.getContentType());
file.setSource(FileSourceEnum.upload.getCode());
file.setBizKey(bizKey);
file.setBizType(bizType);
file.setFileType(fileType);
String fileStore = FileUtil.getFileStore(date, file.getId(), suffix);
file.setFileStore(fileStore);
file.setDeleted(Boolean.FALSE);
file.setCreated(date);
file.setCreator(FSIPContextFactory.getContext().getUserId());
file.setExtObjName(this.objName);
this.fileStore.saveContent(file,multipart.getInputStream());
this.fileMapper.insert(file);
return file;
}
/**
* 获取文件信息,可选择是否返回文件流
*/
@Override
public FileInfo getFile(String id, String target, boolean file, boolean stream) throws IOException {
this.init();
Example example = new Example(ArchiveFile.class);
Criteria criteria = example.createCriteria();
criteria.andEqualTo("id", id);
ArchiveFile record = this.fileMapper.selectOneByExample(example);
if (record == null) {
logger.error("查询文件[{}]信息失败", id);
throw new FSIPRuntimeException("查询文件信息失败");
}
if (file) {
this.fileStore.getFile(record);
if (ParamterConstant.DOWNLOAD_TARGET.equalsIgnoreCase(target)) {
// 获取文件后缀名
String format = FileUtil.getFileFormat(record.getFileName());
// 如果后缀名不为空且后缀名不是pdf,则需要转换
if (StringUtil.isNotEmpty(format) && !ParamterConstant.DOWNLOAD_TARGET.equalsIgnoreCase(format)) {
String sourcePath = String.format("%s/%s", root, record.getFileStore());
String targetPath = sourcePath.substring(0, sourcePath.lastIndexOf(".") + 1)
+ ParamterConstant.DOWNLOAD_TARGET;
File targetFile = new File(targetPath);
// 如果pdf文件已存在则无需转换
if (!targetFile.exists()) {
OfficeToPDF.office2Pdf(sourcePath, targetPath);
if (!targetFile.exists()) {
// 转换失败
logger.error("文件[{}]转换pdf失败", sourcePath);
throw new FSIPRuntimeException("文件转换为pdf失败");
}
}
// 更新转换后的文件信息
record.setFileSize(targetFile.length());
record.setFileStore(record.getFileStore().substring(0, record.getFileStore().lastIndexOf(".") + 1)
+ ParamterConstant.DOWNLOAD_TARGET);
record.setFileName(record.getFileName().substring(0, record.getFileName().lastIndexOf(".") + 1)
+ ParamterConstant.DOWNLOAD_TARGET);
}
}
if (stream) {
String filePath = String.format("%s/%s", root, record.getFileStore());
InputStream input = new FileInputStream(new File(filePath));
return new FileInfo(record, input);
}
}
return new FileInfo(record);
}
/**
* 根据别人传过来的id把文件保存到t_archive_file表中;
*/
@Override
public ArchiveFile saveFileInfo(String fileType, String bizType, String bizKey,
String source, String objName,String batchId,String creator) throws IOException {
this.init();
Date date = Calendar.getInstance().getTime();
ArchiveFile file = new ArchiveFile(fileType, bizType, bizKey, source);
file.setId(IDGeneratorFactory.getIDGenerator().nextId());
int nextId = nextIdService.getNextId();
file.setFileNo(FileUtil.getFileNo(file.getCreated(), FileSystemEnum.lifecycle.getCode(), nextId));
file.setExtObjName(sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE,SysParaConstant.ARCHIVE_OBJ_NAME));
file.setCreated(date);
file.setExtBatchId(batchId);
file.setExtObjName(objName);
file.setCreator(creator);
file.setDeleted(Boolean.FALSE);
// 调用docService会把fileName,MimeType,FileStore,FileSize返回给file;
docService.getDocInfo(file);
this.fileMapper.insertSelective(file);
return file;
}
/**
* 保存用户上传的附件
*/
@Override
public ArchiveFile save(ArchiveFile file, InputStream stream) throws IOException {
this.init();
this.fileStore.saveContent(file, stream);
this.fileMapper.insertSelective(file);
return file;
}
/**
* 获取文件列表数据
*/
@Override
public PageInfo<ArchiveFileVO> queryFilePage(SearchParam<ArchiveFileVO> param) {
String userId = FSIPContextFactory.getContext().getUserId();
//查询用户产品权限
UserProductDataAuth dataAuth = productService.findUserProduct(userId);
if (dataAuth == null || (!dataAuth.isAllAuth() && CollectionUtils.isEmpty(dataAuth.getProductIds()))) {
//如果用户没有产品权限,则直接返回空集合
return new PageInfo<>(Lists.newArrayList());
}
PageHelper.startPage(param.getPageNo(), param.getPageSize());
List<ArchiveFileVO> list = this.fileMapper.queryFilePage(param.getParams(), dataAuth);
IdMappingUtil.change(list);
return new PageInfo<>(list);
}
/**
* 获取同一产品的同一文件类型的重名文件列表数据
*/
@Override
public List<ArchiveFileVO> queryFileName(ArchiveFile file) {
return this.fileMapper.queryFileName(file);
}
private void init() {
this.setRoot(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_FILE_ROOT));
this.setStore(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_FILE_STORE));
this.setObjName(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_OBJ_NAME));
this.setFileStore(BeanUtil.getBean(this.store, FileStore.class));
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public String getStore() {
return store;
}
public void setStore(String store) {
this.store = store;
}
public FileStore getFileStore() {
return fileStore;
}
public void setFileStore(FileStore fileStore) {
this.fileStore = fileStore;
}
public String getObjName() {
return objName;
}
public void setObjName(String objName) {
this.objName = objName;
}
@Override
public int deleteFile(ArchiveFile file) {
Example example = new Example(ArchiveFile.class);
Criteria criteria = example.createCriteria();
criteria.andEqualTo("id", file.getId());
criteria.andEqualTo("bizType", file.getBizType()).andEqualTo("bizKey", file.getBizKey());
return this.fileMapper.deleteByExample(example);
}
}
package com.yss.fsip.lifecycle.web.service.parameter.impl;
import java.math.BigDecimal;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yss.fsip.common.FSIPRuntimeException;
import com.yss.fsip.lifecycle.web.common.constant.SysParaConstant;
import com.yss.fsip.lifecycle.web.entity.SystemParamter;
import com.yss.fsip.lifecycle.web.factory.IDGeneratorFactory;
import com.yss.fsip.lifecycle.web.mapper.dao.SystemParamterMapper;
import com.yss.fsip.lifecycle.web.service.parameter.SystemParamterService;
@Service
public class SystemParamterServiceImpl implements SystemParamterService {
private static Logger logger = LoggerFactory.getLogger(SystemParamterServiceImpl.class);
@Autowired
private SystemParamterMapper paramterMapper;
@Override
public SystemParamter getSysPara(String type, String key) {
SystemParamter paramter=new SystemParamter();
paramter.setKey(key);
paramter.setType(type);
return this.paramterMapper.selectOne(paramter);
}
@Override
public String getSysParaValue(String type, String key) {
SystemParamter paramter=new SystemParamter();
paramter.setKey(key);
paramter.setType(type);
SystemParamter record=this.paramterMapper.selectOne(paramter);
if(record==null) {
logger.error("系统参数[type:{},key:{}]未配置",type,key);
throw new FSIPRuntimeException(String.format("系统参数类型[%s]未配置",key));
}else {
return record.getValue();
}
}
@Override
@Transactional
public void saveOrUpdate(String key,String value,String remark) {
SystemParamter record=this.getSysPara(SysParaConstant.SYS_PARA_TYPE,key);
if(record==null) {
record=new SystemParamter();
record.setId(IDGeneratorFactory.getIDGenerator().nextId());
record.setKey(key);
record.setType(SysParaConstant.SYS_PARA_TYPE);
record.setValue(value);
record.setRemark(remark);
int result=this.paramterMapper.insertSelective(record);
if(result!=1) {
logger.error("保存系统参数[key:{},value:{}]失败,因为保存的数据条数为[{}]",key,value,result);
throw new FSIPRuntimeException("保存系统参数异常");
}
}else {
record.setValue(value);
int result=this.paramterMapper.updateByPrimaryKeySelective(record);
if(result!=1) {
logger.error("更新系统参数[key:{},value:{}]失败,因为更新的数据条数为[{}]",key,value,result);
throw new FSIPRuntimeException("更新系统参数异常");
}
}
}
@Override
public void delete(String key) {
SystemParamter record=new SystemParamter();
record.setKey(key);
record.setType(SysParaConstant.SYS_PARA_TYPE);
int result=this.paramterMapper.delete(record);
if(result!=1) {
logger.error("删除系统参数[{}]失败,成功删除[{}]条",key,result);
throw new FSIPRuntimeException("删除系统参数失败");
}
}
@Override
public List<SystemParamter> getSysPara(String type) {
SystemParamter paramter=new SystemParamter();
paramter.setType(type);
return this.paramterMapper.select(paramter);
}
}
package com.yss.fsip.lifecycle.web.service.sunyard.impl;
import com.sunyard.TransEngine.client.ClientApi;
import com.sunyard.TransEngine.doc.ECMDoc;
import com.sunyard.TransEngine.exception.SunTransEngineException;
import com.sunyard.TransEngine.util.OptionKey;
import com.sunyard.TransEngine.util.key.DocKey;
import com.sunyard.TransEngine.util.key.DocPartKey;
import com.yss.fsip.common.FSIPRuntimeException;
import com.yss.fsip.common.util.DateUtil;
import com.yss.fsip.common.util.StringUtil;
import com.yss.fsip.lifecycle.web.common.constant.FileSystemEnum;
import com.yss.fsip.lifecycle.web.common.constant.ParamterConstant;
import com.yss.fsip.lifecycle.web.common.constant.SysParaConstant;
import com.yss.fsip.lifecycle.web.entity.ArchiveFile;
import com.yss.fsip.lifecycle.web.factory.IDGeneratorFactory;
import com.yss.fsip.lifecycle.web.mapper.dao.ArchiveFileMapper;
import com.yss.fsip.lifecycle.web.service.parameter.SystemParamterService;
import com.yss.fsip.lifecycle.web.service.password.PasswordService;
import com.yss.fsip.lifecycle.web.service.sunyard.EcmDocService;
import com.yss.fsip.lifecycle.web.service.util.NextIdService;
import com.yss.fsip.lifecycle.web.util.FileUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class EcmDocServiceImpl implements EcmDocService{
private static final Logger logger = LoggerFactory.getLogger(EcmDocServiceImpl.class);
public static final String BUSI_SERIAL_NO="BUSI_SERIAL_NO";
public static final String XPATH = "/ROOT/IMAGES/IMAGE";
public static final String ATTRIBUTE_FILE_NO = "FILE_NO";
public static final String ATTRIBUTE_URL = "URL";
public static final String ATTRIBUTE_FILE_NAME = "FILENAME";
public static final String ATTRIBUTE_FILE_SIZE = "FILE_SIZE";
public static final String ATTRIBUTE_FILE_FORMAT = "FILE_FORMAT";
@Autowired
private SystemParamterService sysParaService;
@Autowired
private ArchiveFileMapper fileMapper;
@Autowired
private NextIdService nextIdService;
@Autowired
private PasswordService passwordService;
private String ip;
private String port;
private String username;
private String password;
private ClientApi api;
@Override
public void uploadDoc(String filePath, ArchiveFile file) {
try{
//初始化配置信息
this.init();
ECMDoc doc=new ECMDoc();
doc.setObjName(file.getExtObjName());
//该属性必填
doc.setBusiAttribute(DocKey.BUSI_START_TIME,DateUtil.dateToString(file.getCreated(),ParamterConstant.DATE_FORMAT));
//该属性必填
doc.setBusiAttribute(BUSI_SERIAL_NO,file.getId());
//开始添加上传附件信息
String filePart = this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_FILE_PART);
doc.beginFilePart(filePart);
//每个文件上传时调用此开始方法
doc.beginFile();
//该属性必填
doc.setFileAttribute(DocPartKey.FILE_FORMAT,FileUtil.getFileFormat(file.getFileName()));
//该属性必填
doc.setFileAttribute(DocPartKey.FILE_SIZE,String.valueOf(file.getFileSize()));
//设置上传的附件
doc.setFile(filePath,false);
//每个文件结束时调用此结束方法
doc.endFile();
//结束添加上传附件信息
doc.endFilePart();
//上传附件,返回批次号
String batchId=this.api.add(doc);
this.api.logout();
//将上传的批次号赋值,后续统一保存
file.setExtBatchId(batchId);
} catch (Exception e) {
logger.error("上传文件[{}]到影像异常", file.getId(), e);
throw new FSIPRuntimeException("上传文件到影像异常");
}
}
@Override
public void getDocInfo(ArchiveFile file) {
try{
//构造查询对象
ECMDoc doc=new ECMDoc();
doc.setObjName(file.getExtObjName());
doc.setBatchID(file.getExtBatchId());
doc.setOption(OptionKey.QUERY_BATCH_FILE);
doc.setQueryTime(DateUtil.dateToString(file.getCreated(),ParamterConstant.DATE_FORMAT));
logger.info(" 查询服务托管平台文件, BatchID:{}, ObjName:{}", file.getExtBatchId(), file.getExtObjName());
//初始化配置信息
this.init();
//查询下载地址
String xml=this.api.queryFile(doc);
this.api.logout();
// String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?><IMAGES FILE_PART=“TEST_PART” NOW_VERSION=“1”><IMAGE FILE_NO=“1-7B60C295-17F2-55AA-3ADF-D8F665AAE7C1” FILENAME=“TEST.PDF” FILE_SIZE=“879394” IS_INDEXTYPE=“0” PART_NAME=“TEST_PART” FILE_FORMAT=“jpg” UPLOAD_TIME=“20170608174934” S_VERSION=“1” URL=“http://21.96.212.55:9080/SunDM/servlet/getSdbImage?ITEM_TYPE_NAME=TEST_PART&CL_TIME=201706&FILE_SIZE=879394&FILE_OID=59391daed08e0dc299cc94bf”/> ";
if(StringUtil.isEmpty(xml)) {
return;
}
logger.info(“影像平台查询文件, 批次号:{}, 返回报文:{}”, file.getExtBatchId(), xml);
Document document=DocumentHelper.parseText(xml);
List list=document.selectNodes(XPATH);
if(list!=null && list.size()==1) {
Element element=(Element)list.get(0);
//保存文件在影像平台的ID,后续删除和更新操作时需用到此参数
file.setExtFileNo(element.attributeValue(ATTRIBUTE_FILE_NO));
//下载时的URL
file.setExtDownloadUrl(element.attributeValue(ATTRIBUTE_URL));
if (StringUtil.isEmpty(file.getFileName())) {
if (StringUtil.isNotEmpty(element.attributeValue(ATTRIBUTE_FILE_NAME))) {
file.setFileName(element.attributeValue(ATTRIBUTE_FILE_NAME));
file.setMimeType(FileUtil.getMimeType(file.getFileName()));
}
} else {
file.setMimeType(FileUtil.getMimeType(file.getFileName()));
}
if (StringUtil.isEmpty(file.getFileStore())) {
String suffix;
if (StringUtil.isEmpty(file.getFileName())) {
suffix = element.attributeValue(ATTRIBUTE_FILE_FORMAT);
} else {
suffix = FileUtil.getFileSuffix(file.getFileName());
}
file.setFileStore(FileUtil.getFileStore(file.getCreated(), file.getId(), suffix));
}
if(file.getFileSize()==null || file.getFileSize()==0) {
file.setFileSize(Long.parseLong(element.attributeValue(ATTRIBUTE_FILE_SIZE)));
}
}else {
logger.error(“查询文件[{}]上传批次号[{}]响应XML报文为[{}]时没有节点[/ROOT/IMAGES/IMAGE]”,file.getId(),file.getExtBatchId(),xml);
throw new FSIPRuntimeException(“获取影像平台文件信息异常”);
}
} catch (Exception e) {
logger.error(“下载影像平台文件[{}]异常”,file.getId(),e);
throw new FSIPRuntimeException(“获取影像平台文件信息异常”);
}
}
@Override
public ArchiveFile saveFileByBatchId(String objName,String batchId,String fileName, String fileType, String source,
String bizType, String bizKey,String creator) {
ArchiveFile file=new ArchiveFile();
file.setId(IDGeneratorFactory.getIDGenerator().nextId());
file.setExtBatchId(batchId);
file.setExtObjName(objName);
file.setFileType(fileType);
file.setSource(source);
file.setFileName(fileName);
file.setBizType(bizType);
file.setBizKey(bizKey);
file.setDeleted(Boolean.FALSE);
file.setCreated(new Date());
file.setCreator(creator);
int nextId=nextIdService.getNextId();
file.setFileNo(FileUtil.getFileNo(file.getCreated(),FileSystemEnum.lifecycle.getCode(),nextId));
file.setExtObjName(sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE,SysParaConstant.ARCHIVE_OBJ_NAME));
this.getDocInfo(file);
int result=this.fileMapper.insertSelective(file);
if(result!=1) {
logger.error("保存影像平台批次号[{}]文件到文档表失败,成功条数为[{}]",batchId,result);
}
return file;
}
private void init() {
this.setIp(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_SERVER_IP));
this.setPort(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_SERVER_PORT));
this.setUsername(this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_SERVER_USERNAME));
String pwd = this.sysParaService.getSysParaValue(SysParaConstant.SYS_PARA_TYPE, SysParaConstant.ARCHIVE_SERVER_PWD);
//密码需要解密
this.setPassword(passwordService.decrypt(pwd));
//获取客户端信息
logger.info("影像平台配置, ip:{}, port:{}, username:{}, password:{}", ip, port, username, password);
this.api=new ClientApi(ip, port, username, password);
try {
this.api.login();
logger.info("内容管理平台登录成功");
} catch (SunTransEngineException e) {
logger.error("内容管理平台登录失败", e);
throw new FSIPRuntimeException("内容管理平台登录失败");
}
}
public void setIp(String ip) {
this.ip = ip;
}
public void setPort(String port) {
this.port = port;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.yss.fsip.lifecycle.web.service.parameter.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.yss.fsip.common.FSIPRuntimeException;
import com.yss.fsip.common.util.StringUtil;
import com.yss.fsip.lifecycle.api.vo.SearchParam;
import com.yss.fsip.lifecycle.api.vo.online.SimpleProduct;
import com.yss.fsip.lifecycle.api.vo.parameter.ProductExtendVO;
import com.yss.fsip.lifecycle.api.vo.parameter.ProductMarketVO;
import com.yss.fsip.lifecycle.api.vo.parameter.ProductVO;
import com.yss.fsip.lifecycle.auth.service.auth.AuthenticationService;
import com.yss.fsip.lifecycle.web.common.constant.ProductConstant;
import com.yss.fsip.lifecycle.web.common.constant.ProductStatusEnum;
import com.yss.fsip.lifecycle.web.context.FSIPContextFactory;
import com.yss.fsip.lifecycle.web.dto.UserProductDataAuth;
import com.yss.fsip.lifecycle.web.entity.Product;
import com.yss.fsip.lifecycle.web.entity.ProductMarket;
import com.yss.fsip.lifecycle.web.mapper.dao.ProductMapper;
import com.yss.fsip.lifecycle.web.mapper.dao.ProductMarketMapper;
import com.yss.fsip.lifecycle.web.mapper.dao.ProductTreeMapper;
import com.yss.fsip.lifecycle.web.service.parameter.ProductExtendService;
import com.yss.fsip.lifecycle.web.service.parameter.ProductService;
import com.yss.fsip.lifecycle.web.util.DBUtil;
import com.yss.fsip.lifecycle.web.util.idmapping.IdMappingUtil;
import com.yss.fsip.service.BaseService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;
import java.util.*;
/**
-
产品信息服务
-
@author lw
-
@version 1.0, 2019年8月14日
-
@since 1.0, 2019年8月14日
*/
@Service
public class ProductServiceImpl extends BaseService implements ProductService {@Autowired
private ProductMapper productMapper;@Autowired
private ProductTreeMapper productTreeMapper;@Autowired
private ProductMarketMapper productMarketMapper;@Autowired
private ProductExtendService productExtendService;@Autowired
private AuthenticationService authenticationService;public PageInfo queryOffLinePage(SearchParam param){
String userId = FSIPContextFactory.getContext().getUserId();
//查询用户产品权限
UserProductDataAuth dataAuth = findUserProduct(userId);
if (dataAuth == null || (!dataAuth.isAllAuth() && CollectionUtils.isEmpty(dataAuth.getProductIds()))) {
//如果用户没有产品权限,则直接返回空集合
return new PageInfo<>(Lists.newArrayList());
}
PageHelper.startPage(param.getPageNo(), param.getPageSize());
List list = this.productMapper.queryOffLinePage(param.getParams(), dataAuth);
IdMappingUtil.change(list);
return new PageInfo<>(list);
}@Override
public ProductVO queryProductById(String id) {
Product product=this.productMapper.selectByPrimaryKey(id);
if(product==null) {
throw new FSIPRuntimeException(“查不到产品信息”);
}
ProductVO vo=new ProductVO();
IdMappingUtil.change(product,vo);
return vo;
}/**
- {@inheritDoc}
- @see com.yss.fsip.lifecycle.web.service.parameter.ProductService#queryById(java.lang.String)
*/
public Product queryById(String id) {
if (StringUtil.isEmpty(id)) {
return null;
}
Product product = this.productMapper.selectByPrimaryKey(id);
return product;
}
/**
-
{@inheritDoc}
-
@see com.yss.fsip.lifecycle.web.service.parameter.ProductService#queryBySetCode(java.lang.String)
*/
public Product queryBySetCode(String setCode) {
if (StringUtil.isEmpty(setCode)) {
return null;
}Example example = new Example(Product.class);
example.orderBy(“id”).desc();
example.createCriteria().andEqualTo(“setCode”, setCode);
List records = this.productMapper.selectByExample(example);
Product product = CollectionUtils.isEmpty(records)? null:records.get(0);
return product;
}
public Product queryByProdCode(String prodCode) {
if (StringUtil.isEmpty(prodCode)) {
return null;
}Example example = new Example(Product.class); example.orderBy("id").desc(); example.createCriteria().andEqualTo("code", prodCode); List<Product> records = this.productMapper.selectByExample(example); Product product = CollectionUtils.isEmpty(records)? null:records.get(0); return product;
}
/**
-
{@inheritDoc}
-
@see com.yss.fsip.lifecycle.web.service.parameter.ProductService#queryByCode(java.lang.String)
*/
public Product queryByCode(String code) {
if (StringUtil.isEmpty(code)) {
return null;
}Example example = new Example(Product.class);
example.orderBy(“id”).desc();
example.createCriteria().andEqualTo(“code”, code)
.andEqualTo(“deleted”, 0);
List records = this.productMapper.selectByExample(example);
Product product = CollectionUtils.isEmpty(records)? null:records.get(0);
return product;
}
/**
-
{@inheritDoc}
-
@see com.yss.fsip.lifecycle.web.service.parameter.ProductService#ifPushed(java.lang.String)
*/
public boolean ifPushed(String code) {
if (StringUtil.isEmpty(code)) {
return false;
}Example example = new Example(Product.class);
example.createCriteria().andEqualTo(“code”, code);
List records = this.productMapper.selectByExample(example);
boolean pushed = CollectionUtils.isEmpty(records)? false:true;
return pushed;
}
/**
-
{@inheritDoc}
-
@see com.yss.fsip.lifecycle.web.service.parameter.ProductService#findProCascProExt(java.lang.String)
*/
public ProductVO findProCascProExt(String productId) {
Product product = this.productMapper.selectByPrimaryKey(productId);
ProductVO productVO = this.transProduct(product);
if (null == productVO) {
return null;
}
ProductExtendVO proExtVO = productExtendService.queryProExtVOByProId(productId);
productVO.setProductExtend(proExtVO);Example example = new Example(ProductMarket.class);
example.createCriteria().andEqualTo(“productId”, productId);
List records = productMarketMapper.selectByExample(example);
List results = new ArrayList();
productVO.setMarketList(results);
for (ProductMarket record : records) {
ProductMarketVO result = new ProductMarketVO();
results.add(result);result.setId(DBUtil.getString(record.getId())); result.setMarketUnit(record.getMarketUnit()); result.setIndMarketItem(DBUtil.getString(record.getIndMarketItem())); result.setProportion(record.getProportion());
}
IdMappingUtil.change(results);
return productVO;
}
/**
- {@inheritDoc}
- @see com.yss.fsip.lifecycle.web.service.parameter.ProductService#save(com.yss.fsip.lifecycle.api.vo.parameter.ProductVO)
*/
@Transactional
public void save(ProductVO productVO) {
String productId = productVO.getId();
if (StringUtil.isEmpty(productId)) {
return;
}
Product product = this.transProductVO(productVO);
this.productMapper.updateByPrimaryKeySelective(product);
this.productExtendService.save(productId, productVO.getProductExtend());
this.productExtendService.saveProMarkets(productId, productVO.getMarketList());
}
/**
-
将产品PO转VO
-
@param product
-
@return
*/
private ProductVO transProduct(Product product) {if (null == product) {
return null;
}
ProductVO proVO = new ProductVO();
proVO.setId(DBUtil.getString(product.getId()));
proVO.setSecurity(product.getSecurity());
proVO.setOperationUnit(DBUtil.getString(product.getOperationUnit()));
proVO.setSwiftCode(product.getSwiftCode());
proVO.setCode(product.getCode());proVO.setName(product.getName());
proVO.setAlias(product.getAlias());
proVO.setProductType(product.getProductType());
proVO.setManager(DBUtil.getString(product.getManager()));
proVO.setCustodian(DBUtil.getString(product.getCustodian()));proVO.setEntrustor(DBUtil.getString(product.getEntrustor()));
proVO.setTrustee(DBUtil.getString(product.getTrustee()));
proVO.setAccountManager(DBUtil.getString(product.getAccountManager()));
proVO.setParentId(DBUtil.getString(product.getParentId()));
proVO.setOutsideTrustee(DBUtil.getString(product.getOutsideTrustee()));proVO.setContractBegDate(product.getContractBegDate());
proVO.setContractEndDate(product.getContractEndDate());
proVO.setFactBegDate(product.getFactBegDate());
proVO.setFactEndDate(product.getFactEndDate());
proVO.setPlanlicId(product.getPlanlicId());proVO.setPortfolioId(product.getPortfolioId());
proVO.setAccountMode(product.getAccountMode());
return proVO;
}
/**
-
将产品VO转PO,将transProduct方法反转即可
-
@param proVO
-
@return
*/
private Product transProductVO(ProductVO proVO) {if (null == proVO) {
return null;
}
Product product = new Product();
product.setId(proVO.getId());
product.setSecurity(DBUtil.getBoolean(proVO.getSecurity()));
product.setOperationUnit(proVO.getOperationUnit());
product.setSwiftCode(proVO.getSwiftCode());
product.setCode(proVO.getCode());product.setName(proVO.getName());
product.setAlias(proVO.getAlias());
product.setProductType(proVO.getProductType());
product.setManager(proVO.getManager());
product.setCustodian(proVO.getCustodian());product.setEntrustor(proVO.getEntrustor());
product.setTrustee(proVO.getTrustee());
product.setAccountManager(proVO.getAccountManager());
product.setParentId(proVO.getParentId());
product.setOutsideTrustee(proVO.getOutsideTrustee());product.setContractBegDate(proVO.getContractBegDate());
product.setContractEndDate(proVO.getContractEndDate());
product.setFactBegDate(proVO.getFactBegDate());
product.setFactEndDate(proVO.getFactEndDate());
product.setPlanlicId(proVO.getPlanlicId());product.setPortfolioId(proVO.getPortfolioId());
product.setAccountMode(proVO.getAccountMode());
return product;
}
@Override
public PageInfo queryProductByName(SearchParam<Map<String, String>> reqParam) {
int pageNo = reqParam.getPageNo() == 0 ? 1 : reqParam.getPageNo();
int pageSize = reqParam.getPageSize() == 0 ? 1 : reqParam.getPageSize();String userId = FSIPContextFactory.getContext().getUserId(); //查询用户产品权限 UserProductDataAuth dataAuth = findUserProduct(userId); if (dataAuth == null || (!dataAuth.isAllAuth() && CollectionUtils.isEmpty(dataAuth.getProductIds()))) { //如果用户没有产品权限,则直接返回空集合 return new PageInfo<>(Lists.newArrayList()); } PageHelper.startPage(pageNo, pageSize); List<SimpleProduct> productList = productMapper.queryProductByPName(reqParam.getParams(),dataAuth); return new PageInfo<>(productList);
}
@Override
public UserProductDataAuth findUserProduct(String userId) {
UserProductDataAuth dataAuth = new UserProductDataAuth();
//查询用户的数据权限
Map<String, List> acl = authenticationService.findUserProductDataAuth(userId);
List productAll = acl.get(ProductConstant.TYPE_PRODUCT_ALL); // 全部权限
List productDetailIds = acl.get(ProductConstant.TYPE_PRODUCT); // 明细产品
List productTypes = acl.get(ProductConstant.TYPE_PRODUCTTYPE); // 产品类型
List productGroups = acl.get(ProductConstant.TYPE_PRODUCT_GROUP); // 产品组
List productOperations = acl.get(ProductConstant.TYPE_PRODUCT_OPERATION); // 营运单位
List productIsSecurity = acl.get(ProductConstant.TYPE_PRODUCT_ISSECURITY); // 是否证券类
List productManageOrgs = acl.get(ProductConstant.TYPE_PRODUCT_MANAGEORG); // 产品管理机构
List productSeniorOperations = acl.get(ProductConstant.TYPE_PRODUCT_SENIOROPERATION); // 清算运营机构
List productSeniorType = acl.get(ProductConstant.TYPE_PRODUCT_SENIORTYPE); // 一级清算类型// 都没有权限,则直接返回Null if (CollectionUtils.isEmpty(productAll) && CollectionUtils.isEmpty(productDetailIds) && CollectionUtils.isEmpty(productTypes) && CollectionUtils.isEmpty(productGroups) && CollectionUtils.isEmpty(productOperations) && CollectionUtils.isEmpty(productIsSecurity) && CollectionUtils.isEmpty(productManageOrgs) && CollectionUtils.isEmpty(productSeniorOperations) && CollectionUtils.isEmpty(productSeniorType)) { return null; } if (CollectionUtils.isEmpty(productAll)) { Set<String> productIds = new HashSet<>(); Map<String,Object> advOnlineProMap = new HashMap<>(); Map<String,Object> proTypeOrIsSecurityMap = new HashMap<>(); if (CollectionUtils.isNotEmpty(productDetailIds)) { // 有明细产品权限 productIds.addAll(productDetailIds); } if (CollectionUtils.isNotEmpty(productGroups)) { // 有产品组权限 productIds.addAll(productTreeMapper.findProductIdsByGroupIds(productGroups)); } if (CollectionUtils.isNotEmpty(productOperations)) { // 有产品营运机构权限 advOnlineProMap.put("productOperations", productOperations);//用来查询有权限的未上线产品 productIds.addAll(productTreeMapper.findProductIdsByOperations(productOperations)); } if (CollectionUtils.isNotEmpty(productManageOrgs)) { // 产品管理机构(包括自己创建的产品) Map<String,Object> m = new HashMap<>(); m.put("productManageOrgs", productManageOrgs); m.put("userId", userId); productIds.addAll(productTreeMapper.findProductIdsByManageOrgs(m)); } if (CollectionUtils.isNotEmpty(productSeniorOperations)) { // 产品清算运营机构 advOnlineProMap.put("productSeniorOperations", productSeniorOperations);//用来查询有权限的未上线产品 productIds.addAll(productTreeMapper.findProductIdsBySeniorOperations(productSeniorOperations)); } if (CollectionUtils.isNotEmpty(productSeniorType)) {// 产品一级清算类型权限 productIds.addAll(productTreeMapper.findProIdsByProExtendSeniorTypeCodes(productSeniorType)); } if (CollectionUtils.isNotEmpty(productTypes)) { // 有产品类型权限 proTypeOrIsSecurityMap.put("productTypeList", productTreeMapper.findProductTypeIdsByLeaf(productTypes)); } if (CollectionUtils.isNotEmpty(productIsSecurity)) { // 是否证券类权限 proTypeOrIsSecurityMap.put("productIsSecurityList", productIsSecurity); } //有产品类型权限、是否证券类权限的产品 productIds.addAll(productMapper.findProductIdsByproTypeOrIsSecurity(proTypeOrIsSecurityMap)); //有权限的未上线产品(包括营运机构权限和产品清算运营机构权限。主要是查询已作废流程的产品,其它未上线产品前面查出来了,产品推送fdeleted=0) productIds.addAll(productMapper.queryAdvOnlineProductIds(advOnlineProMap)); dataAuth.setAllAuth(false); dataAuth.setProductIds(new ArrayList<>(productIds)); } else { dataAuth.setAllAuth(true); } return dataAuth;
}
@Override
@Transactional
public int updateProductStatus(String productId, ProductStatusEnum productStatus) {
Assert.notNull(productStatus, “productStatus is not null”);
Product product = new Product();
product.setId(productId);
product.setProductStatus(productStatus.getCode());
return productMapper.updateByPrimaryKeySelective(product);
}@Override
@Transactional
public void updateProductById(String id) {
if (StringUtil.isEmpty(id)) {
return;
}
Product product = new Product();
product.setId(id);
product.setDeleted(true);
product.setDeleteUserId(FSIPContextFactory.getContext().getUserId());
product.setDeleteReason(“生命周期上线作废删除”);
product.setProductStatus(ProductStatusEnum.CPZT99.getCode());
productMapper.updateByPrimaryKeySelective(product);
}
}