mirror of
https://gitee.com/kekingcn/file-online-preview.git
synced 2026-03-14 05:03:49 +08:00
调整项目模块,jodconverter-core重命名为office-plugin。jdocnverter-web重命名为server
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.config.WatermarkConfigConstants;
|
||||
import org.artofsolving.jodconverter.office.OfficeUtils;
|
||||
import org.artofsolving.jodconverter.util.ConfigUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* @auther: chenjh
|
||||
* @time: 2019/4/10 16:16
|
||||
* @description 每隔1s读取并更新一次配置文件
|
||||
*/
|
||||
@Component
|
||||
public class ConfigRefreshComponent {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRefreshComponent.class);
|
||||
|
||||
@PostConstruct
|
||||
void refresh() {
|
||||
Thread configRefreshThread = new Thread(new ConfigRefreshThread());
|
||||
configRefreshThread.start();
|
||||
}
|
||||
|
||||
static class ConfigRefreshThread implements Runnable {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Properties properties = new Properties();
|
||||
String text;
|
||||
String media;
|
||||
boolean cacheEnabled;
|
||||
String[] textArray;
|
||||
String[] mediaArray;
|
||||
String officePreviewType;
|
||||
String officePreviewSwitchDisabled;
|
||||
String ftpUsername;
|
||||
String ftpPassword;
|
||||
String ftpControlEncoding;
|
||||
String configFilePath = ConfigUtils.getCustomizedConfigPath();
|
||||
String baseUrl;
|
||||
String trustHost;
|
||||
String pdfDownloadDisable;
|
||||
while (true) {
|
||||
FileReader fileReader = new FileReader(configFilePath);
|
||||
BufferedReader bufferedReader = new BufferedReader(fileReader);
|
||||
properties.load(bufferedReader);
|
||||
OfficeUtils.restorePropertiesFromEnvFormat(properties);
|
||||
cacheEnabled = Boolean.parseBoolean(properties.getProperty("cache.enabled", ConfigConstants.DEFAULT_CACHE_ENABLED));
|
||||
text = properties.getProperty("simText", ConfigConstants.DEFAULT_TXT_TYPE);
|
||||
media = properties.getProperty("media", ConfigConstants.DEFAULT_MEDIA_TYPE);
|
||||
officePreviewType = properties.getProperty("office.preview.type", ConfigConstants.DEFAULT_OFFICE_PREVIEW_TYPE);
|
||||
officePreviewSwitchDisabled = properties.getProperty("office.preview.switch.disabled", ConfigConstants.DEFAULT_OFFICE_PREVIEW_TYPE);
|
||||
ftpUsername = properties.getProperty("ftp.username", ConfigConstants.DEFAULT_FTP_USERNAME);
|
||||
ftpPassword = properties.getProperty("ftp.password", ConfigConstants.DEFAULT_FTP_PASSWORD);
|
||||
ftpControlEncoding = properties.getProperty("ftp.control.encoding", ConfigConstants.DEFAULT_FTP_CONTROL_ENCODING);
|
||||
textArray = text.split(",");
|
||||
mediaArray = media.split(",");
|
||||
baseUrl = properties.getProperty("base.url", ConfigConstants.DEFAULT_BASE_URL);
|
||||
trustHost = properties.getProperty("trust.host", ConfigConstants.DEFAULT_TRUST_HOST);
|
||||
pdfDownloadDisable = properties.getProperty("pdf.download.disable", ConfigConstants.DEFAULT_PDF_DOWNLOAD_DISABLE);
|
||||
ConfigConstants.setCacheEnabledValueValue(cacheEnabled);
|
||||
ConfigConstants.setSimTextValue(textArray);
|
||||
ConfigConstants.setMediaValue(mediaArray);
|
||||
ConfigConstants.setOfficePreviewTypeValue(officePreviewType);
|
||||
ConfigConstants.setFtpUsernameValue(ftpUsername);
|
||||
ConfigConstants.setFtpPasswordValue(ftpPassword);
|
||||
ConfigConstants.setFtpControlEncodingValue(ftpControlEncoding);
|
||||
ConfigConstants.setBaseUrlValue(baseUrl);
|
||||
ConfigConstants.setTrustHostValue(trustHost);
|
||||
ConfigConstants.setOfficePreviewSwitchDisabledValue(officePreviewSwitchDisabled);
|
||||
ConfigConstants.setPdfDownloadDisableValue(pdfDownloadDisable);
|
||||
setWatermarkConfig(properties);
|
||||
bufferedReader.close();
|
||||
fileReader.close();
|
||||
Thread.sleep(1000L);
|
||||
}
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOGGER.error("读取配置文件异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void setWatermarkConfig(Properties properties) {
|
||||
String watermarkTxt = properties.getProperty("watermark.txt", WatermarkConfigConstants.DEFAULT_WATERMARK_TXT);
|
||||
String watermarkXSpace = properties.getProperty("watermark.x.space", WatermarkConfigConstants.DEFAULT_WATERMARK_X_SPACE);
|
||||
String watermarkYSpace = properties.getProperty("watermark.y.space", WatermarkConfigConstants.DEFAULT_WATERMARK_Y_SPACE);
|
||||
String watermarkFont = properties.getProperty("watermark.font", WatermarkConfigConstants.DEFAULT_WATERMARK_FONT);
|
||||
String watermarkFontsize = properties.getProperty("watermark.fontsize", WatermarkConfigConstants.DEFAULT_WATERMARK_FONTSIZE);
|
||||
String watermarkColor = properties.getProperty("watermark.color", WatermarkConfigConstants.DEFAULT_WATERMARK_COLOR);
|
||||
String watermarkAlpha = properties.getProperty("watermark.alpha", WatermarkConfigConstants.DEFAULT_WATERMARK_ALPHA);
|
||||
String watermarkWidth = properties.getProperty("watermark.width", WatermarkConfigConstants.DEFAULT_WATERMARK_WIDTH);
|
||||
String watermarkHeight = properties.getProperty("watermark.height", WatermarkConfigConstants.DEFAULT_WATERMARK_HEIGHT);
|
||||
String watermarkAngle = properties.getProperty("watermark.angle", WatermarkConfigConstants.DEFAULT_WATERMARK_ANGLE);
|
||||
WatermarkConfigConstants.setWatermarkTxtValue(watermarkTxt);
|
||||
WatermarkConfigConstants.setWatermarkXSpaceValue(watermarkXSpace);
|
||||
WatermarkConfigConstants.setWatermarkYSpaceValue(watermarkYSpace);
|
||||
WatermarkConfigConstants.setWatermarkFontValue(watermarkFont);
|
||||
WatermarkConfigConstants.setWatermarkFontsizeValue(watermarkFontsize);
|
||||
WatermarkConfigConstants.setWatermarkColorValue(watermarkColor);
|
||||
WatermarkConfigConstants.setWatermarkAlphaValue(watermarkAlpha);
|
||||
WatermarkConfigConstants.setWatermarkWidthValue(watermarkWidth);
|
||||
WatermarkConfigConstants.setWatermarkHeightValue(watermarkHeight);
|
||||
WatermarkConfigConstants.setWatermarkAngleValue(watermarkAngle);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.FileType;
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.ExtendedModelMap;
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/19.
|
||||
* Content :消费队列中的转换文件
|
||||
*/
|
||||
@Service
|
||||
public class FileConvertQueueTask {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
private final FilePreviewFactory previewFactory;
|
||||
private final CacheService cacheService;
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
public FileConvertQueueTask(FilePreviewFactory previewFactory, CacheService cacheService, FilePreviewCommonService filePreviewCommonService) {
|
||||
this.previewFactory = previewFactory;
|
||||
this.cacheService = cacheService;
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void startTask(){
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(1);
|
||||
executorService.submit(new ConvertTask(previewFactory, cacheService, filePreviewCommonService));
|
||||
logger.info("队列处理文件转换任务启动完成 ");
|
||||
}
|
||||
|
||||
static class ConvertTask implements Runnable {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(ConvertTask.class);
|
||||
private final FilePreviewFactory previewFactory;
|
||||
private final CacheService cacheService;
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
public ConvertTask(FilePreviewFactory previewFactory,
|
||||
CacheService cacheService,
|
||||
FilePreviewCommonService filePreviewCommonService) {
|
||||
this.previewFactory = previewFactory;
|
||||
this.cacheService = cacheService;
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (true) {
|
||||
String url = null;
|
||||
try {
|
||||
url = cacheService.takeQueueTask();
|
||||
if(url != null){
|
||||
FileAttribute fileAttribute = filePreviewCommonService.getFileAttribute(url,null);
|
||||
FileType fileType = fileAttribute.getType();
|
||||
logger.info("正在处理预览转换任务,url:{},预览类型:{}", url, fileType);
|
||||
if(fileType.equals(FileType.compress) || fileType.equals(FileType.office) || fileType.equals(FileType.cad)) {
|
||||
FilePreview filePreview = previewFactory.get(fileAttribute);
|
||||
filePreview.filePreviewHandle(url, new ExtendedModelMap(), fileAttribute);
|
||||
} else {
|
||||
logger.info("预览类型无需处理,url:{},预览类型:{}", url, fileType);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
Thread.sleep(1000*10);
|
||||
} catch (Exception ex){
|
||||
ex.printStackTrace();
|
||||
}
|
||||
logger.info("处理预览转换任务异常,url:{}", url, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
17
server/src/main/java/cn/keking/service/FilePreview.java
Normal file
17
server/src/main/java/cn/keking/service/FilePreview.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :
|
||||
*/
|
||||
public interface FilePreview {
|
||||
|
||||
String TEXT_TYPE = "textType";
|
||||
String DEFAULT_TEXT_TYPE = "simText";
|
||||
|
||||
String filePreviewHandle(String url, Model model, FileAttribute fileAttribute);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.FileType;
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author yudian-it
|
||||
* @date 2017/11/13
|
||||
*/
|
||||
@Component
|
||||
public class FilePreviewCommonService {
|
||||
|
||||
private static final String DEFAULT_CONVERTER_CHARSET = System.getProperty("sun.jnu.encoding");
|
||||
|
||||
private final String fileDir = ConfigConstants.getFileDir();
|
||||
private final CacheService cacheService;
|
||||
|
||||
public FilePreviewCommonService(CacheService cacheService) {
|
||||
this.cacheService = cacheService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 已转换过的文件集合(缓存)
|
||||
*/
|
||||
public Map<String, String> listConvertedFiles() {
|
||||
return cacheService.getPDFCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 已转换过的文件,根据文件名获取
|
||||
*/
|
||||
public String getConvertedFile(String key) {
|
||||
return cacheService.getPDFCache(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key pdf本地路径
|
||||
* @return 已将pdf转换成图片的图片本地相对路径
|
||||
*/
|
||||
public Integer getConvertedPdfImage(String key) {
|
||||
return cacheService.getPdfImageCache(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看文件类型(防止参数中存在.点号或者其他特殊字符,所以先抽取文件名,然后再获取文件类型)
|
||||
*
|
||||
* @param url url
|
||||
* @return 文件类型
|
||||
*/
|
||||
public FileType typeFromUrl(String url) {
|
||||
String nonPramStr = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length());
|
||||
String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
|
||||
return this.typeFromFileName(fileName);
|
||||
}
|
||||
|
||||
private FileType typeFromFileName(String fileName) {
|
||||
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
return FileType.to(fileType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从url中剥离出文件名
|
||||
*
|
||||
* @param url 格式如:http://www.com.cn/20171113164107_月度绩效表模板(新).xls?UCloudPublicKey=ucloudtangshd@weifenf.com14355492830001993909323&Expires=&Signature=I D1NOFtAJSPT16E6imv6JWuq0k=
|
||||
* @return 文件名
|
||||
*/
|
||||
public String getFileNameFromURL(String url) {
|
||||
// 因为url的参数中可能会存在/的情况,所以直接url.lastIndexOf("/")会有问题
|
||||
// 所以先从?处将url截断,然后运用url.lastIndexOf("/")获取文件名
|
||||
String noQueryUrl = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length());
|
||||
return noQueryUrl.substring(noQueryUrl.lastIndexOf("/") + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从路径中获取文件负
|
||||
*
|
||||
* @param path 类似这种:C:\Users\yudian-it\Downloads
|
||||
* @return 文件名
|
||||
*/
|
||||
public String getFileNameFromPath(String path) {
|
||||
return path.substring(path.lastIndexOf(File.separator) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取相对路径
|
||||
*
|
||||
* @param absolutePath 绝对路径
|
||||
* @return 相对路径
|
||||
*/
|
||||
public String getRelativePath(String absolutePath) {
|
||||
return absolutePath.substring(fileDir.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加转换后PDF缓存
|
||||
*
|
||||
* @param fileName pdf文件名
|
||||
* @param value 缓存相对路径
|
||||
*/
|
||||
public void addConvertedFile(String fileName, String value) {
|
||||
cacheService.putPDFCache(fileName, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加转换后图片组缓存
|
||||
*
|
||||
* @param pdfFilePath pdf文件绝对路径
|
||||
* @param num 图片张数
|
||||
*/
|
||||
public void addConvertedPdfImage(String pdfFilePath, int num) {
|
||||
cacheService.putPdfImageCache(pdfFilePath, num);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取redis中压缩包内图片文件
|
||||
*
|
||||
* @param fileKey fileKey
|
||||
* @return 图片文件访问url列表
|
||||
*/
|
||||
public List<String> getImgCache(String fileKey) {
|
||||
return cacheService.getImgCache(fileKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置redis中压缩包内图片文件
|
||||
*
|
||||
* @param fileKey fileKey
|
||||
* @param imgs 图片文件访问url列表
|
||||
*/
|
||||
public void putImgCache(String fileKey, List<String> imgs) {
|
||||
cacheService.putImgCache(fileKey, imgs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件编码格式
|
||||
*
|
||||
* @param path 绝对路径
|
||||
* @return 编码格式
|
||||
*/
|
||||
public String getFileEncodeUTFGBK(String path) {
|
||||
String enc = Charset.forName("GBK").name();
|
||||
File file = new File(path);
|
||||
InputStream in;
|
||||
try {
|
||||
in = new FileInputStream(file);
|
||||
byte[] b = new byte[3];
|
||||
in.read(b);
|
||||
in.close();
|
||||
if (b[0] == -17 && b[1] == -69 && b[2] == -65) {
|
||||
enc = StandardCharsets.UTF_8.name();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("文件编码格式为:" + enc);
|
||||
return enc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对转换后的文件进行操作(改变编码方式)
|
||||
*
|
||||
* @param outFilePath 文件绝对路径
|
||||
*/
|
||||
public void doActionConvertedFile(String outFilePath) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (InputStream inputStream = new FileInputStream(outFilePath);
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CONVERTER_CHARSET))) {
|
||||
String line;
|
||||
while (null != (line = reader.readLine())) {
|
||||
if (line.contains("charset=gb2312")) {
|
||||
line = line.replace("charset=gb2312", "charset=utf-8");
|
||||
}
|
||||
sb.append(line);
|
||||
}
|
||||
// 添加sheet控制头
|
||||
sb.append("<script src=\"js/jquery-3.0.0.min.js\" type=\"text/javascript\"></script>");
|
||||
sb.append("<script src=\"js/excel.header.js\" type=\"text/javascript\"></script>");
|
||||
sb.append("<link rel=\"stylesheet\" href=\"bootstrap/css/bootstrap.min.css\">");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
// 重新写入文件
|
||||
try (FileOutputStream fos = new FileOutputStream(outFilePath);
|
||||
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8))) {
|
||||
writer.write(sb.toString());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件后缀
|
||||
*
|
||||
* @param url url
|
||||
* @return 文件后缀
|
||||
*/
|
||||
private String suffixFromUrl(String url) {
|
||||
String nonPramStr = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length());
|
||||
String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
|
||||
return suffixFromFileName(fileName);
|
||||
}
|
||||
|
||||
private String suffixFromFileName(String fileName) {
|
||||
return fileName.substring(fileName.lastIndexOf(".") + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取url中的参数
|
||||
*
|
||||
* @param url url
|
||||
* @param name 参数名
|
||||
* @return 参数值
|
||||
*/
|
||||
public String getUrlParameterReg(String url, String name) {
|
||||
Map<String, String> mapRequest = new HashMap<>();
|
||||
String strUrlParam = truncateUrlPage(url);
|
||||
if (strUrlParam == null) {
|
||||
return "";
|
||||
}
|
||||
//每个键值为一组
|
||||
String[] arrSplit = strUrlParam.split("[&]");
|
||||
for (String strSplit : arrSplit) {
|
||||
String[] arrSplitEqual = strSplit.split("[=]");
|
||||
//解析出键值
|
||||
if (arrSplitEqual.length > 1) {
|
||||
//正确解析
|
||||
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
|
||||
} else if (!arrSplitEqual[0].equals("")) {
|
||||
//只有参数没有值,不加入
|
||||
mapRequest.put(arrSplitEqual[0], "");
|
||||
}
|
||||
}
|
||||
return mapRequest.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉url中的路径,留下请求参数部分
|
||||
*
|
||||
* @param strURL url地址
|
||||
* @return url请求参数部分
|
||||
*/
|
||||
private String truncateUrlPage(String strURL) {
|
||||
String strAllParam = null;
|
||||
strURL = strURL.trim();
|
||||
String[] arrSplit = strURL.split("[?]");
|
||||
if (strURL.length() > 1) {
|
||||
if (arrSplit.length > 1) {
|
||||
if (arrSplit[1] != null) {
|
||||
strAllParam = arrSplit[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return strAllParam;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件属性
|
||||
*
|
||||
* @param url url
|
||||
* @return 文件属性
|
||||
*/
|
||||
public FileAttribute getFileAttribute(String url, HttpServletRequest req) {
|
||||
FileAttribute attribute = new FileAttribute();
|
||||
String suffix;
|
||||
FileType type;
|
||||
String fileName;
|
||||
String fullFileName = this.getUrlParameterReg(url, "fullfilename");
|
||||
if (StringUtils.hasText(fullFileName)) {
|
||||
fileName = fullFileName;
|
||||
type = this.typeFromFileName(fullFileName);
|
||||
suffix = suffixFromFileName(fullFileName);
|
||||
} else {
|
||||
fileName = getFileNameFromURL(url);
|
||||
type = typeFromUrl(url);
|
||||
suffix = suffixFromUrl(url);
|
||||
}
|
||||
attribute.setType(type);
|
||||
attribute.setName(fileName);
|
||||
attribute.setSuffix(suffix);
|
||||
attribute.setUrl(url);
|
||||
if (req != null) {
|
||||
String officePreviewType = req.getParameter("officePreviewType");
|
||||
String fileKey = req.getParameter("fileKey");
|
||||
if(StringUtils.hasText(officePreviewType)){
|
||||
attribute.setOfficePreviewType(officePreviewType);
|
||||
}
|
||||
if(StringUtils.hasText(fileKey)){
|
||||
attribute.setFileKey(fileKey);
|
||||
}
|
||||
}
|
||||
return attribute;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :
|
||||
*/
|
||||
@Service
|
||||
public class FilePreviewFactory {
|
||||
|
||||
private final ApplicationContext context;
|
||||
|
||||
public FilePreviewFactory(ApplicationContext context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public FilePreview get(FileAttribute fileAttribute) {
|
||||
Map<String, FilePreview> filePreviewMap = context.getBeansOfType(FilePreview.class);
|
||||
return filePreviewMap.get(fileAttribute.getType().getInstanceName());
|
||||
}
|
||||
}
|
||||
134
server/src/main/java/cn/keking/service/OfficeProcessManager.java
Normal file
134
server/src/main/java/cn/keking/service/OfficeProcessManager.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import com.sun.star.document.UpdateDocMode;
|
||||
import cn.keking.extend.ControlDocumentFormatRegistry;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.artofsolving.jodconverter.OfficeDocumentConverter;
|
||||
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
|
||||
import org.artofsolving.jodconverter.office.OfficeManager;
|
||||
import org.artofsolving.jodconverter.office.OfficeUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 创建文件转换器
|
||||
*
|
||||
* @author yudian-it
|
||||
* @date 2017/11/13
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
public class OfficeProcessManager {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(OfficeProcessManager.class);
|
||||
|
||||
private OfficeManager officeManager;
|
||||
|
||||
@PostConstruct
|
||||
public void initOfficeManager() {
|
||||
new Thread(this::startOfficeManager).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动Office组件进程
|
||||
*/
|
||||
private void startOfficeManager(){
|
||||
File officeHome = OfficeUtils.getDefaultOfficeHome();
|
||||
if (officeHome == null) {
|
||||
throw new RuntimeException("找不到office组件,请确认'office.home'配置是否有误");
|
||||
}
|
||||
boolean killOffice = killProcess();
|
||||
if (killOffice) {
|
||||
logger.warn("检测到有正在运行的office进程,已自动结束该进程");
|
||||
}
|
||||
try {
|
||||
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
|
||||
configuration.setOfficeHome(officeHome);
|
||||
configuration.setPortNumber(8100);
|
||||
// 设置任务执行超时为5分钟
|
||||
configuration.setTaskExecutionTimeout(1000 * 60 * 5L);
|
||||
// 设置任务队列超时为24小时
|
||||
//configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
|
||||
officeManager = configuration.buildOfficeManager();
|
||||
officeManager.start();
|
||||
} catch (Exception e) {
|
||||
logger.error("启动office组件失败,请检查office组件是否可用");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
public OfficeDocumentConverter getDocumentConverter() {
|
||||
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, new ControlDocumentFormatRegistry());
|
||||
converter.setDefaultLoadProperties(getLoadProperties());
|
||||
return converter;
|
||||
}
|
||||
|
||||
private Map<String,?> getLoadProperties() {
|
||||
Map<String,Object> loadProperties = new HashMap<>(10);
|
||||
loadProperties.put("Hidden", true);
|
||||
loadProperties.put("ReadOnly", true);
|
||||
loadProperties.put("UpdateDocMode", UpdateDocMode.QUIET_UPDATE);
|
||||
loadProperties.put("CharacterSet", StandardCharsets.UTF_8.name());
|
||||
return loadProperties;
|
||||
}
|
||||
|
||||
private boolean killProcess() {
|
||||
boolean flag = false;
|
||||
Properties props = System.getProperties();
|
||||
try {
|
||||
if (props.getProperty("os.name").toLowerCase().contains("windows")) {
|
||||
Process p = Runtime.getRuntime().exec("cmd /c tasklist ");
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
InputStream os = p.getInputStream();
|
||||
byte[] b = new byte[256];
|
||||
while (os.read(b) > 0) {
|
||||
baos.write(b);
|
||||
}
|
||||
String s = baos.toString();
|
||||
if (s.contains("soffice.bin")) {
|
||||
Runtime.getRuntime().exec("taskkill /im " + "soffice.bin" + " /f");
|
||||
flag = true;
|
||||
}
|
||||
} else {
|
||||
Process p = Runtime.getRuntime().exec(new String[]{"sh","-c","ps -ef | grep " + "soffice.bin"});
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
InputStream os = p.getInputStream();
|
||||
byte[] b = new byte[256];
|
||||
while (os.read(b) > 0) {
|
||||
baos.write(b);
|
||||
}
|
||||
String s = baos.toString();
|
||||
if (StringUtils.ordinalIndexOf(s, "soffice.bin", 3) > 0) {
|
||||
String[] cmd ={"sh","-c","kill -15 `ps -ef|grep " + "soffice.bin" + "|awk 'NR==1{print $2}'`"};
|
||||
Runtime.getRuntime().exec(cmd);
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.error("检测office进程异常", e);
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroyOfficeManager(){
|
||||
if (null != officeManager && officeManager.isRunning()) {
|
||||
officeManager.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package cn.keking.service;
|
||||
|
||||
import org.artofsolving.jodconverter.OfficeDocumentConverter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* @author yudian-it
|
||||
*/
|
||||
@Component
|
||||
public class OfficeToPdfService {
|
||||
private final OfficeProcessManager officeProcessManager;
|
||||
|
||||
public OfficeToPdfService(OfficeProcessManager officeProcessManager) {
|
||||
this.officeProcessManager = officeProcessManager;
|
||||
}
|
||||
|
||||
public void openOfficeToPDF(String inputFilePath, String outputFilePath) {
|
||||
office2pdf(inputFilePath, outputFilePath);
|
||||
}
|
||||
|
||||
|
||||
public static void converterFile(File inputFile, String outputFilePath_end,
|
||||
OfficeDocumentConverter converter) {
|
||||
File outputFile = new File(outputFilePath_end);
|
||||
// 假如目标路径不存在,则新建该路径
|
||||
if (!outputFile.getParentFile().exists()) {
|
||||
outputFile.getParentFile().mkdirs();
|
||||
}
|
||||
converter.convert(inputFile, outputFile);
|
||||
}
|
||||
|
||||
|
||||
public void office2pdf(String inputFilePath, String outputFilePath) {
|
||||
OfficeDocumentConverter converter = officeProcessManager.getDocumentConverter();
|
||||
if (null != inputFilePath) {
|
||||
File inputFile = new File(inputFilePath);
|
||||
// 判断目标文件路径是否为空
|
||||
if (null == outputFilePath) {
|
||||
// 转换后的文件路径
|
||||
String outputFilePath_end = getOutputFilePath(inputFilePath);
|
||||
if (inputFile.exists()) {
|
||||
// 找不到源文件, 则返回
|
||||
converterFile(inputFile, outputFilePath_end,converter);
|
||||
}
|
||||
} else {
|
||||
if (inputFile.exists()) {
|
||||
// 找不到源文件, 则返回
|
||||
converterFile(inputFile, outputFilePath, converter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String getOutputFilePath(String inputFilePath) {
|
||||
return inputFilePath.replaceAll("."+ getPostfix(inputFilePath), ".pdf");
|
||||
}
|
||||
|
||||
public static String getPostfix(String inputFilePath) {
|
||||
return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
|
||||
}
|
||||
|
||||
}
|
||||
36
server/src/main/java/cn/keking/service/cache/CacheService.java
vendored
Normal file
36
server/src/main/java/cn/keking/service/cache/CacheService.java
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
package cn.keking.service.cache;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author: chenjh
|
||||
* @since: 2019/4/2 16:45
|
||||
*/
|
||||
public interface CacheService {
|
||||
|
||||
String FILE_PREVIEW_PDF_KEY = "converted-preview-pdf-file";
|
||||
String FILE_PREVIEW_IMGS_KEY = "converted-preview-imgs-file";//压缩包内图片文件集合
|
||||
String FILE_PREVIEW_PDF_IMGS_KEY = "converted-preview-pdfimgs-file";
|
||||
String TASK_QUEUE_NAME = "convert-task";
|
||||
|
||||
Integer DEFAULT_PDF_CAPACITY = 500000;
|
||||
Integer DEFAULT_IMG_CAPACITY = 500000;
|
||||
Integer DEFAULT_PDFIMG_CAPACITY = 500000;
|
||||
|
||||
void initPDFCachePool(Integer capacity);
|
||||
void initIMGCachePool(Integer capacity);
|
||||
void initPdfImagesCachePool(Integer capacity);
|
||||
void putPDFCache(String key, String value);
|
||||
void putImgCache(String key, List<String> value);
|
||||
Map<String, String> getPDFCache();
|
||||
String getPDFCache(String key);
|
||||
Map<String, List<String>> getImgCache();
|
||||
List<String> getImgCache(String key);
|
||||
Integer getPdfImageCache(String key);
|
||||
void putPdfImageCache(String pdfFilePath, int num);
|
||||
void cleanCache();
|
||||
void addQueueTask(String url);
|
||||
String takeQueueTask() throws InterruptedException;
|
||||
|
||||
}
|
||||
119
server/src/main/java/cn/keking/service/cache/impl/CacheServiceJDKImpl.java
vendored
Normal file
119
server/src/main/java/cn/keking/service/cache/impl/CacheServiceJDKImpl.java
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
package cn.keking.service.cache.impl;
|
||||
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
|
||||
import com.googlecode.concurrentlinkedhashmap.Weighers;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
/**
|
||||
* @auther: chenjh
|
||||
* @time: 2019/4/2 17:21
|
||||
* @description
|
||||
*/
|
||||
@Service
|
||||
@ConditionalOnExpression("'${cache.type:default}'.equals('jdk')")
|
||||
public class CacheServiceJDKImpl implements CacheService {
|
||||
|
||||
private Map<String, String> pdfCache;
|
||||
private Map<String, List<String>> imgCache;
|
||||
private Map<String, Integer> pdfImagesCache;
|
||||
private static final int QUEUE_SIZE = 500000;
|
||||
private final BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);
|
||||
|
||||
@PostConstruct
|
||||
public void initCache(){
|
||||
initPDFCachePool(CacheService.DEFAULT_PDF_CAPACITY);
|
||||
initIMGCachePool(CacheService.DEFAULT_IMG_CAPACITY);
|
||||
initPdfImagesCachePool(CacheService.DEFAULT_PDFIMG_CAPACITY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPDFCache(String key, String value) {
|
||||
pdfCache.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putImgCache(String key, List<String> value) {
|
||||
imgCache.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getPDFCache() {
|
||||
return pdfCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPDFCache(String key) {
|
||||
return pdfCache.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, List<String>> getImgCache() {
|
||||
return imgCache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getImgCache(String key) {
|
||||
if(StringUtils.isEmpty(key)){
|
||||
return new ArrayList<>();
|
||||
}
|
||||
return imgCache.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getPdfImageCache(String key) {
|
||||
return pdfImagesCache.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPdfImageCache(String pdfFilePath, int num) {
|
||||
pdfImagesCache.put(pdfFilePath, num);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cleanCache() {
|
||||
initPDFCachePool(CacheService.DEFAULT_PDF_CAPACITY);
|
||||
initIMGCachePool(CacheService.DEFAULT_IMG_CAPACITY);
|
||||
initPdfImagesCachePool(CacheService.DEFAULT_PDFIMG_CAPACITY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addQueueTask(String url) {
|
||||
blockingQueue.add(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String takeQueueTask() throws InterruptedException {
|
||||
return blockingQueue.take();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initPDFCachePool(Integer capacity) {
|
||||
pdfCache = new ConcurrentLinkedHashMap.Builder<String, String>()
|
||||
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initIMGCachePool(Integer capacity) {
|
||||
imgCache = new ConcurrentLinkedHashMap.Builder<String, List<String>>()
|
||||
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initPdfImagesCachePool(Integer capacity) {
|
||||
pdfImagesCache = new ConcurrentLinkedHashMap.Builder<String, Integer>()
|
||||
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
124
server/src/main/java/cn/keking/service/cache/impl/CacheServiceRedisImpl.java
vendored
Normal file
124
server/src/main/java/cn/keking/service/cache/impl/CacheServiceRedisImpl.java
vendored
Normal file
@@ -0,0 +1,124 @@
|
||||
package cn.keking.service.cache.impl;
|
||||
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import org.redisson.Redisson;
|
||||
import org.redisson.api.RBlockingQueue;
|
||||
import org.redisson.api.RMapCache;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.redisson.config.Config;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @auther: chenjh
|
||||
* @time: 2019/4/2 18:02
|
||||
* @description
|
||||
*/
|
||||
@ConditionalOnExpression("'${cache.type:default}'.equals('redis')")
|
||||
@Service
|
||||
public class CacheServiceRedisImpl implements CacheService {
|
||||
|
||||
private final RedissonClient redissonClient;
|
||||
|
||||
public CacheServiceRedisImpl(Config config) {
|
||||
this.redissonClient = Redisson.create(config);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initPDFCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initIMGCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initPdfImagesCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPDFCache(String key, String value) {
|
||||
RMapCache<String, String> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
|
||||
convertedList.fastPut(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putImgCache(String key, List<String> value) {
|
||||
RMapCache<String, List<String>> convertedList = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
|
||||
convertedList.fastPut(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getPDFCache() {
|
||||
return redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPDFCache(String key) {
|
||||
RMapCache<String, String> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
|
||||
return convertedList.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, List<String>> getImgCache() {
|
||||
return redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getImgCache(String key) {
|
||||
RMapCache<String, List<String>> convertedList = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
|
||||
return convertedList.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer getPdfImageCache(String key) {
|
||||
RMapCache<String, Integer> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
|
||||
return convertedList.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPdfImageCache(String pdfFilePath, int num) {
|
||||
RMapCache<String, Integer> convertedList = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
|
||||
convertedList.fastPut(pdfFilePath, num);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cleanCache() {
|
||||
cleanPdfCache();
|
||||
cleanImgCache();
|
||||
cleanPdfImgCache();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addQueueTask(String url) {
|
||||
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME);
|
||||
queue.addAsync(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String takeQueueTask() throws InterruptedException {
|
||||
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME);
|
||||
return queue.take();
|
||||
}
|
||||
|
||||
private void cleanPdfCache() {
|
||||
RMapCache<String, String> pdfCache = redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
|
||||
pdfCache.clear();
|
||||
}
|
||||
|
||||
private void cleanImgCache() {
|
||||
RMapCache<String, List<String>> imgCache = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
|
||||
imgCache.clear();
|
||||
}
|
||||
|
||||
private void cleanPdfImgCache() {
|
||||
RMapCache<String, Integer> pdfImg = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
|
||||
pdfImg.clear();
|
||||
}
|
||||
}
|
||||
246
server/src/main/java/cn/keking/service/cache/impl/CacheServiceRocksDBImpl.java
vendored
Normal file
246
server/src/main/java/cn/keking/service/cache/impl/CacheServiceRocksDBImpl.java
vendored
Normal file
@@ -0,0 +1,246 @@
|
||||
package cn.keking.service.cache.impl;
|
||||
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import org.artofsolving.jodconverter.util.ConfigUtils;
|
||||
import org.rocksdb.RocksDB;
|
||||
import org.rocksdb.RocksDBException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
|
||||
/**
|
||||
* @auther: chenjh
|
||||
* @time: 2019/4/22 11:02
|
||||
* @description
|
||||
*/
|
||||
@ConditionalOnExpression("'${cache.type:default}'.equals('default')")
|
||||
@Service
|
||||
public class CacheServiceRocksDBImpl implements CacheService {
|
||||
|
||||
static {
|
||||
RocksDB.loadLibrary();
|
||||
}
|
||||
|
||||
private static final String DB_PATH = ConfigUtils.getHomePath() + File.separator + "cache";
|
||||
|
||||
private static final int QUEUE_SIZE = 500000;
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(CacheServiceRocksDBImpl.class);
|
||||
|
||||
private final BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);
|
||||
|
||||
private RocksDB db;
|
||||
|
||||
{
|
||||
try {
|
||||
db = RocksDB.open(DB_PATH);
|
||||
if (db.get(FILE_PREVIEW_PDF_KEY.getBytes()) == null) {
|
||||
Map<String, String> initPDFCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
|
||||
}
|
||||
if (db.get(FILE_PREVIEW_IMGS_KEY.getBytes()) == null) {
|
||||
Map<String, List<String>> initIMGCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
|
||||
}
|
||||
if (db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()) == null) {
|
||||
Map<String, Integer> initPDFIMGCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
|
||||
}
|
||||
} catch (RocksDBException | IOException e) {
|
||||
LOGGER.error("Uable to init RocksDB" + e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void initPDFCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initIMGCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initPdfImagesCachePool(Integer capacity) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPDFCache(String key, String value) {
|
||||
try {
|
||||
Map<String, String> pdfCacheItem = getPDFCache();
|
||||
pdfCacheItem.put(key, value);
|
||||
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(pdfCacheItem));
|
||||
} catch (RocksDBException | IOException e) {
|
||||
LOGGER.error("Put into RocksDB Exception" + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putImgCache(String key, List<String> value) {
|
||||
try {
|
||||
Map<String, List<String>> imgCacheItem = getImgCache();
|
||||
imgCacheItem.put(key, value);
|
||||
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(imgCacheItem));
|
||||
} catch (RocksDBException | IOException e) {
|
||||
LOGGER.error("Put into RocksDB Exception" + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, String> getPDFCache() {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
try{
|
||||
result = (Map<String, String>) toObject(db.get(FILE_PREVIEW_PDF_KEY.getBytes()));
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public String getPDFCache(String key) {
|
||||
String result = "";
|
||||
try{
|
||||
Map<String, String> map = (Map<String, String>) toObject(db.get(FILE_PREVIEW_PDF_KEY.getBytes()));
|
||||
result = map.get(key);
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, List<String>> getImgCache() {
|
||||
Map<String, List<String>> result = new HashMap<>();
|
||||
try{
|
||||
result = (Map<String, List<String>>) toObject(db.get(FILE_PREVIEW_IMGS_KEY.getBytes()));
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> getImgCache(String key) {
|
||||
List<String> result = new ArrayList<>();
|
||||
Map<String, List<String>> map;
|
||||
try{
|
||||
map = (Map<String, List<String>>) toObject(db.get(FILE_PREVIEW_IMGS_KEY.getBytes()));
|
||||
result = map.get(key);
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Integer getPdfImageCache(String key) {
|
||||
Integer result = 0;
|
||||
Map<String, Integer> map;
|
||||
try{
|
||||
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
|
||||
result = map.get(key);
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void putPdfImageCache(String pdfFilePath, int num) {
|
||||
try {
|
||||
Map<String, Integer> pdfImageCacheItem = getPdfImageCaches();
|
||||
pdfImageCacheItem.put(pdfFilePath, num);
|
||||
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(pdfImageCacheItem));
|
||||
} catch (RocksDBException | IOException e) {
|
||||
LOGGER.error("Put into RocksDB Exception" + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cleanCache() {
|
||||
try {
|
||||
cleanPdfCache();
|
||||
cleanImgCache();
|
||||
cleanPdfImgCache();
|
||||
} catch (IOException | RocksDBException e) {
|
||||
LOGGER.error("Clean Cache Exception" + e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addQueueTask(String url) {
|
||||
blockingQueue.add(url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String takeQueueTask() throws InterruptedException {
|
||||
return blockingQueue.take();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Integer> getPdfImageCaches() {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
try{
|
||||
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
|
||||
} catch (RocksDBException | IOException | ClassNotFoundException e) {
|
||||
LOGGER.error("Get from RocksDB Exception" + e);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
private byte[] toByteArray (Object obj) throws IOException {
|
||||
byte[] bytes;
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(obj);
|
||||
oos.flush();
|
||||
bytes = bos.toByteArray ();
|
||||
oos.close();
|
||||
bos.close();
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private Object toObject (byte[] bytes) throws IOException, ClassNotFoundException {
|
||||
Object obj;
|
||||
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream (bis);
|
||||
obj = ois.readObject();
|
||||
ois.close();
|
||||
bis.close();
|
||||
return obj;
|
||||
}
|
||||
|
||||
private void cleanPdfCache() throws IOException, RocksDBException {
|
||||
Map<String, String> initPDFCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
|
||||
}
|
||||
|
||||
private void cleanImgCache() throws IOException, RocksDBException {
|
||||
Map<String, List<String>> initIMGCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
|
||||
}
|
||||
|
||||
private void cleanPdfImgCache() throws IOException, RocksDBException {
|
||||
Map<String, Integer> initPDFIMGCache = new HashMap<>();
|
||||
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.CadUtils;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import cn.keking.utils.PdfUtils;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import static cn.keking.service.impl.OfficeFilePreviewImpl.getPreviewType;
|
||||
|
||||
/**
|
||||
* @author chenjh
|
||||
* @since 2019/11/21 14:28
|
||||
*/
|
||||
@Service
|
||||
public class CadFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
private final CadUtils cadUtils;
|
||||
|
||||
private final PdfUtils pdfUtils;
|
||||
|
||||
public CadFilePreviewImpl(FilePreviewCommonService filePreviewCommonService,
|
||||
DownloadUtils downloadUtils,
|
||||
CadUtils cadUtils,
|
||||
PdfUtils pdfUtils) {
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
this.downloadUtils = downloadUtils;
|
||||
this.cadUtils = cadUtils;
|
||||
this.pdfUtils = pdfUtils;
|
||||
|
||||
}
|
||||
|
||||
private static final String OFFICE_PREVIEW_TYPE_IMAGE = "image";
|
||||
private static final String OFFICE_PREVIEW_TYPE_ALL_IMAGES = "allImages";
|
||||
private static final String FILE_DIR = ConfigConstants.getFileDir();
|
||||
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
// 预览Type,参数传了就取参数的,没传取系统默认
|
||||
String officePreviewType = model.asMap().get("officePreviewType") == null ? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString();
|
||||
String baseUrl = BaseUrlFilter.getBaseUrl();
|
||||
String suffix=fileAttribute.getSuffix();
|
||||
String fileName=fileAttribute.getName();
|
||||
String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
|
||||
String outFilePath = FILE_DIR + pdfName;
|
||||
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
|
||||
if (!filePreviewCommonService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
String filePath;
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, null);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
filePath = response.getContent();
|
||||
if (StringUtils.hasText(outFilePath)) {
|
||||
boolean convertResult = cadUtils.cadToPdf(filePath, outFilePath);
|
||||
if (!convertResult) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", "cad文件转换异常,请联系管理员");
|
||||
return "fileNotSupported";
|
||||
}
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
filePreviewCommonService.addConvertedFile(pdfName, filePreviewCommonService.getRelativePath(outFilePath));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
|
||||
return getPreviewType(model, fileAttribute, officePreviewType, baseUrl, pdfName, outFilePath, pdfUtils, OFFICE_PREVIEW_TYPE_IMAGE);
|
||||
}
|
||||
model.addAttribute("pdfUrl", pdfName);
|
||||
return "pdf";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import cn.keking.utils.ZipReader;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :处理压缩包文件
|
||||
*/
|
||||
@Service
|
||||
public class CompressFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
private final ZipReader zipReader;
|
||||
|
||||
public CompressFilePreviewImpl(FilePreviewCommonService filePreviewCommonService,
|
||||
DownloadUtils downloadUtils,
|
||||
ZipReader zipReader) {
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
this.downloadUtils = downloadUtils;
|
||||
this.zipReader = zipReader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
String fileName=fileAttribute.getName();
|
||||
String suffix=fileAttribute.getSuffix();
|
||||
String fileTree = null;
|
||||
// 判断文件名是否存在(redis缓存读取)
|
||||
if (!StringUtils.hasText(filePreviewCommonService.getConvertedFile(fileName)) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
String filePath = response.getContent();
|
||||
if ("zip".equalsIgnoreCase(suffix) || "jar".equalsIgnoreCase(suffix) || "gzip".equalsIgnoreCase(suffix)) {
|
||||
fileTree = zipReader.readZipFile(filePath, fileName);
|
||||
} else if ("rar".equalsIgnoreCase(suffix)) {
|
||||
fileTree = zipReader.unRar(filePath, fileName);
|
||||
} else if ("7z".equalsIgnoreCase(suffix)) {
|
||||
fileTree = zipReader.read7zFile(filePath, fileName);
|
||||
}
|
||||
if (fileTree != null && !"null".equals(fileTree) && ConfigConstants.isCacheEnabled()) {
|
||||
filePreviewCommonService.addConvertedFile(fileName, fileTree);
|
||||
}
|
||||
} else {
|
||||
fileTree = filePreviewCommonService.getConvertedFile(fileName);
|
||||
}
|
||||
if (fileTree != null && !"null".equals(fileTree)) {
|
||||
model.addAttribute("fileTree", fileTree);
|
||||
return "compress";
|
||||
} else {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", "压缩文件类型不受支持,尝试在压缩的时候选择RAR4格式");
|
||||
return "fileNotSupported";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.service.FilePreview;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* @author kl (http://kailing.pub)
|
||||
* @since 2020/12/25
|
||||
*/
|
||||
@Service
|
||||
public class MarkdownFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final SimTextFilePreviewImpl simTextFilePreview;
|
||||
|
||||
public MarkdownFilePreviewImpl(SimTextFilePreviewImpl simTextFilePreview) {
|
||||
this.simTextFilePreview = simTextFilePreview;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
model.addAttribute(TEXT_TYPE,"markdown");
|
||||
return simTextFilePreview.filePreviewHandle(url, model, fileAttribute);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
/**
|
||||
* @author : kl
|
||||
* @authorboke : kailing.pub
|
||||
* @create : 2018-03-25 上午11:58
|
||||
* @description:
|
||||
**/
|
||||
@Service
|
||||
public class MediaFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
public MediaFilePreviewImpl(DownloadUtils downloadUtils,
|
||||
FilePreviewCommonService filePreviewCommonService) {
|
||||
this.downloadUtils = downloadUtils;
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, fileAttribute.getName());
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", fileAttribute.getSuffix());
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
} else {
|
||||
model.addAttribute("mediaUrl", BaseUrlFilter.getBaseUrl() + filePreviewCommonService.getRelativePath(response.getContent()));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("mediaUrl", url);
|
||||
}
|
||||
model.addAttribute("mediaUrl", url);
|
||||
String suffix=fileAttribute.getSuffix();
|
||||
if ("flv".equalsIgnoreCase(suffix)) {
|
||||
return "flv";
|
||||
}
|
||||
return "media";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import cn.keking.service.OfficeToPdfService;
|
||||
import cn.keking.utils.PdfUtils;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :处理office文件
|
||||
*/
|
||||
@Service
|
||||
public class OfficeFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
private final PdfUtils pdfUtils;
|
||||
private final DownloadUtils downloadUtils;
|
||||
private final OfficeToPdfService officeToPdfService;
|
||||
|
||||
public OfficeFilePreviewImpl(FilePreviewCommonService filePreviewCommonService, PdfUtils pdfUtils, DownloadUtils downloadUtils, OfficeToPdfService officeToPdfService) {
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
this.pdfUtils = pdfUtils;
|
||||
this.downloadUtils = downloadUtils;
|
||||
this.officeToPdfService = officeToPdfService;
|
||||
}
|
||||
|
||||
public static final String OFFICE_PREVIEW_TYPE_IMAGE = "image";
|
||||
public static final String OFFICE_PREVIEW_TYPE_ALL_IMAGES = "allImages";
|
||||
private static final String FILE_DIR = ConfigConstants.getFileDir();
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
// 预览Type,参数传了就取参数的,没传取系统默认
|
||||
String officePreviewType = fileAttribute.getOfficePreviewType();
|
||||
String baseUrl = BaseUrlFilter.getBaseUrl();
|
||||
String suffix=fileAttribute.getSuffix();
|
||||
String fileName=fileAttribute.getName();
|
||||
boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx");
|
||||
String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf");
|
||||
String outFilePath = FILE_DIR + pdfName;
|
||||
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
|
||||
if (!filePreviewCommonService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
String filePath;
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, null);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
filePath = response.getContent();
|
||||
if (StringUtils.hasText(outFilePath)) {
|
||||
officeToPdfService.openOfficeToPDF(filePath, outFilePath);
|
||||
if (isHtml) {
|
||||
// 对转换后的文件进行操作(改变编码方式)
|
||||
filePreviewCommonService.doActionConvertedFile(outFilePath);
|
||||
}
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
filePreviewCommonService.addConvertedFile(pdfName, filePreviewCommonService.getRelativePath(outFilePath));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isHtml && baseUrl != null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) {
|
||||
return getPreviewType(model, fileAttribute, officePreviewType, baseUrl, pdfName, outFilePath, pdfUtils, OFFICE_PREVIEW_TYPE_IMAGE);
|
||||
}
|
||||
model.addAttribute("pdfUrl", pdfName);
|
||||
return isHtml ? "html" : "pdf";
|
||||
}
|
||||
|
||||
static String getPreviewType(Model model, FileAttribute fileAttribute, String officePreviewType, String baseUrl, String pdfName, String outFilePath, PdfUtils pdfUtils, String officePreviewTypeImage) {
|
||||
List<String> imageUrls = pdfUtils.pdf2jpg(outFilePath, pdfName, baseUrl);
|
||||
if (imageUrls == null || imageUrls.size() < 1) {
|
||||
model.addAttribute("msg", "office转图片异常,请联系管理员");
|
||||
model.addAttribute("fileType",fileAttribute.getSuffix());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
model.addAttribute("imgurls", imageUrls);
|
||||
model.addAttribute("currentUrl", imageUrls.get(0));
|
||||
if (officePreviewTypeImage.equals(officePreviewType)) {
|
||||
return "officePicture";
|
||||
} else {
|
||||
return "picture";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.service.FilePreview;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :其他文件
|
||||
*/
|
||||
@Service
|
||||
public class OtherFilePreviewImpl implements FilePreview {
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
model.addAttribute("fileType",fileAttribute.getSuffix());
|
||||
model.addAttribute("msg", "系统还不支持该格式文件的在线预览");
|
||||
return "fileNotSupported";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import cn.keking.utils.PdfUtils;
|
||||
import cn.keking.web.filter.BaseUrlFilter;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :处理pdf文件
|
||||
*/
|
||||
@Service
|
||||
public class PdfFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
private final PdfUtils pdfUtils;
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
private static final String FILE_DIR = ConfigConstants.getFileDir();
|
||||
|
||||
public PdfFilePreviewImpl(FilePreviewCommonService filePreviewCommonService,
|
||||
PdfUtils pdfUtils,
|
||||
DownloadUtils downloadUtils) {
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
this.pdfUtils = pdfUtils;
|
||||
this.downloadUtils = downloadUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
String suffix=fileAttribute.getSuffix();
|
||||
String fileName=fileAttribute.getName();
|
||||
String officePreviewType = fileAttribute.getOfficePreviewType();
|
||||
String baseUrl = BaseUrlFilter.getBaseUrl();
|
||||
String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
|
||||
String outFilePath = FILE_DIR + pdfName;
|
||||
if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType)) {
|
||||
//当文件不存在时,就去下载
|
||||
if (!filePreviewCommonService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
outFilePath = response.getContent();
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
filePreviewCommonService.addConvertedFile(pdfName, filePreviewCommonService.getRelativePath(outFilePath));
|
||||
}
|
||||
}
|
||||
List<String> imageUrls = pdfUtils.pdf2jpg(outFilePath, pdfName, baseUrl);
|
||||
if (imageUrls == null || imageUrls.size() < 1) {
|
||||
model.addAttribute("msg", "pdf转图片异常,请联系管理员");
|
||||
model.addAttribute("fileType",fileAttribute.getSuffix());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
model.addAttribute("imgurls", imageUrls);
|
||||
model.addAttribute("currentUrl", imageUrls.get(0));
|
||||
if (OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType)) {
|
||||
return "officePicture";
|
||||
} else {
|
||||
return "picture";
|
||||
}
|
||||
} else {
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
if (!filePreviewCommonService.listConvertedFiles().containsKey(pdfName) || !ConfigConstants.isCacheEnabled()) {
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, pdfName);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", suffix);
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
model.addAttribute("pdfUrl", filePreviewCommonService.getRelativePath(response.getContent()));
|
||||
if (ConfigConstants.isCacheEnabled()) {
|
||||
// 加入缓存
|
||||
filePreviewCommonService.addConvertedFile(pdfName, filePreviewCommonService.getRelativePath(outFilePath));
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("pdfUrl", pdfName);
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("pdfUrl", url);
|
||||
}
|
||||
}
|
||||
return "pdf";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.service.FilePreviewCommonService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :图片文件处理
|
||||
*/
|
||||
@Service
|
||||
public class PictureFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final FilePreviewCommonService filePreviewCommonService;
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
public PictureFilePreviewImpl(FilePreviewCommonService filePreviewCommonService,
|
||||
DownloadUtils downloadUtils) {
|
||||
this.filePreviewCommonService = filePreviewCommonService;
|
||||
this.downloadUtils = downloadUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
List<String> imgUrls = new ArrayList<>();
|
||||
imgUrls.add(url);
|
||||
String fileKey = fileAttribute.getFileKey();
|
||||
List<String> zipImgUrls = filePreviewCommonService.getImgCache(fileKey);
|
||||
if (!CollectionUtils.isEmpty(zipImgUrls)) {
|
||||
imgUrls.addAll(zipImgUrls);
|
||||
}
|
||||
// 不是http开头,浏览器不能直接访问,需下载到本地
|
||||
if (url != null && !url.toLowerCase().startsWith("http")) {
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, null);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("fileType", fileAttribute.getSuffix());
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
return "fileNotSupported";
|
||||
} else {
|
||||
String file = filePreviewCommonService.getRelativePath(response.getContent());
|
||||
imgUrls.clear();
|
||||
imgUrls.add(file);
|
||||
model.addAttribute("imgurls", imgUrls);
|
||||
model.addAttribute("currentUrl", file);
|
||||
}
|
||||
} else {
|
||||
model.addAttribute("imgurls", imgUrls);
|
||||
model.addAttribute("currentUrl", url);
|
||||
}
|
||||
return "picture";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.model.FileType;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.util.Base64Utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
|
||||
/**
|
||||
* Created by kl on 2018/1/17.
|
||||
* Content :处理文本文件
|
||||
*/
|
||||
@Service
|
||||
public class SimTextFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
|
||||
public SimTextFilePreviewImpl(DownloadUtils downloadUtils) {
|
||||
this.downloadUtils = downloadUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
String fileName = fileAttribute.getName();
|
||||
ReturnResponse<String> response = downloadUtils.downLoad(fileAttribute, fileName);
|
||||
if (0 != response.getCode()) {
|
||||
model.addAttribute("msg", response.getMsg());
|
||||
model.addAttribute("fileType", fileAttribute.getSuffix());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
try {
|
||||
File originFile = new File(response.getContent());
|
||||
String xmlString = FileUtils.readFileToString(originFile, StandardCharsets.UTF_8);
|
||||
model.addAttribute("textData", Base64Utils.encodeToString(xmlString.getBytes()));
|
||||
} catch (IOException e) {
|
||||
model.addAttribute("msg", e.getLocalizedMessage());
|
||||
model.addAttribute("fileType", fileAttribute.getSuffix());
|
||||
return "fileNotSupported";
|
||||
}
|
||||
if (!model.containsAttribute(TEXT_TYPE)) {
|
||||
model.addAttribute(TEXT_TYPE, DEFAULT_TEXT_TYPE);
|
||||
}
|
||||
return "txt";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package cn.keking.service.impl;
|
||||
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.service.FilePreview;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.ui.Model;
|
||||
|
||||
/**
|
||||
* @author kl (http://kailing.pub)
|
||||
* @since 2020/12/25
|
||||
*/
|
||||
@Service
|
||||
public class XmlFilePreviewImpl implements FilePreview {
|
||||
|
||||
private final SimTextFilePreviewImpl simTextFilePreview;
|
||||
|
||||
public XmlFilePreviewImpl(SimTextFilePreviewImpl simTextFilePreview) {
|
||||
this.simTextFilePreview = simTextFilePreview;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
|
||||
model.addAttribute(TEXT_TYPE,"xml");
|
||||
return simTextFilePreview.filePreviewHandle(url, model, fileAttribute);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user