Search in sources :

Example 11 with BasicParser

use of org.apache.commons.cli.BasicParser in project cdap by caskdata.

the class ReplicationStatusTool method parseArgs.

private static CommandLine parseArgs(String[] args) throws ParseException {
    options.addOption(MASTER_OPTION, false, "Use when running on Master Cluster");
    options.addOption(OUTPUT_OPTION, true, "FilePath to dump Master Cluster Status");
    options.addOption(INPUT_OPTION, true, "Status File copied from the Master Cluster");
    options.addOption(FILE_OPTION, true, "File with HDFS Paths");
    options.addOption(SHUTDOWNTIME_OPTION, true, "Override cdap-master Shutdown Time on Master Cluster [epoch time]");
    options.addOption(DEBUG_OPTION, false, "Dump Cluster Status for debugging");
    options.addOption(HELP_OPTION, false, "Show this Usage");
    CommandLineParser parser = new BasicParser();
    return parser.parse(options, args);
}
Also used : BasicParser(org.apache.commons.cli.BasicParser) CommandLineParser(org.apache.commons.cli.CommandLineParser)

Example 12 with BasicParser

use of org.apache.commons.cli.BasicParser in project cdap by caskdata.

the class FlowQueuePendingCorrector method parseArgs.

private static CommandLine parseArgs(String[] args) {
    Options options = new Options();
    options.addOption(createOption("n", "namespace", true, "namespace (optional, leave empty to correct all flowlets)", false));
    options.addOption(createOption("a", "app", true, "app (optional, leave empty to correct all apps)", false));
    options.addOption(createOption("f", "flow", true, "flow (optional, leave empty to correct all flows)", false));
    options.addOption(createOption("p", "producer-flowlet", true, "producer flowlet (optional, leave empty to correct entire flow)", false));
    options.addOption(createOption("c", "consumer-flowlet", true, "consumer flowlet (optional, leave empty to correct entire flow)", false));
    options.addOption(createOption("q", "queue", true, "flowlet queue (optional, defaults to \"queue\")", false));
    CommandLineParser parser = new BasicParser();
    try {
        return parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        String argsFormat = "[--namespace <namespace> " + "[--app <app> " + "[--flow <flow> " + "[[--producer-flowlet <flowlet> " + "--consumer-flowlet <flowlet> " + "[--queue <queue>]]]]]]";
        formatter.printHelp(argsFormat, options);
        System.exit(0);
        return null;
    }
}
Also used : HelpFormatter(org.apache.commons.cli.HelpFormatter) Options(org.apache.commons.cli.Options) BasicParser(org.apache.commons.cli.BasicParser) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException)

Example 13 with BasicParser

use of org.apache.commons.cli.BasicParser in project druid by druid-io.

