Search in sources :

Example 31 with ArchiveEntry

use of org.apache.commons.compress.archivers.ArchiveEntry 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;
    }
}
Also used : Archive(com.github.junrar.Archive) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) InputStream(java.io.InputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) Vector(java.util.Vector) FileHeader(com.github.junrar.rarfile.FileHeader) FileInputStream(java.io.FileInputStream)

Example 32 with ArchiveEntry

use of org.apache.commons.compress.archivers.ArchiveEntry 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;
    }
}
Also used : ChapterInfo(com.github.hmdev.info.ChapterInfo) Archive(com.github.junrar.Archive) CRC32(java.util.zip.CRC32) VelocityContext(org.apache.velocity.VelocityContext) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) BufferedInputStream(java.io.BufferedInputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ImageInfo(com.github.hmdev.info.ImageInfo) BufferedOutputStream(java.io.BufferedOutputStream) FileHeader(com.github.junrar.rarfile.FileHeader) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) InputStream(java.io.InputStream) ChapterLineInfo(com.github.hmdev.info.ChapterLineInfo) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) SectionInfo(com.github.hmdev.info.SectionInfo) GaijiInfo(com.github.hmdev.info.GaijiInfo) File(java.io.File)

Example 33 with ArchiveEntry

use of org.apache.commons.compress.archivers.ArchiveEntry in project AozoraEpub3 by hmdev.

the class ImageInfoReader method loadZipImageInfos.

/**
 * zip内の画像情報をすべて読み込み
 * @throws IOException
 */
public void loadZipImageInfos(File srcFile, boolean addFileName) throws IOException {
    ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), 65536), "MS932", false);
    try {
        ArchiveEntry entry;
        int idx = 0;
        while ((entry = zis.getNextEntry()) != null) {
            if (idx++ % 10 == 0)
                LogAppender.append(".");
            String entryName = entry.getName();
            String lowerName = entryName.toLowerCase();
            if (lowerName.endsWith(".png") || lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".gif")) {
                ImageInfo imageInfo = null;
                try {
                    imageInfo = ImageInfo.getImageInfo(zis, zis.getCount());
                } catch (Exception e) {
                    LogAppender.error("画像が読み込めませんでした: " + srcFile.getPath());
                    e.printStackTrace();
                }
                if (imageInfo != null) {
                    this.imageFileInfos.put(entryName, imageInfo);
                    if (addFileName)
                        this.addImageFileName(entryName);
                }
            }
        }
    } finally {
        LogAppender.println();
        zis.close();
    }
}
Also used : ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) BufferedInputStream(java.io.BufferedInputStream) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) ImageInfo(com.github.hmdev.info.ImageInfo) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) RarException(com.github.junrar.exception.RarException)

Example 34 with ArchiveEntry

use of org.apache.commons.compress.archivers.ArchiveEntry in project gerrit by GerritCodeReview.

the class UploadArchiveIT method assertEntries.

private void assertEntries(ArchiveInputStream o) throws IOException {
    Set<String> entryNames = new TreeSet<>();
    ArchiveEntry e;
    while ((e = o.getNextEntry()) != null) {
        entryNames.add(e.getName());
    }
    assertThat(entryNames).containsExactly(String.format("%s/", commit.commit), String.format("%s/%s", commit.commit, FILE_NAME)).inOrder();
}
Also used : TreeSet(java.util.TreeSet) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry)

Example 35 with ArchiveEntry

use of org.apache.commons.compress.archivers.ArchiveEntry in project packr by libgdx.

the class ArchiveUtils method createArchive.

/**
 * Creates a new archive from the contents in {@code directoryToArchive}.
 *
 * @param archiveType        the type of archive to create
 * @param directoryToArchive the directory to archive the contents of
 * @param archiveFile        the file to write the archive to
 * @throws IOException      if an IO error occurs
 * @throws ArchiveException if an archive error occurs
 */
public static void createArchive(ArchiveType archiveType, Path directoryToArchive, Path archiveFile) throws IOException, ArchiveException {
    try (OutputStream fileOutputStream = new BufferedOutputStream(Files.newOutputStream(archiveFile));
        ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(archiveType.getCommonsCompressName(), fileOutputStream)) {
        if (archiveType == ArchiveType.TAR) {
            ((TarArchiveOutputStream) archiveOutputStream).setLongFileMode(LONGFILE_GNU);
        }
        Files.walkFileTree(directoryToArchive, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                createAndPutArchiveEntry(archiveType, archiveOutputStream, directoryToArchive, file);
                archiveOutputStream.closeArchiveEntry();
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (Files.isSameFile(dir, directoryToArchive)) {
                    return FileVisitResult.CONTINUE;
                }
                ArchiveEntry entry = archiveOutputStream.createArchiveEntry(dir.toFile(), getRelativePathString(dir, directoryToArchive));
                archiveOutputStream.putArchiveEntry(entry);
                archiveOutputStream.closeArchiveEntry();
                return FileVisitResult.CONTINUE;
            }
        });
        archiveOutputStream.finish();
    }
}
Also used : ArchiveStreamFactory(org.apache.commons.compress.archivers.ArchiveStreamFactory) Path(java.nio.file.Path) BufferedOutputStream(java.io.BufferedOutputStream) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) OutputStream(java.io.OutputStream) ArchiveOutputStream(org.apache.commons.compress.archivers.ArchiveOutputStream) FileVisitResult(java.nio.file.FileVisitResult) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ArchiveEntry(org.apache.commons.compress.archivers.ArchiveEntry) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) JarArchiveEntry(org.apache.commons.compress.archivers.jar.JarArchiveEntry) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) ArchiveOutputStream(org.apache.commons.compress.archivers.ArchiveOutputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

ArchiveEntry (org.apache.commons.compress.archivers.ArchiveEntry)62 File (java.io.File)24 FileInputStream (java.io.FileInputStream)24 IOException (java.io.IOException)22 TarArchiveInputStream (org.apache.commons.compress.archivers.tar.TarArchiveInputStream)20 ZipArchiveEntry (org.apache.commons.compress.archivers.zip.ZipArchiveEntry)19 ZipArchiveInputStream (org.apache.commons.compress.archivers.zip.ZipArchiveInputStream)17 InputStream (java.io.InputStream)16 FileOutputStream (java.io.FileOutputStream)11 TarArchiveEntry (org.apache.commons.compress.archivers.tar.TarArchiveEntry)11 BufferedInputStream (java.io.BufferedInputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 Path (java.nio.file.Path)9 ArchiveInputStream (org.apache.commons.compress.archivers.ArchiveInputStream)9 ArchiveStreamFactory (org.apache.commons.compress.archivers.ArchiveStreamFactory)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 ArchiveException (org.apache.commons.compress.archivers.ArchiveException)6 OutputStream (java.io.OutputStream)5 TarArchiveOutputStream (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream)5 BufferedOutputStream (java.io.BufferedOutputStream)4