001package co.codewizards.cloudstore.client; 002 003import org.kohsuke.args4j.CmdLineException; 004import org.kohsuke.args4j.CmdLineParser; 005import org.kohsuke.args4j.Option; 006import org.kohsuke.args4j.OptionDef; 007import org.kohsuke.args4j.spi.OneArgumentOptionHandler; 008import org.kohsuke.args4j.spi.Setter; 009 010import co.codewizards.cloudstore.core.TimeUnit; 011 012/** 013 * <p> 014 * Option handler implementation to interprete a time period (e.g. "5 minutes". 015 * </p> 016 * <p> 017 * The time period is specified in the command line by writing a number 018 * directly followed (no space!) by a unit. For example 5 minutes could be 019 * written as "5min" or "300s" (300 seconds are 5 minutes). 020 * </p> 021 * <p> 022 * This handler can be chosen for every <code>long</code> property using 023 * the {@link Option} annotation like this: 024 * </p> 025 * <pre> 026 * @Option(name="-myArg", handler=TimePeriodOptionHandler.class) 027 * private long myArg; 028 * </pre> 029 * <p> 030 * The <code>long</code> property will be set to the milliseconds value. 031 * For example, if the command line user passes "5min", the <code>long</code> value 032 * will be 300000 (5 min * 60 s * 1000 ms). 033 * </p> 034 * 035 * @author Marco หงุ่ยตระกูล-Schulze - marco at nightlabs dot de 036 */ 037public class TimePeriodOptionHandler extends OneArgumentOptionHandler<Long> 038{ 039 public TimePeriodOptionHandler(CmdLineParser parser, OptionDef option, Setter<Long> setter) 040 { 041 super(parser, option, setter); 042 } 043 044 @Override 045 protected Long parse(String argument) throws NumberFormatException, CmdLineException 046 { 047 TimeUnit timeUnit = null; 048 for (TimeUnit u : TimeUnit.values()) { 049 if (argument.endsWith(u.name()) && (timeUnit == null || timeUnit.name().length() < u.name().length())) 050 timeUnit = u; 051 } 052 053 if (timeUnit == null) 054 throw new CmdLineException(owner, "Argument '" + argument + "' does not end with one of the following unit-suffixes: " + TimeUnit.getAllUnitsWithDisplayName()); 055 056 String numberVal = argument.substring(0, argument.length() - timeUnit.name().length()).trim(); 057 long valueMSec = Long.parseLong(numberVal); 058 return timeUnit.toMillis(valueMSec); 059 } 060 061}