use of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream 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 org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream in project buck by facebook.
the class UnzipTest method testExtractSymlink.
@Test
public void testExtractSymlink() throws IOException {
assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));
// Create a simple zip archive using apache's commons-compress to store executable info.
try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
entry.setUnixMode((int) MoreFiles.S_IFLNK);
String target = "target.txt";
entry.setSize(target.getBytes(Charsets.UTF_8).length);
entry.setMethod(ZipEntry.STORED);
zip.putArchiveEntry(entry);
zip.write(target.getBytes(Charsets.UTF_8));
zip.closeArchiveEntry();
}
// Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
Path extractFolder = tmpFolder.newFolder();
Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE);
Path link = extractFolder.toAbsolutePath().resolve("link.txt");
assertTrue(Files.isSymbolicLink(link));
assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}
use of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream in project streamsx.topology by IBMStreams.
the class ZippedToolkitRemoteContext method addAllToZippedArchive.
private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException {
try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) {
for (Path start : starts.keySet()) {
final String rootEntryName = starts.get(start);
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Skip pyc files.
if (file.getFileName().toString().endsWith(".pyc"))
return FileVisitResult.CONTINUE;
String entryName = rootEntryName;
String relativePath = start.relativize(file).toString();
// If empty, file is the start file.
if (!relativePath.isEmpty()) {
entryName = entryName + "/" + relativePath;
}
// Zip uses forward slashes
entryName = entryName.replace(File.separatorChar, '/');
ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName);
if (Files.isExecutable(file))
entry.setUnixMode(0100770);
else
entry.setUnixMode(0100660);
zos.putArchiveEntry(entry);
Files.copy(file, zos);
zos.closeArchiveEntry();
return FileVisitResult.CONTINUE;
}
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
final String dirName = dir.getFileName().toString();
// Don't include pyc files or .toolkit
if (dirName.equals("__pycache__"))
return FileVisitResult.SKIP_SUBTREE;
ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/" + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/");
zos.putArchiveEntry(dirEntry);
zos.closeArchiveEntry();
return FileVisitResult.CONTINUE;
}
});
}
}
}
use of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream in project tika by apache.
the class ZipWriter method writeTo.
public void writeTo(Map<String, byte[]> parts, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
ZipArchiveOutputStream zip = new ZipArchiveOutputStream(entityStream);
zip.setMethod(ZipArchiveOutputStream.STORED);
for (Map.Entry<String, byte[]> entry : parts.entrySet()) {
zipStoreBuffer(zip, entry.getKey(), entry.getValue());
}
zip.close();
}
use of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream in project tomee by apache.
the class BuildTomEEMojo method execute.
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
super.execute();
if (formats == null) {
formats = Collections.emptyMap();
}
String prefix = catalinaBase.getParentFile().getAbsolutePath();
if (!prefix.endsWith(File.separator)) {
prefix += File.separator;
}
if (skipArchiveRootFolder) {
prefix += catalinaBase.getName() + File.separator;
}
if (zip || formats.containsKey("zip")) {
getLog().info("Zipping Custom TomEE Distribution");
final String zip = formats.get("zip");
final File output = zip != null ? new File(zip) : zipFile;
try (final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(output))) {
for (final String entry : catalinaBase.list()) {
zip(zos, new File(catalinaBase, entry), prefix);
}
} catch (final IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
attach("zip", output);
}
if (formats != null) {
//handled previously for compatibility
formats.remove("zip");
for (final Map.Entry<String, String> format : formats.entrySet()) {
final String key = format.getKey();
getLog().info(key + "-ing Custom TomEE Distribution");
if ("tar.gz".equals(key)) {
final String out = format.getValue();
final File output = out != null ? new File(out) : new File(base.getParentFile(), base.getName() + "." + key);
Files.mkdirs(output.getParentFile());
try (final TarArchiveOutputStream tarGz = new TarArchiveOutputStream(new GZIPOutputStream(new FileOutputStream(output)))) {
tarGz.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
for (final String entry : catalinaBase.list()) {
tarGz(tarGz, new File(catalinaBase, entry), prefix);
}
} catch (final IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
attach(key, output);
} else {
throw new MojoExecutionException(key + " format not supported");
}
}
}
}
Aggregations