the class RabbitMQProducerMain method main.

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();
    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg().withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg().withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg().withDescription("username to connect to the AMQP broker [defaults to AMQP library default]").create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg().withDescription("password to connect to the AMQP broker [defaults to AMQP library default]").create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg().withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]").create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg().withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg().withDescription("the routing key to use when sending messages [default: 'default.routing.key']").create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg().withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable").withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete").withDescription("if set, an auto-delete exchange will be declared [default: not set]").create("a"));
    optionList.add(OptionBuilder.withLongOpt("single").withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg().withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]").create());
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription("time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]").create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg().withDescription("the interval to add to the timestamp between messages in seconds [default: 10]").create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg().withDescription("the delay between sending messages in milliseconds [default: 100]").create());
    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });
    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }
    CommandLine cmd = null;
    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }
    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }
    ConnectionFactory factory = new ConnectionFactory();
    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }
    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }
    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));
    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));
    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);
    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);
        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);
        channel.basicPublish(exchange, routingKey, null, line.getBytes());
        System.out.println("Sent message: " + line);
        timer.add(Calendar.SECOND, interval);
        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));
    connection.close();
}
Also used : Options(org.apache.commons.cli.Options) Calendar(java.util.Calendar) Channel(com.rabbitmq.client.Channel) ArrayList(java.util.ArrayList) Connection(com.rabbitmq.client.Connection) Date(java.util.Date) Comparator(java.util.Comparator) HelpFormatter(org.apache.commons.cli.HelpFormatter) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) Random(java.util.Random) Option(org.apache.commons.cli.Option) ParseException(org.apache.commons.cli.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 14 with BasicParser

use of org.apache.commons.cli.BasicParser in project AozoraEpub3 by hmdev.

the class AozoraEpub3 method main.

/** コマンドライン実行用 */
public static void main(String[] args) {
    String jarPath = System.getProperty("java.class.path");
    int idx = jarPath.indexOf(";");
    if (idx > 0)
        jarPath = jarPath.substring(0, idx);
    if (!jarPath.endsWith(".jar"))
        jarPath = "";
    else
        jarPath = jarPath.substring(0, jarPath.lastIndexOf(File.separator) + 1);
    //this.cachePath = new File(jarPath+".cache");
    //this.webConfigPath = new File(jarPath+"web");
    /** ePub3出力クラス */
    Epub3Writer epub3Writer;
    /** ePub3画像出力クラス */
    Epub3ImageWriter epub3ImageWriter;
    /** 設定ファイル */
    Properties props;
    /** 設定ファイル名 */
    String propFileName = "AozoraEpub3.ini";
    /** 出力先パス */
    File dstPath = null;
    String helpMsg = "AozoraEpub3 [-options] input_files(txt,zip,cbz)\nversion : " + VERSION;
    try {
        //コマンドライン オプション設定
        Options options = new Options();
        options.addOption("h", "help", false, "show usage");
        options.addOption("i", "ini", true, "指定したiniファイルから設定を読み込みます (コマンドラインオプション以外の設定)");
        options.addOption("t", true, "本文内の表題種別\n[0:表題→著者名] (default)\n[1:著者名→表題]\n[2:表題→著者名(副題優先)]\n[3:表題のみ]\n[4:なし]");
        options.addOption("tf", false, "入力ファイル名を表題に利用");
        options.addOption("c", "cover", true, "表紙画像\n[0:先頭の挿絵]\n[1:ファイル名と同じ画像]\n[ファイル名 or URL]");
        options.addOption("ext", true, "出力ファイル拡張子\n[.epub] (default)\n[.kepub.epub]");
        options.addOption("of", false, "出力ファイル名を入力ファイル名に合せる");
        options.addOption("d", "dst", true, "出力先パス");
        options.addOption("enc", true, "入力ファイルエンコード\n[MS932] (default)\n[UTF-8]");
        //options.addOption("id", false, "栞用ID出力 (for Kobo)");
        //options.addOption("tcy", false, "自動縦中横有効");
        //options.addOption("g4", false, "4バイト文字変換");
        //options.addOption("tm", false, "表題を左右中央");
        //options.addOption("cp", false, "表紙画像ページ追加");
        options.addOption("hor", false, "横書き (指定がなければ縦書き)");
        options.addOption("device", true, "端末種別(指定した端末向けの例外処理を行う)\n[kindle]");
        CommandLine commandLine;
        try {
            commandLine = new BasicParser().parse(options, args, true);
        } catch (ParseException e) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //オプションの後ろをファイル名に設定
        String[] fileNames = commandLine.getArgs();
        if (fileNames.length == 0) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //ヘルプ出力
        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp(helpMsg, options);
            return;
        }
        //iniファイル確認
        if (commandLine.hasOption("i")) {
            propFileName = commandLine.getOptionValue("i");
            File file = new File(propFileName);
            if (file == null || !file.isFile()) {
                LogAppender.error("-i : ini file not exist. " + file.getAbsolutePath());
                return;
            }
        }
        //出力パス確認
        if (commandLine.hasOption("d")) {
            dstPath = new File(commandLine.getOptionValue("d"));
            if (dstPath == null || !dstPath.isDirectory()) {
                LogAppender.error("-d : dst path not exist. " + dstPath.getAbsolutePath());
                return;
            }
        }
        //ePub出力クラス初期化
        epub3Writer = new Epub3Writer(jarPath + "template/");
        epub3ImageWriter = new Epub3ImageWriter(jarPath + "template/");
        //propsから読み込み
        props = new Properties();
        try {
            props.load(new FileInputStream(propFileName));
        } catch (Exception e) {
        }
        //try { titleIndex = Integer.parseInt(props.getProperty("TitleType")); } catch (Exception e) {}//表題
        int titleIndex = 0;
        //コマンドラインオプション以外
        //表紙追加
        boolean coverPage = "1".equals(props.getProperty("CoverPage"));
        int titlePage = BookInfo.TITLE_NONE;
        if ("1".equals(props.getProperty("TitlePageWrite"))) {
            try {
                titlePage = Integer.parseInt(props.getProperty("TitlePage"));
            } catch (Exception e) {
            }
        }
        boolean withMarkId = "1".equals(props.getProperty("MarkId"));
        //boolean gaiji32 = "1".equals(props.getProperty("Gaiji32"));
        boolean commentPrint = "1".equals(props.getProperty("CommentPrint"));
        boolean commentConvert = "1".equals(props.getProperty("CommentConvert"));
        boolean autoYoko = "1".equals(props.getProperty("AutoYoko"));
        boolean autoYokoNum1 = "1".equals(props.getProperty("AutoYokoNum1"));
        boolean autoYokoNum3 = "1".equals(props.getProperty("AutoYokoNum3"));
        boolean autoYokoEQ1 = "1".equals(props.getProperty("AutoYokoEQ1"));
        int spaceHyp = 0;
        try {
            spaceHyp = Integer.parseInt(props.getProperty("SpaceHyphenation"));
        } catch (Exception e) {
        }
        //目次追加
        boolean tocPage = "1".equals(props.getProperty("TocPage"));
        //目次縦書き
        boolean tocVertical = "1".equals(props.getProperty("TocVertical"));
        boolean coverPageToc = "1".equals(props.getProperty("CoverPageToc"));
        int removeEmptyLine = 0;
        try {
            removeEmptyLine = Integer.parseInt(props.getProperty("RemoveEmptyLine"));
        } catch (Exception e) {
        }
        int maxEmptyLine = 0;
        try {
            maxEmptyLine = Integer.parseInt(props.getProperty("MaxEmptyLine"));
        } catch (Exception e) {
        }
        //画面サイズと画像リサイズ
        int dispW = 600;
        try {
            dispW = Integer.parseInt(props.getProperty("DispW"));
        } catch (Exception e) {
        }
        int dispH = 800;
        try {
            dispH = Integer.parseInt(props.getProperty("DispH"));
        } catch (Exception e) {
        }
        int coverW = 600;
        try {
            coverW = Integer.parseInt(props.getProperty("CoverW"));
        } catch (Exception e) {
        }
        int coverH = 800;
        try {
            coverH = Integer.parseInt(props.getProperty("CoverH"));
        } catch (Exception e) {
        }
        int resizeW = 0;
        if ("1".equals(props.getProperty("ResizeW")))
            try {
                resizeW = Integer.parseInt(props.getProperty("ResizeNumW"));
            } catch (Exception e) {
            }
        int resizeH = 0;
        if ("1".equals(props.getProperty("ResizeH")))
            try {
                resizeH = Integer.parseInt(props.getProperty("ResizeNumH"));
            } catch (Exception e) {
            }
        int singlePageSizeW = 480;
        try {
            singlePageSizeW = Integer.parseInt(props.getProperty("SinglePageSizeW"));
        } catch (Exception e) {
        }
        int singlePageSizeH = 640;
        try {
            singlePageSizeH = Integer.parseInt(props.getProperty("SinglePageSizeH"));
        } catch (Exception e) {
        }
        int singlePageWidth = 600;
        try {
            singlePageWidth = Integer.parseInt(props.getProperty("SinglePageWidth"));
        } catch (Exception e) {
        }
        float imageScale = 1;
        try {
            imageScale = Float.parseFloat(props.getProperty("ImageScale"));
        } catch (Exception e) {
        }
        int imageFloatType = 0;
        try {
            imageFloatType = Integer.parseInt(props.getProperty("ImageFloatType"));
        } catch (Exception e) {
        }
        int imageFloatW = 0;
        try {
            imageFloatW = Integer.parseInt(props.getProperty("ImageFloatW"));
        } catch (Exception e) {
        }
        int imageFloatH = 0;
        try {
            imageFloatH = Integer.parseInt(props.getProperty("ImageFloatH"));
        } catch (Exception e) {
        }
        int imageSizeType = SectionInfo.IMAGE_SIZE_TYPE_HEIGHT;
        try {
            imageSizeType = Integer.parseInt(props.getProperty("ImageSizeType"));
        } catch (Exception e) {
        }
        boolean fitImage = "1".equals(props.getProperty("FitImage"));
        boolean svgImage = "1".equals(props.getProperty("SvgImage"));
        int rotateImage = 0;
        if ("1".equals(props.getProperty("RotateImage")))
            rotateImage = 90;
        else if ("2".equals(props.getProperty("RotateImage")))
            rotateImage = -90;
        float jpegQualty = 0.8f;
        try {
            jpegQualty = Integer.parseInt(props.getProperty("JpegQuality")) / 100f;
        } catch (Exception e) {
        }
        float gamma = 1.0f;
        if ("1".equals(props.getProperty("Gamma")))
            try {
                gamma = Float.parseFloat(props.getProperty("GammaValue"));
            } catch (Exception e) {
            }
        int autoMarginLimitH = 0;
        int autoMarginLimitV = 0;
        int autoMarginWhiteLevel = 80;
        float autoMarginPadding = 0;
        int autoMarginNombre = 0;
        float nobreSize = 0.03f;
        if ("1".equals(props.getProperty("AutoMargin"))) {
            try {
                autoMarginLimitH = Integer.parseInt(props.getProperty("AutoMarginLimitH"));
            } catch (Exception e) {
            }
            try {
                autoMarginLimitV = Integer.parseInt(props.getProperty("AutoMarginLimitV"));
            } catch (Exception e) {
            }
            try {
                autoMarginWhiteLevel = Integer.parseInt(props.getProperty("AutoMarginWhiteLevel"));
            } catch (Exception e) {
            }
            try {
                autoMarginPadding = Float.parseFloat(props.getProperty("AutoMarginPadding"));
            } catch (Exception e) {
            }
            try {
                autoMarginNombre = Integer.parseInt(props.getProperty("AutoMarginNombre"));
            } catch (Exception e) {
            }
            try {
                autoMarginPadding = Float.parseFloat(props.getProperty("AutoMarginNombreSize"));
            } catch (Exception e) {
            }
        }
        epub3Writer.setImageParam(dispW, dispH, coverW, coverH, resizeW, resizeH, singlePageSizeW, singlePageSizeH, singlePageWidth, imageSizeType, fitImage, svgImage, rotateImage, imageScale, imageFloatType, imageFloatW, imageFloatH, jpegQualty, gamma, autoMarginLimitH, autoMarginLimitV, autoMarginWhiteLevel, autoMarginPadding, autoMarginNombre, nobreSize);
        epub3ImageWriter.setImageParam(dispW, dispH, coverW, coverH, resizeW, resizeH, singlePageSizeW, singlePageSizeH, singlePageWidth, imageSizeType, fitImage, svgImage, rotateImage, imageScale, imageFloatType, imageFloatW, imageFloatH, jpegQualty, gamma, autoMarginLimitH, autoMarginLimitV, autoMarginWhiteLevel, autoMarginPadding, autoMarginNombre, nobreSize);
        //目次階層化設定
        epub3Writer.setTocParam("1".equals(props.getProperty("NavNest")), "1".equals(props.getProperty("NcxNest")));
        //スタイル設定
        String[] pageMargin = {};
        try {
            pageMargin = props.getProperty("PageMargin").split(",");
        } catch (Exception e) {
        }
        if (pageMargin.length != 4)
            pageMargin = new String[] { "0", "0", "0", "0" };
        else {
            String pageMarginUnit = props.getProperty("PageMarginUnit");
            for (int i = 0; i < 4; i++) {
                pageMargin[i] += pageMarginUnit;
            }
        }
        String[] bodyMargin = {};
        try {
            bodyMargin = props.getProperty("BodyMargin").split(",");
        } catch (Exception e) {
        }
        if (bodyMargin.length != 4)
            bodyMargin = new String[] { "0", "0", "0", "0" };
        else {
            String bodyMarginUnit = props.getProperty("BodyMarginUnit");
            for (int i = 0; i < 4; i++) {
                bodyMargin[i] += bodyMarginUnit;
            }
        }
        float lineHeight = 1.8f;
        try {
            lineHeight = Float.parseFloat(props.getProperty("LineHeight"));
        } catch (Exception e) {
        }
        int fontSize = 100;
        try {
            fontSize = Integer.parseInt(props.getProperty("FontSize"));
        } catch (Exception e) {
        }
        boolean boldUseGothic = "1".equals(props.getProperty("BoldUseGothic"));
        boolean gothicUseBold = "1".equals(props.getProperty("gothicUseBold"));
        epub3Writer.setStyles(pageMargin, bodyMargin, lineHeight, fontSize, boldUseGothic, gothicUseBold);
        //自動改ページ
        int forcePageBreakSize = 0;
        int forcePageBreakEmpty = 0;
        int forcePageBreakEmptySize = 0;
        int forcePageBreakChapter = 0;
        int forcePageBreakChapterSize = 0;
        if ("1".equals(props.getProperty("PageBreak"))) {
            try {
                try {
                    forcePageBreakSize = Integer.parseInt(props.getProperty("PageBreakSize")) * 1024;
                } catch (Exception e) {
                }
                if ("1".equals(props.getProperty("PageBreakEmpty"))) {
                    try {
                        forcePageBreakEmpty = Integer.parseInt(props.getProperty("PageBreakEmptyLine"));
                    } catch (Exception e) {
                    }
                    try {
                        forcePageBreakEmptySize = Integer.parseInt(props.getProperty("PageBreakEmptySize")) * 1024;
                    } catch (Exception e) {
                    }
                }
                if ("1".equals(props.getProperty("PageBreakChapter"))) {
                    forcePageBreakChapter = 1;
                    try {
                        forcePageBreakChapterSize = Integer.parseInt(props.getProperty("PageBreakChapterSize")) * 1024;
                    } catch (Exception e) {
                    }
                }
            } catch (Exception e) {
            }
        }
        int maxLength = 64;
        try {
            maxLength = Integer.parseInt((props.getProperty("ChapterNameLength")));
        } catch (Exception e) {
        }
        boolean insertTitleToc = "1".equals(props.getProperty("TitleToc"));
        boolean chapterExclude = "1".equals(props.getProperty("ChapterExclude"));
        boolean chapterUseNextLine = "1".equals(props.getProperty("ChapterUseNextLine"));
        boolean chapterSection = !props.containsKey("ChapterSection") || "1".equals(props.getProperty("ChapterSection"));
        boolean chapterH = "1".equals(props.getProperty("ChapterH"));
        boolean chapterH1 = "1".equals(props.getProperty("ChapterH1"));
        boolean chapterH2 = "1".equals(props.getProperty("ChapterH2"));
        boolean chapterH3 = "1".equals(props.getProperty("ChapterH3"));
        boolean sameLineChapter = "1".equals(props.getProperty("SameLineChapter"));
        boolean chapterName = "1".equals(props.getProperty("ChapterName"));
        boolean chapterNumOnly = "1".equals(props.getProperty("ChapterNumOnly"));
        boolean chapterNumTitle = "1".equals(props.getProperty("ChapterNumTitle"));
        boolean chapterNumParen = "1".equals(props.getProperty("ChapterNumParen"));
        boolean chapterNumParenTitle = "1".equals(props.getProperty("hapterNumParenTitle"));
        String chapterPattern = "";
        if ("1".equals(props.getProperty("ChapterPattern")))
            chapterPattern = props.getProperty("ChapterPatternText");
        //オプション指定を反映
        //表題に入力ファイル名利用
        boolean useFileName = false;
        String coverFileName = null;
        String encType = "MS932";
        String outExt = ".epub";
        //ファイル名を表題に利用
        boolean autoFileName = true;
        boolean vertical = true;
        String targetDevice = null;
        //表題
        if (commandLine.hasOption("t"))
            try {
                titleIndex = Integer.parseInt(commandLine.getOptionValue("t"));
            } catch (Exception e) {
            }
        if (commandLine.hasOption("tf"))
            useFileName = true;
        if (commandLine.hasOption("c"))
            coverFileName = commandLine.getOptionValue("c");
        if (commandLine.hasOption("enc"))
            encType = commandLine.getOptionValue("enc");
        if (commandLine.hasOption("ext"))
            outExt = commandLine.getOptionValue("ext");
        if (commandLine.hasOption("of"))
            autoFileName = false;
        //if(commandLine.hasOption("cp")) coverPage = true;
        if (commandLine.hasOption("hor"))
            vertical = false;
        if (commandLine.hasOption("device")) {
            targetDevice = commandLine.getOptionValue("device");
            if (targetDevice.equalsIgnoreCase("kindle")) {
                epub3Writer.setIsKindle(true);
            }
        }
        //変換クラス生成とパラメータ設定
        AozoraEpub3Converter aozoraConverter = new AozoraEpub3Converter(epub3Writer, jarPath);
        //挿絵なし
        aozoraConverter.setNoIllust("1".equals(props.getProperty("NoIllust")));
        //栞用span出力
        aozoraConverter.setWithMarkId(withMarkId);
        //変換オプション設定
        aozoraConverter.setAutoYoko(autoYoko, autoYokoNum1, autoYokoNum3, autoYokoEQ1);
        //文字出力設定
        int dakutenType = 0;
        try {
            dakutenType = Integer.parseInt(props.getProperty("DakutenType"));
        } catch (Exception e) {
        }
        boolean printIvsBMP = "1".equals(props.getProperty("IvsBMP"));
        boolean printIvsSSP = "1".equals(props.getProperty("IvsSSP"));
        aozoraConverter.setCharOutput(dakutenType, printIvsBMP, printIvsSSP);
        //全角スペースの禁則
        aozoraConverter.setSpaceHyphenation(spaceHyp);
        //コメント
        aozoraConverter.setCommentPrint(commentPrint, commentConvert);
        aozoraConverter.setRemoveEmptyLine(removeEmptyLine, maxEmptyLine);
        //強制改ページ
        aozoraConverter.setForcePageBreak(forcePageBreakSize, forcePageBreakEmpty, forcePageBreakEmptySize, forcePageBreakChapter, forcePageBreakChapterSize);
        //目次設定
        aozoraConverter.setChapterLevel(maxLength, chapterExclude, chapterUseNextLine, chapterSection, chapterH, chapterH1, chapterH2, chapterH3, sameLineChapter, chapterName, chapterNumOnly, chapterNumTitle, chapterNumParen, chapterNumParenTitle, chapterPattern);
        ////////////////////////////////
        for (String fileName : fileNames) {
            LogAppender.println("--------");
            File srcFile = new File(fileName);
            if (srcFile == null || !srcFile.isFile()) {
                LogAppender.error("file not exist. " + srcFile.getAbsolutePath());
                continue;
            }
            String ext = srcFile.getName();
            ext = ext.substring(ext.lastIndexOf('.') + 1).toLowerCase();
            int coverImageIndex = -1;
            if (coverFileName != null) {
                if ("0".equals(coverFileName)) {
                    coverImageIndex = 0;
                    coverFileName = "";
                } else if ("1".equals(coverFileName)) {
                    //入力ファイルと同じ名前+.jpg/.png
                    coverFileName = AozoraEpub3.getSameCoverFileName(srcFile);
                }
            }
            //zipならzip内のテキストを検索
            int txtCount = 1;
            boolean imageOnly = false;
            boolean isFile = "txt".equals(ext);
            if ("zip".equals(ext) || "txtz".equals(ext)) {
                try {
                    txtCount = AozoraEpub3.countZipText(srcFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (txtCount == 0) {
                    txtCount = 1;
                    imageOnly = true;
                }
            } else if ("rar".equals(ext)) {
                try {
                    txtCount = AozoraEpub3.countRarText(srcFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (txtCount == 0) {
                    txtCount = 1;
                    imageOnly = true;
                }
            } else if ("cbz".equals(ext)) {
                imageOnly = true;
            }
            for (int txtIdx = 0; txtIdx < txtCount; txtIdx++) {
                ImageInfoReader imageInfoReader = new ImageInfoReader(isFile, srcFile);
                BookInfo bookInfo = null;
                if (!imageOnly) {
                    bookInfo = AozoraEpub3.getBookInfo(srcFile, ext, txtIdx, imageInfoReader, aozoraConverter, encType, BookInfo.TitleType.indexOf(titleIndex), false);
                    bookInfo.vertical = vertical;
                    bookInfo.insertTocPage = tocPage;
                    bookInfo.setTocVertical(tocVertical);
                    bookInfo.insertTitleToc = insertTitleToc;
                    aozoraConverter.vertical = vertical;
                    //表題ページ
                    bookInfo.titlePageType = titlePage;
                }
                //表題の見出しが非表示で行が追加されていたら削除
                if (!bookInfo.insertTitleToc && bookInfo.titleLine >= 0) {
                    bookInfo.removeChapterLineInfo(bookInfo.titleLine);
                }
                Epub3Writer writer = epub3Writer;
                if (!isFile) {
                    if ("rar".equals(ext)) {
                        imageInfoReader.loadRarImageInfos(srcFile, imageOnly);
                    } else {
                        imageInfoReader.loadZipImageInfos(srcFile, imageOnly);
                    }
                    if (imageOnly) {
                        LogAppender.println("画像のみのePubファイルを生成します");
                        //画像出力用のBookInfo生成
                        bookInfo = new BookInfo(srcFile);
                        bookInfo.imageOnly = true;
                        //Writerを画像出力用派生クラスに入れ替え
                        writer = epub3ImageWriter;
                        if (imageInfoReader.countImageFileInfos() == 0) {
                            LogAppender.error("画像がありませんでした");
                            return;
                        }
                        //名前順で並び替え
                        imageInfoReader.sortImageFileNames();
                    }
                }
                //先頭からの場合で指定行数以降なら表紙無し
                if ("".equals(coverFileName)) {
                    try {
                        int maxCoverLine = Integer.parseInt(props.getProperty("MaxCoverLine"));
                        if (maxCoverLine > 0 && bookInfo.firstImageLineNum >= maxCoverLine) {
                            coverImageIndex = -1;
                            coverFileName = null;
                        }
                    } catch (Exception e) {
                    }
                }
                //表紙設定
                bookInfo.insertCoverPageToc = coverPageToc;
                bookInfo.insertCoverPage = coverPage;
                bookInfo.coverImageIndex = coverImageIndex;
                if (coverFileName != null && !coverFileName.startsWith("http")) {
                    File coverFile = new File(coverFileName);
                    if (!coverFile.exists()) {
                        coverFileName = srcFile.getParent() + "/" + coverFileName;
                        if (!new File(coverFileName).exists()) {
                            coverFileName = null;
                            LogAppender.println("[WARN] 表紙画像ファイルが見つかりません : " + coverFile.getAbsolutePath());
                        }
                    }
                }
                bookInfo.coverFileName = coverFileName;
                String[] titleCreator = BookInfo.getFileTitleCreator(srcFile.getName());
                if (titleCreator != null) {
                    if (useFileName) {
                        if (titleCreator[0] != null && titleCreator[0].trim().length() > 0)
                            bookInfo.title = titleCreator[0];
                        if (titleCreator[1] != null && titleCreator[1].trim().length() > 0)
                            bookInfo.creator = titleCreator[1];
                    } else {
                        //テキストから取得できていない場合
                        if (bookInfo.title == null || bookInfo.title.length() == 0)
                            bookInfo.title = titleCreator[0] == null ? "" : titleCreator[0];
                        if (bookInfo.creator == null || bookInfo.creator.length() == 0)
                            bookInfo.creator = titleCreator[1] == null ? "" : titleCreator[1];
                    }
                }
                File outFile = getOutFile(srcFile, dstPath, bookInfo, autoFileName, outExt);
                AozoraEpub3.convertFile(srcFile, ext, outFile, aozoraConverter, writer, encType, bookInfo, imageInfoReader, txtIdx);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Options(org.apache.commons.cli.Options) Epub3Writer(com.github.hmdev.writer.Epub3Writer) ImageInfoReader(com.github.hmdev.image.ImageInfoReader) BookInfo(com.github.hmdev.info.BookInfo) IOException(java.io.IOException) Epub3ImageWriter(com.github.hmdev.writer.Epub3ImageWriter) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) RarException(com.github.junrar.exception.RarException) IOException(java.io.IOException) ParseException(org.apache.commons.cli.ParseException) HelpFormatter(org.apache.commons.cli.HelpFormatter) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) AozoraEpub3Converter(com.github.hmdev.converter.AozoraEpub3Converter) ParseException(org.apache.commons.cli.ParseException) File(java.io.File)

Example 15 with BasicParser

use of org.apache.commons.cli.BasicParser in project languagetool by languagetool-org.

the class BuilderOptions method parseArguments.

@NotNull
public CommandLine parseArguments(String[] args, Class<? extends DictionaryBuilder> clazz) throws ParseException {
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        return cmd;
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(clazz.getName(), options);
        System.exit(1);
        // should never happen - just to make compiler happy
        throw e;
    }
}
Also used : HelpFormatter(org.apache.commons.cli.HelpFormatter) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

BasicParser (org.apache.commons.cli.BasicParser)23 CommandLine (org.apache.commons.cli.CommandLine)19 CommandLineParser (org.apache.commons.cli.CommandLineParser)14 Options (org.apache.commons.cli.Options)14 ParseException (org.apache.commons.cli.ParseException)14 HelpFormatter (org.apache.commons.cli.HelpFormatter)11 IOException (java.io.IOException)8 Option (org.apache.commons.cli.Option)6 File (java.io.File)5 ClientConfig (co.cask.cdap.client.config.ClientConfig)2 NullStatsProvider (org.apache.bookkeeper.stats.NullStatsProvider)2 StatsProvider (org.apache.bookkeeper.stats.StatsProvider)2 Logger (ch.qos.logback.classic.Logger)1 AltStyleTableRenderer (co.cask.cdap.cli.util.table.AltStyleTableRenderer)1 ArtifactClient (co.cask.cdap.client.ArtifactClient)1 DisconnectedException (co.cask.cdap.client.exception.DisconnectedException)1 CConfiguration (co.cask.cdap.common.conf.CConfiguration)1 ConfigModule (co.cask.cdap.common.guice.ConfigModule)1 InsecureFileContextLocationFactory (co.cask.cdap.common.guice.InsecureFileContextLocationFactory)1 CoprocessorManager (co.cask.cdap.data2.util.hbase.CoprocessorManager)1