use of com.github.junrar.Archive in project AozoraEpub3 by hmdev.
the class ImageInfoReader method loadRarImageInfos.
/** rar内の画像情報をすべて読み込み */
public void loadRarImageInfos(File srcFile, boolean addFileName) throws IOException, RarException {
Archive archive = new Archive(srcFile);
try {
int idx = 0;
for (FileHeader fileHeader : archive.getFileHeaders()) {
if (idx++ % 10 == 0)
LogAppender.append(".");
if (!fileHeader.isDirectory()) {
String entryName = fileHeader.getFileNameW();
if (entryName.length() == 0)
entryName = fileHeader.getFileNameString();
entryName = entryName.replace('\\', '/');
String lowerName = entryName.toLowerCase();
if (lowerName.endsWith(".png") || lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".gif")) {
ImageInfo imageInfo = null;
InputStream is = null;
try {
//読めない場合があるので一旦バイト配列に読み込み
ByteArrayOutputStream baos = new ByteArrayOutputStream();
archive.extractFile(fileHeader, baos);
baos.close();
is = new ByteArrayInputStream(baos.toByteArray());
imageInfo = ImageInfo.getImageInfo(is);
if (imageInfo != null) {
this.imageFileInfos.put(entryName, imageInfo);
if (addFileName)
this.addImageFileName(entryName);
} else {
LogAppender.println();
LogAppender.error("画像が読み込めませんでした: " + entryName);
}
} catch (Exception e) {
LogAppender.println();
LogAppender.error("画像が読み込めませんでした: " + entryName);
e.printStackTrace();
} finally {
if (is != null)
is.close();
}
}
}
}
} finally {
LogAppender.println();
archive.close();
}
}
use of com.github.junrar.Archive in project AozoraEpub3 by hmdev.
the class Epub3Writer method write.
/** epubファイルを出力
* @param converter 青空文庫テキスト変換クラス 画像のみの場合と切り替えて利用する
* @param src 青空文庫テキストファイルの入力Stream
* @param srcFile 青空文庫テキストファイル zip時の画像取得用
* @param zipTextFileName zipの場合はzip内のテキストファイルのパス付きファイル名
* @param epubFile 出力ファイル .epub拡張子
* @param bookInfo 書籍情報と縦横書き指定
* @param zipImageFileInfos zipの場合はzip内画像の情報 key=サブフォルダ付きの画像ファイル名
* @throws IOException */
public void write(AozoraEpub3Converter converter, BufferedReader src, File srcFile, String srcExt, File epubFile, BookInfo bookInfo, ImageInfoReader imageInfoReader) throws Exception {
try {
this.canceled = false;
this.bookInfo = bookInfo;
this.imageInfoReader = imageInfoReader;
//インデックス初期化
this.sectionIndex = 0;
this.imageIndex = 0;
this.sectionInfos.clear();
this.chapterInfos.clear();
this.vecGaijiInfo.clear();
this.gaijiNameSet.clear();
this.imageInfos.clear();
this.outImageFileNames.clear();
//Velocity用 共通コンテキスト設定
this.velocityContext = new VelocityContext();
//IDはタイトル著作者のハッシュで適当に生成
String title = bookInfo.title == null ? "" : bookInfo.title;
String creator = bookInfo.creator == null ? "" : bookInfo.creator;
if ("".equals(bookInfo.creator))
bookInfo.creator = null;
//固有ID
velocityContext.put("identifier", UUID.nameUUIDFromBytes((title + "-" + creator).getBytes()));
//表紙の目次表示名
velocityContext.put("cover_name", "表紙");
//タイトル &<>はエスケープ
velocityContext.put("title", CharUtils.escapeHtml(title));
//タイトル読み &<>はエスケープ
if (bookInfo.titleAs != null)
velocityContext.put("titleAs", CharUtils.escapeHtml(bookInfo.titleAs));
//著者 &<>はエスケープ
velocityContext.put("creator", CharUtils.escapeHtml(creator));
//著者読み &<>はエスケープ
if (bookInfo.creatorAs != null)
velocityContext.put("creatorAs", CharUtils.escapeHtml(bookInfo.creatorAs));
//刊行者情報
if (bookInfo.publisher != null)
velocityContext.put("publisher", bookInfo.publisher);
//書籍情報
velocityContext.put("bookInfo", bookInfo);
//更新日時
velocityContext.put("modified", dateFormat.format(bookInfo.modified));
//目次階層化
velocityContext.put("navNest", this.navNest);
//端末種別
if (this.isKindle)
velocityContext.put("kindle", true);
//SVG画像出力
if (this.isSvgImage)
velocityContext.put("svgImage", true);
//スタイル
velocityContext.put("pageMargin", this.pageMargin);
velocityContext.put("bodyMargin", this.bodyMargin);
velocityContext.put("lineHeight", this.lineHeight);
velocityContext.put("fontSize", this.fontSize);
velocityContext.put("boldUseGothic", this.boldUseGothic);
velocityContext.put("gothicUseBold", this.gothicUseBold);
//出力先ePubのZipストリーム生成
zos = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(epubFile)));
//mimetypeは非圧縮
//STOREDで格納しCRCとsizeを指定する必要がある
ZipArchiveEntry mimeTypeEntry = new ZipArchiveEntry(MIMETYPE_PATH);
FileInputStream fis = new FileInputStream(new File(templatePath + MIMETYPE_PATH));
byte[] b = new byte[256];
int len = fis.read(b);
fis.close();
CRC32 crc32 = new CRC32();
crc32.update(b, 0, len);
mimeTypeEntry.setMethod(ZipArchiveEntry.STORED);
mimeTypeEntry.setCrc(crc32.getValue());
mimeTypeEntry.setSize(len);
zos.putArchiveEntry(mimeTypeEntry);
zos.write(b, 0, len);
b = null;
zos.closeArchiveEntry();
zos.setLevel(9);
//テンプレートのファイルを格納
for (String fileName : getTemplateFiles()) {
writeFile(zos, fileName);
}
//サブパスの文字長
int archivePathLength = 0;
if (this.bookInfo.textEntryName != null)
archivePathLength = this.bookInfo.textEntryName.indexOf('/') + 1;
//zip出力用Writer
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
//本文を出力
this.writeSections(converter, src, bw, srcFile, srcExt, zos);
if (this.canceled)
return;
//外字のcssを格納
velocityContext.put("vecGaijiInfo", this.vecGaijiInfo);
//スタイルと外字のcssを格納
if (bookInfo.vertical) {
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + CSS_PATH + VERTICAL_TEXT_CSS));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + CSS_PATH + VERTICAL_TEXT_CSS_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
} else {
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + CSS_PATH + HORIZONTAL_TEXT_CSS));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + CSS_PATH + HORIZONTAL_TEXT_CSS_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
}
//表紙をテンプレート+メタ情報から生成 先に出力すると外字画像出力で表紙の順番が狂う
if (!bookInfo.imageOnly && (bookInfo.titlePageType == BookInfo.TITLE_MIDDLE || bookInfo.titlePageType == BookInfo.TITLE_HORIZONTAL)) {
String vmFilePath = templatePath + OPS_PATH + XHTML_PATH + TITLE_M_VM;
if (bookInfo.titlePageType == BookInfo.TITLE_HORIZONTAL) {
converter.vertical = false;
vmFilePath = templatePath + OPS_PATH + XHTML_PATH + TITLE_H_VM;
}
//ルビと外字画像注記と縦中横注記(縦書きのみ)のみ変換する
String line = bookInfo.getTitleText();
if (line != null)
velocityContext.put("TITLE", converter.convertTitleLineToEpub3(line));
line = bookInfo.getSubTitleText();
if (line != null)
velocityContext.put("SUBTITLE", converter.convertTitleLineToEpub3(line));
line = bookInfo.getOrgTitleText();
if (line != null)
velocityContext.put("ORGTITLE", converter.convertTitleLineToEpub3(line));
line = bookInfo.getSubOrgTitleText();
if (line != null)
velocityContext.put("SUBORGTITLE", converter.convertTitleLineToEpub3(line));
line = bookInfo.getCreatorText();
if (line != null)
velocityContext.put("CREATOR", converter.convertTitleLineToEpub3(line));
line = bookInfo.getSubCreatorText();
if (line != null)
velocityContext.put("SUBCREATOR", converter.convertTitleLineToEpub3(line));
line = bookInfo.getSeriesText();
if (line != null)
velocityContext.put("SERIES", converter.convertTitleLineToEpub3(line));
line = bookInfo.getPublisherText();
if (line != null)
velocityContext.put("PUBLISHER", converter.convertTitleLineToEpub3(line));
//package.opf内で目次前に出力
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + TITLE_FILE));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(vmFilePath, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
velocityContext.put("title_page", true);
//表題行を目次に出力するならtitle.xhtmlを追加 (本文内の行はchapterinfosに追加されていない)
ChapterLineInfo titleLineInfo = bookInfo.getChapterLineInfo(bookInfo.titleLine);
if (titleLineInfo != null) {
chapterInfos.add(0, new ChapterInfo("title", null, bookInfo.title, ChapterLineInfo.LEVEL_TITLE));
}
}
if (this.canceled)
return;
//表紙データと表示の画像情報
byte[] coverImageBytes = null;
ImageInfo coverImageInfo = null;
if (bookInfo.coverFileName != null && bookInfo.coverFileName.length() > 0) {
//表紙情報をimageInfosに追加
try {
//表紙設定解除
for (ImageInfo imageInfo2 : imageInfos) {
imageInfo2.setIsCover(false);
}
BufferedInputStream bis;
if (bookInfo.coverFileName.startsWith("http")) {
bis = new BufferedInputStream(new URL(bookInfo.coverFileName).openStream(), 8192);
} else {
bis = new BufferedInputStream(new FileInputStream(new File(bookInfo.coverFileName)), 8192);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(bis, baos);
coverImageBytes = baos.toByteArray();
bis.close();
baos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
coverImageInfo = ImageInfo.getImageInfo(bais);
bais.close();
String ext = coverImageInfo.getExt();
if (isKindle || ext.equals("jpeg"))
ext = "jpg";
coverImageInfo.setId("0000");
coverImageInfo.setOutFileName("0000." + ext);
if (!ext.matches("^(png|jpg|jpeg|gif)$")) {
LogAppender.println("表紙画像フォーマットエラー: " + bookInfo.coverFileName);
coverImageInfo = null;
} else {
coverImageInfo.setIsCover(true);
this.imageInfos.add(0, coverImageInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (bookInfo.coverImage != null) {
//すべてのページの表紙設定解除
for (ImageInfo imageInfo2 : imageInfos) {
imageInfo2.setIsCover(false);
}
//プレビューでトリミングされた表紙
String ext = "jpg";
if (bookInfo.coverExt != null) {
ext = bookInfo.coverExt;
} else if (bookInfo.coverImageIndex > -1) {
ImageInfo imageInfo = imageInfoReader.getImageInfo(bookInfo.coverImageIndex);
if (imageInfo != null)
ext = imageInfo.getExt();
}
if (isKindle || ext.equals("jpeg"))
ext = "jpg";
coverImageInfo = ImageInfo.getImageInfo(ext, bookInfo.coverImage, -1);
coverImageInfo.setId("0000");
coverImageInfo.setOutFileName("0000." + ext);
coverImageInfo.setIsCover(true);
this.imageInfos.add(0, coverImageInfo);
} else {
//本文にないzip内の表紙を出力対象に追加 (テキストからの相対パス)
if (bookInfo.coverImageIndex > -1 && imageInfoReader.countImageFileNames() > bookInfo.coverImageIndex) {
if (!"txt".equals(srcExt)) {
String imageFileName = imageInfoReader.getImageFileName(bookInfo.coverImageIndex);
if (imageFileName != null) {
ImageInfo imageInfo = imageInfoReader.getImageInfo(imageFileName);
if (imageInfo != null) {
imageFileName = imageFileName.substring(archivePathLength);
outImageFileNames.add(imageFileName);
//表紙フラグも設定
for (ImageInfo imageInfo2 : imageInfos) {
imageInfo2.setIsCover(false);
}
imageInfo.setIsCover(true);
if (!this.imageInfos.contains(imageInfo))
this.imageInfos.add(imageInfo);
}
}
}
}
}
//表紙ページ出力 先頭画像表示時は画像出力時にカバー指定するので出力しない
if (bookInfo.insertCoverPage) {
//追加用の情報取得にのみ使う
ImageInfo insertCoverInfo = coverImageInfo;
if (insertCoverInfo == null && bookInfo.coverImageIndex > -1) {
//本文中の挿絵の場合
insertCoverInfo = imageInfoReader.getImageInfo(bookInfo.coverImageIndex);
if (insertCoverInfo != null) {
insertCoverInfo.setIsCover(true);
if (!bookInfo.imageOnly && insertCoverInfo.getId() == null) {
//zip内の画像で追加処理されていない
this.imageIndex++;
String imageId = decimalFormat.format(this.imageIndex);
insertCoverInfo.setId(imageId);
String ext = insertCoverInfo.getExt();
if (isKindle)
ext = "jpg";
insertCoverInfo.setOutFileName(imageId + "." + ext);
}
}
}
if (insertCoverInfo != null) {
SectionInfo sectionInfo = new SectionInfo("cover-page");
if (this.imageSizeType != SectionInfo.IMAGE_SIZE_TYPE_AUTO) {
//画像が横長なら幅100% それ以外は高さ100%
if ((double) insertCoverInfo.getWidth() / insertCoverInfo.getHeight() >= (double) this.coverW / this.coverH)
sectionInfo.setImageFitW(true);
else
sectionInfo.setImageFitH(true);
} else {
sectionInfo.setImageFitW(false);
sectionInfo.setImageFitH(false);
}
this.velocityContext.put("sectionInfo", sectionInfo);
this.velocityContext.put("coverImage", insertCoverInfo);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + COVER_FILE));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + XHTML_PATH + COVER_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
} else {
//画像がなかったら表紙ページ無し
bookInfo.insertCoverPage = false;
}
}
//package.opf 出力
velocityContext.put("sections", sectionInfos);
velocityContext.put("images", imageInfos);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + PACKAGE_FILE));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + PACKAGE_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
//nullを除去
for (int i = chapterInfos.size() - 1; i >= 0; i--) {
if (chapterInfos.get(i).getChapterName() == null)
chapterInfos.remove(i);
}
//表題のレベルを2つめと同じにする
if (bookInfo.insertTitleToc && chapterInfos.size() >= 2) {
chapterInfos.get(0).chapterLevel = chapterInfos.get(1).chapterLevel;
}
//目次の階層情報を設定
//レベルを0から開始に変更
int[] chapterCounts = new int[10];
for (ChapterInfo chapterInfo : chapterInfos) {
chapterCounts[chapterInfo.getChapterLevel()]++;
}
int[] newLevel = new int[10];
int level = 0;
for (int i = 0; i < chapterCounts.length; i++) {
if (chapterCounts[i] > 0)
newLevel[i] = level++;
}
for (ChapterInfo chapterInfo : chapterInfos) {
chapterInfo.chapterLevel = newLevel[chapterInfo.chapterLevel];
}
//開始終了情報を追加 nav用
//レベル0
ChapterInfo preChapterInfo = new ChapterInfo(null, null, null, 0);
for (ChapterInfo chapterInfo : chapterInfos) {
if (preChapterInfo != null) {
//開始
chapterInfo.levelStart = Math.max(0, chapterInfo.chapterLevel - preChapterInfo.chapterLevel);
//終了
preChapterInfo.levelEnd = Math.max(0, preChapterInfo.chapterLevel - chapterInfo.chapterLevel);
}
preChapterInfo = chapterInfo;
}
//一番最後は閉じる
if (chapterInfos.size() > 0) {
ChapterInfo chapterInfo = chapterInfos.lastElement();
if (chapterInfo != null)
chapterInfo.levelEnd = chapterInfo.chapterLevel;
}
int ncxDepth = 1;
if (this.ncxNest) {
int minLevel = 99;
int maxLevel = 0;
//navPointを閉じる回数をlevelEndに設定
//navPointを開始したレベルidxに1を設定
int[] navPointLevel = new int[10];
preChapterInfo = null;
for (ChapterInfo chapterInfo : chapterInfos) {
if (preChapterInfo != null) {
int preLevel = preChapterInfo.chapterLevel;
int curLevel = chapterInfo.chapterLevel;
minLevel = Math.min(minLevel, curLevel);
maxLevel = Math.max(maxLevel, curLevel);
navPointLevel[preLevel] = 1;
if (preLevel < curLevel) {
//前より小さい場合
preChapterInfo.navClose = 0;
} else if (preLevel > curLevel) {
//前より大きい
int close = 0;
for (int i = curLevel; i < navPointLevel.length; i++) {
if (navPointLevel[i] == 1) {
close++;
navPointLevel[i] = 0;
}
}
preChapterInfo.navClose = close;
} else {
preChapterInfo.navClose = 1;
navPointLevel[preLevel] = 0;
}
}
preChapterInfo = chapterInfo;
}
if (minLevel < maxLevel)
ncxDepth = maxLevel - minLevel + 1;
//一番最後は閉じる
if (chapterInfos.size() > 0) {
ChapterInfo chapterInfo = chapterInfos.lastElement();
if (chapterInfo != null) {
int close = 1;
for (int i = 0; i < navPointLevel.length; i++) {
if (navPointLevel[i] == 1) {
close++;
}
}
chapterInfo.navClose = close;
}
}
}
//velocityに設定 1~
velocityContext.put("ncx_depth", ncxDepth);
//出力前に縦中横とエスケープ処理
if (!bookInfo.imageOnly) {
converter.vertical = bookInfo.tocVertical;
int spaceHyphenation = converter.getSpaceHyphenation();
converter.setSpaceHyphenation(0);
StringBuilder buf = new StringBuilder();
for (ChapterInfo chapterInfo : chapterInfos) {
buf.setLength(0);
String converted = CharUtils.escapeHtml(chapterInfo.getChapterName());
if (bookInfo.tocVertical) {
converted = converter.convertTcyText(converted);
}
chapterInfo.setChapterName(converted);
}
//戻す
converter.vertical = bookInfo.vertical;
converter.setSpaceHyphenation(spaceHyphenation);
}
//navファイル
velocityContext.put("chapters", chapterInfos);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + XHTML_PATH + XHTML_NAV_FILE));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + XHTML_PATH + XHTML_NAV_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
//tocファイル
velocityContext.put("chapters", chapterInfos);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + TOC_FILE));
bw = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8"));
Velocity.mergeTemplate(templatePath + OPS_PATH + TOC_VM, "UTF-8", velocityContext, bw);
bw.flush();
zos.closeArchiveEntry();
if (src != null)
src.close();
if (this.canceled)
return;
//プログレスバーにテキスト進捗分を追加
if (this.jProgressBar != null && !bookInfo.imageOnly)
this.jProgressBar.setValue(bookInfo.totalLineNum / 10);
//フォントファイル格納
if (!bookInfo.imageOnly) {
File fontsPath = new File(templatePath + OPS_PATH + FONTS_PATH);
if (fontsPath.exists()) {
for (File fontFile : fontsPath.listFiles()) {
String outFileName = OPS_PATH + FONTS_PATH + fontFile.getName();
zos.putArchiveEntry(new ZipArchiveEntry(outFileName));
fis = new FileInputStream(new File(templatePath + outFileName));
IOUtils.copy(fis, zos);
fis.close();
zos.closeArchiveEntry();
}
}
}
//外字ファイル格納
for (GaijiInfo gaijiInfo : this.vecGaijiInfo) {
File gaijiFile = gaijiInfo.getFile();
if (gaijiFile.exists()) {
String outFileName = OPS_PATH + GAIJI_PATH + gaijiFile.getName();
zos.putArchiveEntry(new ZipArchiveEntry(outFileName));
fis = new FileInputStream(gaijiFile);
IOUtils.copy(fis, zos);
fis.close();
zos.closeArchiveEntry();
}
}
zos.setLevel(0);
//表紙編集時のイメージ出力
if (coverImageInfo != null) {
try {
//kindleの場合は常にjpegに変換
if (isKindle) {
String imgExt = coverImageInfo.getExt();
if (!imgExt.startsWith("jp")) {
if (bookInfo.coverImage == null) {
ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
bookInfo.coverImage = ImageUtils.readImage(imgExt, bais);
bais.close();
}
coverImageInfo.setExt("jpeg");
}
}
if (bookInfo.coverImage != null) {
//プレビューで編集されている場合
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + coverImageInfo.getOutFileName()));
this.writeCoverImage(bookInfo.coverImage, zos, coverImageInfo);
zos.closeArchiveEntry();
//同じ画像が使われている場合は以後はファイルから読み込ませる
bookInfo.coverImage = null;
} else {
ByteArrayInputStream bais = new ByteArrayInputStream(coverImageBytes);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + coverImageInfo.getOutFileName()));
this.writeCoverImage(bais, zos, coverImageInfo);
zos.closeArchiveEntry();
bais.close();
}
//カバー画像は出力済みなので削除
imageInfos.remove(0);
if (this.jProgressBar != null)
this.jProgressBar.setValue(this.jProgressBar.getValue() + 10);
} catch (Exception e) {
e.printStackTrace();
LogAppender.error("表紙画像取得エラー: " + bookInfo.coverFileName);
}
}
if (this.canceled)
return;
//本文画像出力 (画像のみの場合は出力済)
if ("txt".equals(srcExt)) {
//txtの場合はファイルシステムから取得
for (String srcImageFileName : imageInfoReader.getImageFileNames()) {
//拡張子修正
srcImageFileName = imageInfoReader.correctExt(srcImageFileName);
if (outImageFileNames.contains(srcImageFileName)) {
ImageInfo imageInfo = imageInfoReader.getImageInfo(srcImageFileName);
if (imageInfo == null) {
LogAppender.println("[WARN] 画像ファイルなし: " + srcImageFileName);
} else {
File imageFile = imageInfoReader.getImageFile(srcImageFileName);
if (imageFile.exists()) {
fis = new FileInputStream(imageFile);
zos.putArchiveEntry(new ZipArchiveEntry(OPS_PATH + IMAGES_PATH + imageInfo.getOutFileName()));
this.writeImage(new BufferedInputStream(fis, 8192), zos, imageInfo);
zos.closeArchiveEntry();
fis.close();
outImageFileNames.remove(srcImageFileName);
}
}
}
if (this.canceled)
return;
if (this.jProgressBar != null)
this.jProgressBar.setValue(this.jProgressBar.getValue() + 10);
}
} else if (!bookInfo.imageOnly) {
if ("rar".equals(srcExt)) {
////////////////////////////////
//Rar
Archive archive = new Archive(srcFile);
try {
for (FileHeader fileHeader : archive.getFileHeaders()) {
if (!fileHeader.isDirectory()) {
String entryName = fileHeader.getFileNameW();
if (entryName.length() == 0)
entryName = fileHeader.getFileNameString();
entryName = entryName.replace('\\', '/');
//アーカイブ内のサブフォルダは除外してテキストからのパスにする
String srcImageFileName = entryName.substring(archivePathLength);
if (outImageFileNames.contains(srcImageFileName)) {
InputStream is = archive.getInputStream(fileHeader);
try {
this.writeArchiveImage(srcImageFileName, is);
} finally {
is.close();
}
}
}
}
} finally {
archive.close();
}
} else {
////////////////////////////////
//Zip
ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), 65536), "MS932", false);
try {
ArchiveEntry entry;
while ((entry = zis.getNextZipEntry()) != null) {
//アーカイブ内のサブフォルダは除外してテキストからのパスにする
String srcImageFileName = entry.getName().substring(archivePathLength);
if (outImageFileNames.contains(srcImageFileName)) {
this.writeArchiveImage(srcImageFileName, zis);
}
}
} finally {
zis.close();
}
}
}
//エラーがなければ100%
if (this.jProgressBar != null)
this.jProgressBar.setValue(this.jProgressBar.getMaximum());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//ePub3出力ファイルを閉じる
if (zos != null)
zos.close();
} catch (Exception e) {
e.printStackTrace();
}
//メンバ変数解放
this.velocityContext = null;
this.bookInfo = null;
this.imageInfoReader = null;
}
}
use of com.github.junrar.Archive in project AozoraEpub3 by hmdev.
the class Epub3ImageWriter method writeSections.
/** 本文を出力する
* setFileNamesで sortedFileNames が設定されている必要がある
* @throws RarException */
@Override
void writeSections(AozoraEpub3Converter converter, BufferedReader src, BufferedWriter bw, File srcFile, String srcExt, ZipArchiveOutputStream zos) throws IOException, RarException {
Vector<String> vecFileName = new Vector<>();
//ファイル名取得してImageInfoのIDを設定
int pageNum = 0;
for (String srcFilePath : this.imageInfoReader.getImageFileNames()) {
if (this.canceled)
return;
pageNum++;
vecFileName.add(this.getImageFilePath(srcFilePath.trim(), pageNum));
}
//画像を出力して出力サイズを取得
zos.setLevel(0);
//サブパスの文字長
int archivePathLength = 0;
if (this.bookInfo.textEntryName != null)
archivePathLength = this.bookInfo.textEntryName.indexOf('/') + 1;
if ("rar".equals(srcExt)) {
Archive archive = new Archive(srcFile);
try {
for (FileHeader fileHeader : archive.getFileHeaders()) {
if (!fileHeader.isDirectory()) {
String entryName = fileHeader.getFileNameW();
if (entryName.length() == 0)
entryName = fileHeader.getFileNameString();
entryName = entryName.replace('\\', '/');
//アーカイブ内のサブフォルダは除外
String srcImageFileName = entryName.substring(archivePathLength);
InputStream is = archive.getInputStream(fileHeader);
try {
this.writeArchiveImage(srcImageFileName, is);
} finally {
is.close();
}
}
if (this.canceled)
return;
}
} finally {
archive.close();
}
} else {
ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), 65536), "MS932", false);
try {
ArchiveEntry entry;
while ((entry = zis.getNextZipEntry()) != null) {
//アーカイブ内のサブフォルダは除外
String srcImageFileName = entry.getName().substring(archivePathLength);
this.writeArchiveImage(srcImageFileName, zis);
if (this.canceled)
return;
}
} finally {
zis.close();
}
}
//画像xhtmlを出力
zos.setLevel(9);
pageNum = 0;
for (String srcFilePath : this.imageInfoReader.getImageFileNames()) {
if (this.canceled)
return;
String fileName = vecFileName.get(pageNum++);
if (fileName != null) {
if (isSvgImage) {
this.printSvgImageSection(srcFilePath);
} else {
this.startImageSection(srcFilePath);
bw.write(String.format(converter.getChukiValue("画像")[0], fileName));
bw.write(converter.getChukiValue("画像終わり")[0]);
bw.flush();
this.endSection();
}
}
if (this.jProgressBar != null)
this.jProgressBar.setValue(this.jProgressBar.getValue() + 1);
if (this.canceled)
return;
}
}
use of com.github.junrar.Archive in project tika by apache.
the class RarParser method parse.
@Override
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
xhtml.startDocument();
EmbeddedDocumentExtractor extractor = EmbeddedDocumentUtil.getEmbeddedDocumentExtractor(context);
Archive rar = null;
try (TemporaryResources tmp = new TemporaryResources()) {
TikaInputStream tis = TikaInputStream.get(stream, tmp);
rar = new Archive(tis.getFile());
if (rar.isEncrypted()) {
throw new EncryptedDocumentException();
}
//Without this BodyContentHandler does not work
xhtml.element("div", " ");
FileHeader header = rar.nextFileHeader();
while (header != null && !Thread.currentThread().isInterrupted()) {
if (!header.isDirectory()) {
try (InputStream subFile = rar.getInputStream(header)) {
Metadata entrydata = PackageParser.handleEntryMetadata("".equals(header.getFileNameW()) ? header.getFileNameString() : header.getFileNameW(), header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml);
if (extractor.shouldParseEmbedded(entrydata)) {
extractor.parseEmbedded(subFile, handler, entrydata, true);
}
}
}
header = rar.nextFileHeader();
}
} catch (RarException e) {
throw new TikaException("RarParser Exception", e);
} finally {
if (rar != null)
rar.close();
}
xhtml.endDocument();
}
use of com.github.junrar.Archive in project AozoraEpub3 by hmdev.
the class ImageInfoReader method getImage.
/** ファイル名から画像を取得
* 拡張子変更等は外側で修正しておく
* ファイルシステムまたはZipファイルから指定されたファイル名の画像を取得
* @param srcImageFileName ファイル名 Zipならエントリ名
* ※先頭からシークされるので遅い?
* @throws RarException */
public BufferedImage getImage(String srcImageFileName) throws IOException, RarException {
if (this.isFile) {
File file = new File(this.srcParentPath + srcImageFileName);
if (!file.exists()) {
//拡張子修正
srcImageFileName = this.correctExt(srcImageFileName);
file = new File(this.srcParentPath + srcImageFileName);
if (!file.exists())
return null;
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 8192);
try {
return ImageUtils.readImage(srcImageFileName.substring(srcImageFileName.lastIndexOf('.') + 1).toLowerCase(), bis);
} finally {
bis.close();
}
} else {
if (this.srcFile.getName().endsWith(".rar")) {
InputStream is = null;
Archive archive = new Archive(srcFile);
try {
FileHeader fileHeader = archive.nextFileHeader();
while (fileHeader != null) {
if (!fileHeader.isDirectory()) {
String entryName = fileHeader.getFileNameW();
if (entryName.length() == 0)
entryName = fileHeader.getFileNameString();
entryName = entryName.replace('\\', '/');
if (srcImageFileName.equals(entryName)) {
is = archive.getInputStream(fileHeader);
return ImageUtils.readImage(srcImageFileName.substring(srcImageFileName.lastIndexOf('.') + 1).toLowerCase(), is);
}
}
fileHeader = archive.nextFileHeader();
}
} finally {
if (is != null)
is.close();
archive.close();
}
} else {
ZipFile zf = new ZipFile(this.srcFile, "MS932");
ZipArchiveEntry entry = zf.getEntry(srcImageFileName);
if (entry == null) {
srcImageFileName = this.correctExt(srcImageFileName);
entry = zf.getEntry(srcImageFileName);
if (entry == null)
return null;
}
InputStream is = zf.getInputStream(entry);
try {
return ImageUtils.readImage(srcImageFileName.substring(srcImageFileName.lastIndexOf('.') + 1).toLowerCase(), is);
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
zf.close();
}
}
}
return null;
}
Aggregations