提交 4b48b7ae authored 作者: renjiancai's avatar renjiancai

--no commit message

上级 1f50a18d
package com.zrqx.file.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nl.siegmann.epublib.domain.TOCReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.zrqx.core.exception.BaseException;
import com.zrqx.core.model.file.FileInfo;
import com.zrqx.core.model.resource.articlelibrary.ArticleLibrary;
import com.zrqx.core.model.resource.articlelibrary.ChapterLibrary;
import com.zrqx.core.model.resource.ebook.Book;
import com.zrqx.core.model.resource.ebook.Ebook;
import com.zrqx.core.model.resource.imagelibrary.ImageLibrary;
import com.zrqx.core.util.datatype.DateUtils;
import com.zrqx.core.util.datatype.UUIDUtil;
import com.zrqx.core.vo.resource.EpubVo;
import com.zrqx.file.commons.Redis;
import com.zrqx.file.service.FileService;
import com.zrqx.file.util.EpubResolve;
import com.zrqx.file.util.EpubUtil;
import com.zrqx.file.util.MockMultipartFile;
@RestController
@RequestMapping(value = "/epub")
@Api(description = "文件上传下载服务")
public class EpubController {
private final static Logger logger = LoggerFactory.getLogger(EpubController.class);
@Autowired
private FileService service;
@Value("${file-root-path}")
private String rootPath;
@Autowired
private Redis redis;
private EpubVo ev = new EpubVo();
@ApiOperation(value = "epub上传 返回token")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(Integer dtId ,String code, Integer nationsType, @RequestParam("file") MultipartFile file) throws Exception {
// 获取原文件的全名称
String originalFilename = file.getOriginalFilename();
// 源文件的名称,不带后缀
String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
FileInfo fileInfo = new FileInfo();
fileInfo.setOriginalFileName(originalFilename);
int count = service.selectCount(fileInfo);
if (count > 0) {
throw new BaseException("epub已存在");
}
ev.setCode(code);
ev.setDtId(dtId);
Ebook ebook = new Ebook();
Book book = new Book();
book.setId(UUIDUtil.getUUID());
// epub工具类
EpubUtil epubUtil = new EpubUtil();
// epub解析方法类
EpubResolve er = new EpubResolve();
//book.setNationsType(nationsType);
epubUtil.setEpubFile(file.getInputStream());
FileInfo entity = er.uploadFile(file, rootPath + fileName);
if (!service.insert(entity)) {
throw new BaseException("上传失败!");
} else {
String path = entity.getPath();
// 载入电子书资源
epubUtil.setEpubFile(file.getInputStream());
/**
* 保存元数据相关内容
*/
// 名称
book.setName(epubUtil.getBookTitle());
// 作者
book.setAuthor(epubUtil.getAuthor());
// 出版时间
book.setPublishTime(DateUtils.dateTimeToStrYMD(epubUtil.getPublishDate()));
// 出版单位
book.setPublisher(epubUtil.getPublisher());
// isbn
book.setIsbn(epubUtil.getISBN());
ev.setBook(book);
/**
* 保存电子书相关内容
*/
ebook.setId(book.getId());
ebook.setUploadTime(new Date());
// 修改时间4
ebook.setUpdateTime(new Date());// 设置为上传时间
// 关键字(图书的名字)20
ebook.setKeywords(epubUtil.getBookTitle());
ebook.setEpubFile(path);
ebook.setFileName(entity.getFileName());
ebook.setSynopsis(epubUtil.getDescription());
// css路径
FileInfo cssentity = er.getCss(epubUtil, rootPath + fileName);
if (!service.insert(cssentity)) {
throw new BaseException("css文件上传失败!");
}
ebook.setCssPath(cssentity.getPath());
// 保存封面
if(epubUtil.getCover() != null){
String imgName = epubUtil.getCover().getHref().substring(epubUtil.getCover().getHref().lastIndexOf("/") + 1);
MultipartFile multipartFile = new MockMultipartFile(imgName, imgName, "image/jpeg", epubUtil.getCover().getInputStream());
FileInfo cover = er.uploadFile(multipartFile, rootPath + fileName);
ebook.setImg(cover.getFileName());
}
ev.setEbook(ebook);
// ---------获取图书所有内容------------
List<TOCReference> listReferences = epubUtil.getTocReferences();
// 当前目录
TOCReference tocRef = new TOCReference();
// 初始化顶级目录id 为 "0"
tocRef.setFragmentId("0");
// 初始化顶级目录层级为 0
int level = 0;
// *******************解析章节信息*************
Set<ChapterLibrary> chapterSet = new HashSet<>();
chapterSet = er.setChapter(listReferences, tocRef, level, ebook, chapterSet);
ev.setChapterSet(chapterSet);
// ******************解析内容信息**************
Set<ArticleLibrary> contentSet = new HashSet<>();
Map<String, String> imgtzMap = new HashMap<>();// 图片图注信息
Object[] data = new Object[2];
data = er.setContent(listReferences, contentSet, ebook, imgtzMap, data);
ev.setArticleSet(contentSet);
// ************导入图书中的图片资源************
if (data[1] instanceof Map && data[1] != null) {
imgtzMap = (Map<String, String>) data[1];
// 图片info
List<FileInfo> imageInfoList = er.getImages(epubUtil, rootPath + fileName);
if (!service.insertList(imageInfoList)) {
throw new BaseException("图片上传失败!");
}
importBookImgs(imgtzMap, book, code, rootPath + fileName, imageInfoList);
}
redis.set(entity.getFileName(), ev);
}
return entity.getFileName();
}
/**
* (后台) 导入epub中的图片资源到resource
*
* @throws Exception
*/
public void importBookImgs(Map<String, String> imgtzMap, Book book, String classifyCode, String relativeBookFolderPath, List<FileInfo> imageInfoList) throws Exception {
Set<ImageLibrary> imageSet = new HashSet<ImageLibrary>();
try {
// 保存图书中的图片资源到资源表中
for (FileInfo file : imageInfoList) {
ImageLibrary il = new ImageLibrary();
String imgName = file.getPath().substring(file.getPath().lastIndexOf("/") + 1);
String showName = imgtzMap.get(file.getPath());
// 图片的页面显示名称(图注),没有默认为原文件名
showName = (showName != null && !showName.equals("")) ? showName : imgName;
il.setName(showName);
// il.setImage(relativeBookFolderPath + file.getPath());
il.setUploadTime(new Date());
il.setBookId(book.getId());
//il.setNationsType(book.getNationsType());
il.setBookName(book.getName());
il.setStatus(0);
il.setImage(file.getFileName());
imageSet.add(il);
}
ev.setImageSet(imageSet);
} catch (Exception e) {
// 保存操作日志
throw new Exception();
}
}
}
......@@ -195,14 +195,6 @@ public class FileController {
DownloadUtil.start(response, f, fileName);
}
}
@ApiOperation(value = "生成二维码zip")
@RequestMapping(value = "/download/zip", method = RequestMethod.POST)
public String downLoad(HttpServletResponse response,@RequestBody List<String> fileNames) throws Exception {
Example example =service.createExample();
example.createCriteria().andIn("fileName", fileNames);
List<FileInfo> list = service.selectByExample(example);
return ZipUtil.zip(rootPath, list);
}
@ApiOperation(value = "导出二维码zip")
@RequestMapping(value = "/download/zip", method = RequestMethod.GET)
public String downLoad(HttpServletResponse response,String fileName) throws Exception {
......
/**
* @Title: EpubController.java
* @Package epub
* @Description: TODO(用一句话描述该文件做什么)
* @author 段思铭
* @date 2015-5-15 上午10:17:55
* @version V5.0
*/
package com.zrqx.file.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.LinkedMap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.zrqx.core.model.file.FileInfo;
import com.zrqx.core.model.resource.articlelibrary.ArticleLibrary;
import com.zrqx.core.model.resource.articlelibrary.ChapterLibrary;
import com.zrqx.core.model.resource.ebook.Book;
import com.zrqx.core.model.resource.ebook.Ebook;
import com.zrqx.core.util.datatype.DateUtils;
import com.zrqx.core.util.datatype.UUIDUtil;
import freemarker.template.utility.DateUtil;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.TOCReference;
/**
* @ClassName: EpubController
* @Description: TODO(这里用一句话描述这个类的作用)
* @author 段思铭
* @date 2015-5-15 上午10:17:55
*
*/
public class EpubResolve {
private final static Logger logger = LoggerFactory.getLogger(EpubResolve.class);
/**
* 将html文件解析成Document对象
* @param spineReference
* @return
*/
private Document getDocument(TOCReference spineReference) {
// 获取页所有html内容
String html = "";
try {
// 增加非空判断
if (spineReference.getResource() != null) {
html = new String(spineReference.getResource().getData(), "utf-8");
}
} catch (IOException e) {
e.printStackTrace();
}
// jsoup解析,生成doc对象
Document doc = Jsoup.parse(html);
return doc;
}
/**
* 获取图书所有的id
*
* @param tocref
* @param alltitle
* @param flag
* @author 李禚
* @return
*/
public Map<String, TOCReference> getAllId(TOCReference tocref, Map<String, TOCReference> allid, int flag) {// 判断是否是父章节,父=0,++
if (flag == 0) {
String id = tocref.getFragmentId();
if (!"".equals(id)) {
allid.put(id, tocref);
}
}
if (tocref.getChildren().size() > 0) {
flag++;
for (TOCReference toc : tocref.getChildren()) {
String id1 = toc.getFragmentId();
if (!"".equals(id1)) {
allid.put(id1, toc);
}
if (toc.getChildren().size() > 0) {
getAllId(toc, allid, flag);
}
}
}
return allid;
}
// **********************************************************************************
// ***************************** 图书信息 *****************************
// **********************************************************************************
/**
* 通过版权页获取图书部分信息
*
* @Title: setBookInfo
* @Description:
* @param listReferences
* @return
* @throws Exception
* @return Map<String,Object> 返回类型
* @author 刘自耀
* @date 2015-6-29 下午4:12:28
*/
public Book setBookInfo(EpubUtil epubUtil, Book book) {
// 保存图书部分信息
// 获取图书的目录结构标题及对应的资源内容
List<TOCReference> listReferences = epubUtil.getTocReferences();
int index = 0;
for (; index < listReferences.size(); index++) {
TOCReference spineReference = listReferences.get(index);
// 判断只获取版权页的内容
if (spineReference.getTitle().contains("版权")) {
// dom选择器,获取doc中的所有<p>标签
Elements ps = getDocument(spineReference).select("p");
// 遍历Elements 中的元素
int i = 0;
for (Element p : ps) {
// 文本内容
String ptext = p.text().replaceAll("[  ]", "");
if (ptext != null && !ptext.equals("")) {
// 著作方式13(著,编著,编,主编,改编,译,编译,绘,摄,书)
String editor = "";
if (i == 1 && StringUtils.anyContains(ptext, "著,编著,编,主编,改编,译,编译,绘,摄,书")) {
if (ptext.contains("—") || ptext.contains("-")) {
editor = ptext.substring(0, ptext.lastIndexOf("—") > 0 ? ptext.lastIndexOf("—") : ptext.lastIndexOf("-"));
} else {
editor = ptext.substring(0, StringUtils.containsMaxIndex(ptext, "著,编") + 1);
editor = editor.length() > 90 ? "" : editor;
}
}
//book.setEditor(editor);
book.setExecutiveEditor(editor);
// 中图分类编号14 ①G239.21
String clcnumberCode = "";
if (ptext.contains("Ⅳ.")) {
if (ptext.lastIndexOf("Ⅳ.") > 0) {
clcnumberCode = ptext.substring(ptext.lastIndexOf("Ⅳ.") + 2).replaceAll("[\u2460-\u2469 ]+", "");
}
}
// book.setMidpicid(clcnumberCode);
// 图书字数15
String wordNumber = "";
if (ptext.contains("字数") && ptext.contains("千")) {
wordNumber = ptext.substring(ptext.indexOf("字数") + 2, ptext.indexOf("千")).replace("千", "").replaceAll("[\u4e00-\u9fa5a-zA-Z/ //::]", "");
} else if (!ptext.contains("字数") && ptext.contains("千字")) {
wordNumber = ptext.substring(ptext.indexOf("千") - 4, ptext.indexOf("千")).replace("千", "").replaceAll("[\u4e00-\u9fa5a-zA-Z/ //::]", "");
}
if (!wordNumber.equals("")) {
book.setFontCount(wordNumber);
}
// 图书版次16
String edition = "";
if (ptext.contains("版次")) {
edition = ptext.substring(ptext.indexOf("版次") + 2).replaceAll("[//::]", " ");
}
book.setRevision(edition);
// 图书价钱17 定 价/20.00元(册) ^[\u4e00-\u9fa5a-zA-Z]+$
if (StringUtils.anyContains(ptext, "定价,成本价,价格")) {
Float price = 0.0f;
try {
Float.parseFloat(ptext.substring(ptext.indexOf("价") + 1, ptext.indexOf("元") > 0 ? ptext.indexOf("元") : ptext.length()).replace("元", ""));
price = Float.parseFloat(ptext.substring(ptext.indexOf("价") + 1, ptext.indexOf("元") > 0 ? ptext.indexOf("元") : ptext.length()).replace("元", "")
.replaceAll("[\u4e00-\u9fa5a-zA-Z/ //::]", ""));
if (price == null || price == 0f) {
// book.setStatus(SysConstant.CHECK_NOTPASS);
}
// book.setPrice(price);
} catch (Exception e) {
System.out.println("价格信息异常:" + ptext);
continue;
}
}
} // end if(内)
i++;
} // end for(内)
// break;
} // end if(外)
Ebook ebook = new Ebook();
String intro = "暂无简介";
if (StringUtils.anyContains(spineReference.getTitle().replaceAll("[  ]", ""), "序,序言,前言,摘要,内容简介")) {
String doc = getDocument(spineReference).select("h1,h2,h3,h4,h5,p,div,img").text().replace(spineReference.getTitle(), spineReference.getTitle() + "  ");
intro = doc.substring(0, doc.length() < 500 ? doc.length() : 500);
ebook.setSynopsis(intro);
} else {
if (spineReference.getTitle().replaceAll("[  ]", "").contains("目录")) {
TOCReference reference = listReferences.get(index + 1);
String doc = getDocument(reference).select("h1,h2,h3,h4,h5,p,div,img").text().replace(spineReference.getTitle(), spineReference.getTitle() + "  ");
intro = doc.substring(0, doc.length() < 500 ? doc.length() : 500);
ebook.setSynopsis(intro);
}
}
} // end for(外)
return book;
}
// **********************************************************************************
// ***************************** 图书章节信息 *****************************
// **********************************************************************************
/**
* 获取封面 以及 其他所有图片,返回封面的src路径
*
* @Title: getCoverImage
* @Description:
* @param epubUtil
* @param bookFolderPath
* @return
* @return String 返回类型
* @author 刘自耀
* @date 2015-7-1 上午10:15:18
*/
public String getCoverImage(EpubUtil epubUtil, String bookFolderPath) {
// 保存封面在内的所有图片到磁盘上
List<FileInfo> entity = getImages(epubUtil, bookFolderPath);
// 封面图片的href
Resource cover = epubUtil.getCover();
if (cover != null) {
return cover.getHref();
} else {
return "Images/cover.jpg";
}
}
/**
* 保存章节名称,用于判断文章是否属于章节
*/
private List<String> chapterList = new ArrayList<String>();
/**
* 分等级封装图书章节信息
*
* @Title: setChapter
* @Description:
* @param listReferences
* @param refe
* @param level
* @return
* @throws Exception
* @return Chapter 返回类型
* @author 刘自耀
* @param book
* @date 2015-7-1 下午3:34:41
*/
public Set<ChapterLibrary> setChapter(List<TOCReference> listReferences, TOCReference refe, Integer level, Ebook ebook, Set<ChapterLibrary> chapterSet) {
ChapterLibrary chapter = null;
// ================================ 遍历目录方式一
// =======================================
for (TOCReference spineReference : listReferences) {
// 章节对象
chapter = new ChapterLibrary();
// 所属图书的id
chapter.setBookid(ebook.getId());
// 所属图书名称
// chapter.setBookName(ebook.getName());
// 章节名称
chapter.setChapterName(spineReference.getTitle());
/**
* 保存章节名称,用于判断文章是否属于章节
*/
chapterList.add(spineReference.getTitle());
// 章节标识号
// chapter.setMarkid(book.getId()+"-"+(spineReference.getFragmentId()));
if (spineReference.getFragmentId() != null && !spineReference.getFragmentId().equals("")) {
chapter.setMarkid(ebook.getId() + "-" + spineReference.getFragmentId());
} else {
chapter.setMarkid(ebook.getId() + "-" + spineReference.getResourceId());
}
// 章节排序
chapter.setOrderNum(chapterSet.size());
// 父章节名称
if (refe.getFragmentId() != null && !refe.getFragmentId().equals("")) {
chapter.setPid(ebook.getId() + "-" + refe.getFragmentId());
} else if (refe.getResourceId() != null) {
chapter.setPid(ebook.getId() + "-" + refe.getResourceId());
} else {
chapter.setPid(ebook.getId() + "-" + 0);
}
// 章节层级
chapter.setLevel(level);
// 将章节目录对象放进 set 集合
chapterSet.add(chapter);
// 递归,如果该标题下还有子标题,继续遍历子标题
if (spineReference.getChildren().size() != 0) {
Integer nextLevel = level + 1;
setChapter(spineReference.getChildren(), spineReference, nextLevel, ebook, chapterSet);
}
}
return chapterSet;
}
// **********************************************************************************
// ***************************** 图书内容信息 ****************************
// **********************************************************************************
public Map<String, TOCReference> getAllTitle(TOCReference tocref, Map<String, TOCReference> alltitle, int flag) {// 判断是否是父章节,父=0,++
if (flag == 0) {
String title0 = tocref.getTitle();
alltitle.put(title0, tocref);
}
if (tocref.getChildren().size() > 0) {
flag++;
for (TOCReference toc : tocref.getChildren()) {
String title = toc.getTitle();
alltitle.put(title, toc);
if (toc.getChildren().size() > 0) {
getAllTitle(toc, alltitle, flag);
}
}
}
return alltitle;
}
/**
*
* @Description: TODO
* @param @param
* listReferences
* @param @param
* contentSet
* @param @param
* book
* @param @param
* imgtzMap
* @param @param
* data
* @param @return
* @return Object[]
* @throws @author
* 李禚
* @date 2016年5月26日
*/
@SuppressWarnings("unchecked")
public Object[] setContent(List<TOCReference> listReferences, Set<ArticleLibrary> contentSet, Ebook ebook, Map<String, String> imgtzMap, Object[] data) {
// 遍历章节的内容
Map<String, TOCReference> titles1 = null;
Map<String, TOCReference> ids1 = null;
for (TOCReference spineReference : listReferences) {
titles1 = new LinkedMap();
ids1 = new LinkedMap();
// 获取所有title
Map<String, TOCReference> tmap = getAllTitle(spineReference, titles1, 0);
// 获取所有id
Map<String, TOCReference> tmapid = getAllId(spineReference, ids1, 0);
// 顶级目录 用resourceId 标识
String resourceId = "";
if (spineReference.getFragmentId() != null && !spineReference.getFragmentId().equals("")) {
resourceId = spineReference.getFragmentId();
} else {
resourceId = spineReference.getResourceId();
}
// jsoup解析,生成dom对象
Document doc = getDocument(spineReference);
Elements elements = doc.select("h1,h2,h3,h4,h5,h6,ul,hr,p,div");
// ###################去重复的标题###########################
Elements titles = new Elements();
Set<String> keys = tmapid.keySet();
for (String key : keys) {
Element str;
try {
str = doc.getElementById(key);
if (str != null)
titles.add(str);
} catch (Exception e) {
continue;
}
}
// 图注:
// Elements select = elements.select("p,img");
for (Element elmt : elements) {
if (elmt.toString().contains("<img")) {
for (Element e : elmt.children()) {
if (e.toString().contains("<img")) {
String imgsrc = e.attr("src");
// 将带上一层目录的取消
if (imgsrc.contains("../")) {
imgsrc = imgsrc.replace("../", "");
}
String imgtz = "";
String before = "";
String after = "";
if (e.previousElementSibling() != null) {
before = e.previousElementSibling().attr("class");
}
if (e.nextElementSibling() != null) {
after = e.nextElementSibling().attr("class");
}
if (StringUtils.anyEquals(before, "picture_figure_note,picture_table_note,picture_table_title,picture_figure_title,tableCaption")) {
imgtz = e.previousElementSibling().text();
} else if (StringUtils.anyEquals(after, "picture_figure_note,picture_table_note,picture_table_title,picture_figure_title,tableCaption")) {
imgtz = e.nextElementSibling().text();
}
imgtzMap.put(imgsrc, imgtz);
}
}
}
}
// 不包含,h标签,直接存储
boolean anyEquals = false;
if (titles.size() > 0) {
anyEquals = StringUtils.anyEquals(titles.get(0).text().replaceAll("[  ]", ""), "序,总序,序言,前言,摘要");
}
if (!titles.toString().contains("<h") || anyEquals) {
// 不包含h标签的直接整体存入
ArticleLibrary content = new ArticleLibrary();
// 当前章节标题
String title = spineReference.getTitle();// elements.get(0).toString().contains("<h")?elements.get(0).text():
content.setName(title);// 标题
// markid
content.setMarkid(ebook.getId() + "-" + resourceId);
int num = 1;
content.setText(elements.toString());
// 设置公共信息
setContentCommInfo(content, ebook, elements);
// **********将章节内容存入Set集合*********
contentSet.add(content);
} else if (!anyEquals) {
Elements es = null;
for (int i = 0, tlen = titles.size(); i < tlen; i++) {
/**
* 如果属于章节,则保存。 否则直接跳过
*/
if (chapterList.contains(titles.get(i).text())) {
// h标签
Element hlabel1 = titles.get(i);
Element hlabel2 = null;
if (i != titles.size() - 1) {
for (int j = i + 1; j < titles.size(); j++) {
if (chapterList.contains(titles.get(j).text())) {
hlabel2 = titles.get(j);
i = j - 1;
break;
}
}
}
// 截取整个大章节中的每个小章节
// 一.xxxx
// 1.xxx
// 2.xxx
// 二.xxxx
List<Element> subchapter = elements.subList(elements.indexOf(hlabel1), hlabel2 == null ? elements.size() : elements.indexOf(hlabel2));
es = new Elements();
// markid
String markid = ebook.getId() + "-" + (hlabel1.attr("id").equals("") ? resourceId : hlabel1.attr("id"));
for (Element element : subchapter) {
es.add(element);
}
ArticleLibrary content = new ArticleLibrary();
// 内容信息(6)
content.setName(hlabel1.text());
// 章节内容
content.setText(es.toString());// 内容
String filterText = es.text();
content.setMarkid(markid);
// 内容相关信息,为正文时才去设置关键字,预览,简介(3)
if (!StringUtils.anyEquals(hlabel1.text(), "封面,版权页,目录,序,总序,序言,前言,摘要")) {
content.setSynopsis(filterText.toString().substring(0, filterText.length()/3));
}
// 设置公共信息(6)
setContentCommInfo(content, ebook, es);
// *********将章节内容存入Set集合****************
contentSet.add(content);
}
}
}
// =============递归 遍历子章节内容============
if (spineReference.getChildren().size() > 0) {
if (spineReference.getChildren().get(0).getFragmentId().contains("_")) {
String spchild = spineReference.getChildren().get(0).getFragmentId().substring(0, spineReference.getChildren().get(0).getFragmentId().indexOf("_"));
if (!spineReference.getFragmentId().contains(spchild))
setContent(spineReference.getChildren(), contentSet, ebook, imgtzMap, data);
} else {
setContent(spineReference.getChildren(), contentSet, ebook, imgtzMap, data);
}
}
// =============递归 遍历子章节内容============
} // for循环结束
data[0] = contentSet;
data[1] = imgtzMap;
return data;
}
/**
* 设置图书内容信息 公共部分
*
* @Title: setContentCommInfo
* @Description:
* @param content
* @param book
* @param doc
* @return
* @return Content 返回类型
* @author 刘自耀
* @date 2015-7-10 上午9:33:56
*/
int c = 0;
private ArticleLibrary setContentCommInfo(ArticleLibrary content, Ebook ebook, Elements label) {
// 图书相关信息
//content.setBookName(ebook.getName());
content.setBookId(ebook.getId());
// 替换图片资源的href
// book路径
String bookPath = ebook.getEpubFile().substring(0, ebook.getEpubFile().lastIndexOf("/") + 1);
Elements imgs = label.select("img");
String oldImg = "";
String newImg = "";
if (imgs.size() != 0) {
for (Element img : imgs) {
String imgSrc = img.attr("src");
// 原图片资源路径
oldImg = img.toString();
// 修改替换图片路径
if (!imgSrc.contains("/resource")) {
img.attr("src", bookPath + imgSrc);
// 新的图片资源路径
newImg = img.toString();
content.setText(content.getText().replace(oldImg, newImg));
}
}
}
return content;
}
/**
* 获取css样式文件
*
* @param epubUtil
* @param bookPath
* @return
*/
public FileInfo getCss(EpubUtil epubUtil, String bookPath) {
Resource cssRes = epubUtil.getCssResource();
FileInfo entity = new FileInfo();
if (cssRes == null) {
return entity;
}
String cssPath=cssRes.getHref().substring(0, cssRes.getHref().contains("/") ? cssRes.getHref().lastIndexOf("/") : 0);
String cssName =cssRes.getHref().substring(cssRes.getHref().lastIndexOf("/")+1);
// 写入文件中
InputStream inputStream = null;
File css = new File(bookPath +"/"+ cssPath);
if (!css.exists()) {
css.mkdirs();
}
try {
inputStream = cssRes.getInputStream();
MultipartFile multipartFile = new MockMultipartFile(cssName,cssName,"text/css", inputStream);
entity = this.uploadFile(multipartFile, css.getPath());
} catch (Exception e) {
e.printStackTrace();
}
return entity;
}
/**
* 获取图书中所有图片资源
* @param epubUtil
* @param bookFolderPath
* @return
*/
public List<FileInfo> getImages(EpubUtil epubUtil, String bookFolderPath) {
List<Resource> imgs = epubUtil.getImagesResources();
List<FileInfo> entityList = new ArrayList<FileInfo>();
String imagePath=imgs.get(0).getHref().substring(0, imgs.get(0).getHref().lastIndexOf("/"));
// 创建图书中的图片的保存文件夹
File imageRes = null;
if (imgs.size() != 0) {
imageRes = new File(bookFolderPath +"/"+ imagePath);
if (!imageRes.exists()) {
imageRes.mkdirs();
}
// 将图片保存到磁盘中
InputStream in = null;
try {
for (Resource img : imgs) {
String imgName=img.getHref().substring(img.getHref().lastIndexOf("/")+1);
in = img.getInputStream();
MultipartFile multipartFile = new MockMultipartFile(imgName,imgName,"image/jpeg", in);
FileInfo entity = this.uploadFile(multipartFile, imageRes.getPath());
entityList.add(entity);
}
// 多线程处理图片生成缩略图
new Thread(()->ImageUtil.createThumbnailToThread(imgs, bookFolderPath+"/")).start();
} catch (IOException e) {
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return entityList;
}
public FileInfo uploadFile(MultipartFile file, String path) {
String contentType = file.getContentType();
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 解决中文问题,liunx下中文路径,图片显示问题
String uuid = UUIDUtil.getUUID();
String filePath = path + "/";
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
filePath = filePath + file.getOriginalFilename();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
FileInfo entity = new FileInfo();
try {
fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
bos.write(file.getBytes());
entity.setFileName(uuid);
entity.setOriginalFileName(fileName);
entity.setSuffixName(suffixName);
entity.setPath(path);
entity.setContentType(contentType);
entity.setSize(file.getSize());
entity.setCreateTime(new Date());
} catch (Exception e) {
logger.error("上传异常:" + e);
e.printStackTrace();
} finally {
try {
if (null != fos)
fos.flush();
if (null != bos)
bos.close();
} catch (IOException e) {
}
}
return entity;
}
}
\ No newline at end of file
package com.zrqx.file.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.zip.ZipInputStream;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Date;
import nl.siegmann.epublib.domain.Identifier;
import nl.siegmann.epublib.domain.MediaType;
import nl.siegmann.epublib.domain.Metadata;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Resources;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.domain.TOCReference;
import nl.siegmann.epublib.epub.EpubReader;
import org.apache.commons.lang3.StringUtils;
import com.zrqx.core.util.datatype.ArrayUtils;
/**
* epub 数字书籍格式 数据工具包
* @author Administrator
*
*/
public class EpubUtil {
private Book book=null;
private EpubReader epubReader=null;
/**
* 设置Book实例对象
* @return
*/
public EpubUtil setEpubFile(File file){
try {
return setEpubFile(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return this;
}
/**
* 设置Book实例对象
* @return
*/
public EpubUtil setEpubFile(InputStream in){
try {
epubReader=getEpubReader();
book=epubReader.readEpub(in);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* 设置Book实例对象
* @return
*/
public EpubUtil setEpubFile(InputStream in, String encoding){
try {
epubReader=getEpubReader();
book=epubReader.readEpub(in,encoding);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* 设置Book实例对象
* @return
*/
public EpubUtil setEpubFile(ZipInputStream in){
try {
epubReader=getEpubReader();
book=epubReader.readEpub(in);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* 设置Book实例对象
* @return
*/
public EpubUtil setEpubFile(ZipInputStream in,String encoding){
try {
epubReader=getEpubReader();
book=epubReader.readEpub(in,encoding);
} catch (IOException e) {
e.printStackTrace();
}
return this;
}
/**
* 获取所有的资源对象
* @return
*/
public Resources getResources(){
return book.getResources();
}
/**
* 获取封面
*/
public Resource getCover(){
//epub格式的书籍中都没有将封面图片的信息放到<metadata>标签下的cover标签中。所以用第二种fangs
Resource res = book.getCoverImage();
if(res!=null){
return res;
}else{
Resources ress = book.getResources();
res = ress.getById("cover");
return res;
}
}
/**
* 获取制定的文件资源
* @param mediaTypes
* @return
*/
public List<Resource> getResources(MediaType ... mediaTypes){
return getResources().getResourcesByMediaTypes(mediaTypes);
}
/**
* 获取图书的css资源文件
* @return
*/
public Resource getCssResource(){
List<Resource> list=getResources(new MediaType("text/css","css"));
if(list!=null && list.size()>0){
return list.get(0);
}
return null;
}
/**
* 获取图书的图片资源
* @return
*/
public List<Resource> getImagesResources(){
return getResources(
new MediaType("image/jpeg","jpg"),
new MediaType("image/gif","gif"),
new MediaType("image/png","png")
);
}
/**
*获取根据阅读顺序获取图书的内容资源(html)文件资源
* @return
*/
public List<SpineReference> getSpineReferences(){
return book.getSpine().getSpineReferences();
}
/**
*获取图书的目录结构标题及对应的资源内容
* @return
*/
public List<TOCReference> getTocReferences(){
return book.getTableOfContents().getTocReferences();
}
/**
* 获取图书
* @return
* author:haopeng
*/
public Book getBook(){
return book;
}
/**
* 获取图书信息
* @return
* author:haopeng
* @throws Exception
*/
public Metadata getMetadata() throws Exception{
if(book==null){
throw new NullPointerException("图书Book属性为null");
}
return book.getMetadata();
}
/**
* 获取文件读取器
* @return
*/
private EpubReader getEpubReader(){
if(epubReader==null){
epubReader=new EpubReader();
}
return epubReader;
}
/**
* 获取图书ISBN号
* @throws Exception
*/
public String getISBN() throws Exception{
String isbn=null;
List<Identifier> identifiers=getMetadata().getIdentifiers();
for(Identifier identifier:identifiers){
String value=identifier.getValue();
// if(value.matches("^97[8|9]\\d{10}$") ){//新版isbn号格式
if(value.contains("-")){
value=value.replaceAll("-", "");
isbn=value;
break;
}
}
return isbn;
}
/**
* 获取图书作者
*/
public String getAuthor(){
List<Author> authors = null;
try {
authors = getMetadata().getAuthors();
} catch (Exception e) {
e.printStackTrace();
}
String author = "";
if(authors.size()>0){
author = authors.get(0).getFirstname()+authors.get(0).getLastname();
author = author.replaceAll("[\\[\\],]"," ");
}
return author;
}
/**
* 获取出版日期
*/
public java.util.Date getPublishDate(){
List<Date> dates = null;
try {
dates = getMetadata().getDates();
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyy");
String tempDate = "";
if(dates.size()>0){
if(dates.get(0).toString().contains(".")){
sdf= new SimpleDateFormat("yyy.MM");
}
if(dates.get(0).toString().contains("-")){
sdf= new SimpleDateFormat("yyy-MM");
}
tempDate= dates.get(0).toString();
}
java.util.Date publicDate = null;
try {
if(tempDate!=null && !tempDate.equals("")){
publicDate = sdf.parse(tempDate);
}
} catch (ParseException e) {
System.out.println("日期转换错误!");
e.printStackTrace();
}
return publicDate;
}
/**
* 出版单位
*/
public String getPublisher(){
String publisher = "";
List<String> publishers;
try {
publishers = getMetadata().getPublishers();
for(String p : publishers){
if(p.contains("-")){
publisher = publisher + "、" + p;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if(StringUtils.isBlank(publisher)){
return null;
}
return publisher;
}
/**
* 获取图书的名字
*/
public String getBookTitle(){
String bookTitle = "";
//List<String> bookTitle2 = null;
try {
bookTitle = getMetadata().getFirstTitle();
//bookTitle2 = getMetadata().getTitles();
} catch (Exception e) {
e.printStackTrace();
}
return bookTitle;
}
/**
* 简介
*/
public String getDescription(){
String description = "";
List<String> descriptions;
try {
descriptions = getMetadata().getDescriptions();
/*for(String p : descriptions){
if(p.contains("-")){
publisher = publisher + "、" + p;
break;
}
}*/
if(ArrayUtils.isNotEmpty(descriptions)){
description = descriptions.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
if(StringUtils.isBlank(description)){
return null;
}
return description;
}
}
Manifest-Version: 1.0
Implementation-Title: com.zrqx.file
Implementation-Version: 4.0.0
Built-By: Administrator
Implementation-Vendor-Id: com.zrqx.file
Build-Jdk: 1.8.0_152
Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo
ot-starter-parent/com.zrqx.pom/com.zrqx.file
Created-By: Maven Integration for Eclipse
#Generated by Maven Integration for Eclipse
#Thu Mar 07 10:12:00 CST 2019
version=4.0.0
groupId=com.zrqx.file
m2e.projectName=com.zrqx.file
m2e.projectLocation=D\:\\work\\workspacezcq\\com.zrqx.file
artifactId=com.zrqx.file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.pom</artifactId>
<version>4.0.0</version>
<relativePath>../com.zrqx.pom</relativePath>
</parent>
<groupId>com.zrqx.file</groupId>
<artifactId>com.zrqx.file</artifactId>
<dependencies>
<!--视频时长 -->
<dependency>
<groupId>it.sauronsoftware.jave</groupId>
<artifactId>jave</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
<!-- <dependency> <groupId>com.positiondev.epublib</groupId> <artifactId>epublib-core</artifactId>
<version>3.1</version> </dependency> -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.zrqx</groupId>
<artifactId>com.zrqx.core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--熔断器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Springsecurity给服务端提供安全访问 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<!-- 用于健康监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--分布式事务 -->
<!-- <dependency> <groupId>com.codingapi</groupId> <artifactId>transaction-springcloud</artifactId>
<exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>*</artifactId>
</exclusion> </exclusions> </dependency> <dependency> <groupId>com.codingapi</groupId>
<artifactId>tx-plugins-db</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId>
<artifactId>*</artifactId> </exclusion> </exclusions> </dependency> -->
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!--用于测试的 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入epublib -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>com.positiondev.epublib</groupId>
<artifactId>epublib-core</artifactId>
<version>3.1</version>
</dependency>
<!-- 热部署工具 -->
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId>
</dependency> -->
</dependencies>
</project>
\ No newline at end of file
......@@ -41,4 +41,4 @@
</includes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
</assembly>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论