Java tutorial
/** * Copyright (C) 2014 EMBL - European Bioinformatics Institute * * All rights reserved. This file is part of the YOLogP project. * * author: oXis (Benjamin Roques) * * This program is free software; you can redistribute it and/or * modify it under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, * please visit http://creativecommons.org/licenses/by-nc-sa/4.0/. * All we ask is that proper credit is given for my work, which includes * - but is not limited to - adding the above copyright notice to the beginning * of your source code files, and to any copyright notice that you may distribute * with programs based on this work. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package oxis.yologp; /** * * @author John May, edited by oXis */ import java.io.File; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.cli.*; /** * Abstract object for when a main is runnable on the command line. The object * effectively provides a wrapper for command option processing utilising the * Apache Commons CLI library * * @author John May */ public abstract class CommandLineMain extends ArrayList<Option> { private final Options options = new Options(); private final CommandLineParser parser = new PosixParser(); private CommandLine cmdLine = null; public abstract void setupOptions(); /** * Main processing method */ public abstract void process(); public CommandLineMain(String[] args) { setupOptions(); for (Option opt : this) { options.addOption(opt); } options.addOption(new Option("h", "help", false, "print the help section")); try { cmdLine = parser.parse(options, args); } catch (ParseException ex) { Logger.getLogger(CommandLineMain.class.getName()).log(Level.SEVERE, "Could not parse arguments!", ex); } if (cmdLine.hasOption('h') || cmdLine.hasOption("help")) { printHelp(); } } public CommandLine getCommandLine() { return cmdLine; } public boolean hasOption(String option) { return getCommandLine().hasOption(option); } /** * Convenience method for accessing a file from the parsed options. */ public File getFileOption(String option) throws IllegalArgumentException { if (getCommandLine().hasOption(option)) { if (new File(getCommandLine().getOptionValue(option)).isFile()) { return new File(getCommandLine().getOptionValue(option)); } else { throw new IllegalArgumentException(); } } else { throw new IllegalArgumentException(); } } public void printHelp() { for (Object obj : options.getOptions().toArray(new Option[0])) { Option opt = (Option) obj; System.out.println( String.format(" -%s|--%-30s ", opt.getOpt(), opt.getLongOpt()) + opt.getDescription()); } System.exit(0); } }