Example usage for java.lang IllegalArgumentException IllegalArgumentException

List of usage examples for java.lang IllegalArgumentException IllegalArgumentException

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException IllegalArgumentException.

Prototype

public IllegalArgumentException() 

Source Link

Document

Constructs an IllegalArgumentException with no detail message.

Usage

From source file:MonthsInYear.java

public static void main(String[] args) {
    int year = 0;

    if (args.length <= 0) {
        System.out.printf("Usage: MonthsInYear <year>%n");
        throw new IllegalArgumentException();
    }//from ww  w  . ja  va2 s .c  o  m

    try {
        year = Integer.parseInt(args[0]);
    } catch (NumberFormatException nexc) {
        System.out.printf("%s is not a properly formatted number.%n", args[0]);
        throw nexc; // Rethrow the exception.
    }

    try {
        Year test = Year.of(year);
    } catch (DateTimeException exc) {
        System.out.printf("%d is not a valid year.%n", year);
        throw exc; // Rethrow the exception.
    }

    System.out.printf("For the year %d:%n", year);
    for (Month month : Month.values()) {
        YearMonth ym = YearMonth.of(year, month);
        System.out.printf("%s: %d days%n", month, ym.lengthOfMonth());
    }
}

From source file:Superstitious.java

public static void main(String[] args) {
    Month month = null;// w  w w  . ja va2 s . c  o  m
    LocalDate date = null;

    if (args.length < 2) {
        System.out.printf("Usage: Superstitious <month> <day>%n");
        throw new IllegalArgumentException();
    }

    try {
        month = Month.valueOf(args[0].toUpperCase());
    } catch (IllegalArgumentException exc) {
        System.out.printf("%s is not a valid month.%n", args[0]);
        throw exc; // Rethrow the exception.
    }

    int day = Integer.parseInt(args[1]);

    try {
        date = Year.now().atMonth(month).atDay(day);
    } catch (DateTimeException exc) {
        System.out.printf("%s %s is not a valid date.%n", month, day);
        throw exc; // Rethrow the exception.
    }

    System.out.println(date.query(new FridayThirteenQuery()));
}

From source file:com.ahanda.techops.noty.clientTest.Client.java

public static void main(String[] args) throws Exception {
    if (args.length == 1) {
        System.setProperty("PINT.conf", args[0]);
    }/*from   w ww . jav  a 2 s. c  o  m*/

    if (System.getProperty("PINT.conf") == null)
        throw new IllegalArgumentException();

    JsonNode config = null;
    Config cf = Config.getInstance();
    cf.setupConfig();

    String scheme = "http";
    String host = cf.getHttpHost();
    int port = cf.getHttpPort();

    if (port == -1) {
        port = 8080;
    }

    if (!"http".equalsIgnoreCase(scheme)) {
        l.warn("Only HTTP is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                // p.addLast( "decoder", new HttpResponseDecoder());
                // p.addLast( "encoder", new HttpRequestEncoder());

                // Remove the following line if you don't want automatic content decompression.
                // p.addLast(new HttpContentDecompressor());

                // Uncomment the following line if you don't want to handle HttpContents.
                p.addLast(new HttpObjectAggregator(10485760));

                p.addLast(new ClientHandler());
            }
        });

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        ClientHandler client = new ClientHandler();
        client.login(ch, ClientHandler.credential);
        // ClientHandler.pubEvent( ch, ClientHandler.event );

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
        l.info("Closing Client side Connection !!!");
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:ListMondays.java

public static void main(String[] args) {
    Month month = null;// w ww.  j a v  a  2s  .co  m

    if (args.length < 1) {
        System.out.printf("Usage: ListMondays <month>%n");
        throw new IllegalArgumentException();
    }

    try {
        month = Month.valueOf(args[0].toUpperCase());
    } catch (IllegalArgumentException exc) {
        System.out.printf("%s is not a valid month.%n", args[0]);
        throw exc; // Rethrow the exception.
    }

    System.out.printf("For the month of %s:%n", month);
    LocalDate date = Year.now().atMonth(month).atDay(1).with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
    Month mi = date.getMonth();
    while (mi == month) {
        System.out.printf("%s%n", date);
        date = date.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        mi = date.getMonth();
    }
}

From source file:com.stgmastek.core.comm.main.StartCoreCommunication.java

/**
 * Main method that would have to be called to up the CORE Communication
 * System//from w  w  w .j  a  va  2s.  com
 * 
 * @param args
 *            Any runtime arguments, none in this case
 */
public static void main(String[] args) throws Throwable {
    if (args.length < 2) {
        printUsage();
        throw new IllegalArgumentException();
    }
    COMMAND command;
    try {
        command = Constants.COMMAND.resolve(args[0]);
    } catch (Throwable t) {
        printUsage();
        throw t;
    }

    String log4jProp = args[1];
    if ("".equals(log4jProp)) {
        printUsage();
        throw new IllegalArgumentException();
    }
    PropertyConfigurator.configure(args[1]);

    // Boot the configurations
    boot();
    switch (command) {
    case startup:
        start();
        break;
    case shutdown:
        stop();
        break;
    default:
        break;
    }
}

From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java

public static void main(String[] args) throws Exception {
    HelpFormatter formatter = new HelpFormatter();

    // cli options
    Options options = new Options();
    options.addOption(CMD_OPT_INPUT, true, "Input file");
    // options.addOption(CMD_OPT_OUTPUT, true, "Output file");

    try {//from   www. ja v a  2 s.c om

        // evaluate command line options
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(CMD_OPT_INPUT)) {
            // option value
            String optionValue = cmd.getOptionValue(CMD_OPT_INPUT);

            // input file
            File inputFile = new File(optionValue);

            // id extractor
            IdExtractor idExtractor = new IdExtractor(inputFile);
            Vector<Vector> data = idExtractor.parse();

            // // TODO implement output folder
            // if (cmd.hasOption(CMD_OPT_OUTPUT))
            // {
            // // file output
            // throw new Exception("Not implemented");
            // }
            // else
            // {
            // console output
            System.out.println("Id;Value");
            for (Vector vector : data) {
                StringBuilder sb = new StringBuilder();
                if (vector.size() >= 1) {
                    sb.append(vector.get(0));
                }
                sb.append(";");
                if (vector.size() >= 2) {
                    sb.append(vector.get(1));
                }
                System.out.println(sb.toString());
            }
            // }
        } else {
            throw new IllegalArgumentException();
        }

    } catch (ParseException e) {
        formatter.printHelp("ExtractorCLI", options);
    } catch (IllegalArgumentException e) {
        formatter.printHelp("ExtractorCLI", options);
    }
}

From source file:scalespace.filter.Gaussian_Derivative_.java

public static void main(String[] args) {

    try {//w w  w  .  j  av  a 2s. c  o  m

        File f = new File(args[0]);

        if (f.exists() && f.isDirectory()) {
            System.setProperty("plugins.dir", args[0]);
            new ImageJ();
        } else {
            throw new IllegalArgumentException();
        }
    } catch (Exception ex) {
        IJ.log("plugins.dir misspecified\n");
        ex.printStackTrace();
    }

}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param args/*from   w  w  w.j a v a  2s  .co m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String command = null;
    if (args.length == 0) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_STARTUP)) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_SHUTDOWN)) {
        command = COMMAND_SHUTDOWN;
    }

    if (command == null) {
        throw new IllegalArgumentException();
    }

    String propertyFile = DEFAULT_PROPERTY_FILE_NAME; // default
    if (args.length == 2) {
        propertyFile = args[1];
    }
    final Properties properties = new Properties();
    FileInputStream inputStream = new FileInputStream(propertyFile);
    try {
        properties.load(inputStream);
    } finally {
        inputStream.close();
    }

    if (command.equals(COMMAND_STARTUP)) {

        new Thread(new Runnable() {
            public void run() {
                try {

                    AutoExecServer autoExecServer = new AutoExecServer();

                    autoExecServer.startup(properties);
                    autoExecServer.runningLoop();
                    autoExecServer.destroy();

                } catch (Exception e) {
                    log.error("Error", e);
                    e.printStackTrace();
                } finally {
                    System.exit(0);
                }
            }
        }).start();

    } else {

        StringBuilder commandURL = new StringBuilder("http://localhost:");
        commandURL.append(
                PropertiesUtils.getInt(properties, "port", RemoteControlConfiguration.getDefaultPort()));
        commandURL.append(CONTEXT_PATH_COMMAND);

        RemoteControlClient client = new RemoteControlClient(commandURL.toString());

        client.stopServer();
    }
}

From source file:net.sf.mcf2pdf.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option o = OptionBuilder.hasArg().isRequired()
            .withDescription("Installation location of My CEWE Photobook. REQUIRED.").create('i');
    options.addOption(o);//from   ww  w . j  a v  a  2 s  .  co m
    options.addOption("h", false, "Prints this help and exits.");
    options.addOption("t", true, "Location of MCF temporary files.");
    options.addOption("w", true, "Location for temporary images generated during conversion.");
    options.addOption("r", true, "Sets the resolution to use for page rendering, in DPI. Default is 150.");
    options.addOption("n", true, "Sets the page number to render up to. Default renders all pages.");
    options.addOption("b", false, "Prevents rendering of binding between double pages.");
    options.addOption("x", false, "Generates only XSL-FO content instead of PDF content.");
    options.addOption("q", false, "Quiet mode - only errors are logged.");
    options.addOption("d", false, "Enables debugging logging output.");

    CommandLine cl;
    try {
        CommandLineParser parser = new PosixParser();
        cl = parser.parse(options, args);
    } catch (ParseException pe) {
        printUsage(options, pe);
        System.exit(3);
        return;
    }

    if (cl.hasOption("h")) {
        printUsage(options, null);
        return;
    }

    if (cl.getArgs().length != 2) {
        printUsage(options,
                new ParseException("INFILE and OUTFILE must be specified. Arguments were: " + cl.getArgList()));
        System.exit(3);
        return;
    }

    File installDir = new File(cl.getOptionValue("i"));
    if (!installDir.isDirectory()) {
        printUsage(options, new ParseException("Specified installation directory does not exist."));
        System.exit(3);
        return;
    }

    File tempDir = null;
    String sTempDir = cl.getOptionValue("t");
    if (sTempDir == null) {
        tempDir = new File(new File(System.getProperty("user.home")), ".mcf");
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("MCF temporary location not specified and default location "
                    + tempDir + " does not exist."));
            System.exit(3);
            return;
        }
    } else {
        tempDir = new File(sTempDir);
        if (!tempDir.isDirectory()) {
            printUsage(options, new ParseException("Specified temporary location does not exist."));
            System.exit(3);
            return;
        }
    }

    File mcfFile = new File(cl.getArgs()[0]);
    if (!mcfFile.isFile()) {
        printUsage(options, new ParseException("MCF input file does not exist."));
        System.exit(3);
        return;
    }
    mcfFile = mcfFile.getAbsoluteFile();

    File tempImages = new File(new File(System.getProperty("user.home")), ".mcf2pdf");
    if (cl.hasOption("w")) {
        tempImages = new File(cl.getOptionValue("w"));
        if (!tempImages.mkdirs() && !tempImages.isDirectory()) {
            printUsage(options,
                    new ParseException("Specified working dir does not exist and could not be created."));
            System.exit(3);
            return;
        }
    }

    int dpi = 150;
    if (cl.hasOption("r")) {
        try {
            dpi = Integer.valueOf(cl.getOptionValue("r")).intValue();
            if (dpi < 30 || dpi > 600)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options,
                    new ParseException("Parameter for option -r must be an integer between 30 and 600."));
        }
    }

    int maxPageNo = -1;
    if (cl.hasOption("n")) {
        try {
            maxPageNo = Integer.valueOf(cl.getOptionValue("n")).intValue();
            if (maxPageNo < 0)
                throw new IllegalArgumentException();
        } catch (Exception e) {
            printUsage(options, new ParseException("Parameter for option -n must be an integer >= 0."));
        }
    }

    boolean binding = true;
    if (cl.hasOption("b")) {
        binding = false;
    }

    OutputStream finalOut;
    if (cl.getArgs()[1].equals("-"))
        finalOut = System.out;
    else {
        try {
            finalOut = new FileOutputStream(cl.getArgs()[1]);
        } catch (IOException e) {
            printUsage(options, new ParseException("Output file could not be created."));
            System.exit(3);
            return;
        }
    }

    // configure logging, if no system property is present
    if (System.getProperty("log4j.configuration") == null) {
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("log4j.properties"));

        Logger.getRootLogger().setLevel(Level.INFO);
        if (cl.hasOption("q"))
            Logger.getRootLogger().setLevel(Level.ERROR);
        if (cl.hasOption("d"))
            Logger.getRootLogger().setLevel(Level.DEBUG);
    }

    // start conversion to XSL-FO
    // if -x is specified, this is the only thing we do
    OutputStream xslFoOut;
    if (cl.hasOption("x"))
        xslFoOut = finalOut;
    else
        xslFoOut = new ByteArrayOutputStream();

    Log log = LogFactory.getLog(Main.class);

    try {
        new Mcf2FoConverter(installDir, tempDir, tempImages).convert(mcfFile, xslFoOut, dpi, binding,
                maxPageNo);
        xslFoOut.flush();

        if (!cl.hasOption("x")) {
            // convert to PDF
            log.debug("Converting XSL-FO data to PDF");
            byte[] data = ((ByteArrayOutputStream) xslFoOut).toByteArray();
            PdfUtil.convertFO2PDF(new ByteArrayInputStream(data), finalOut, dpi);
            finalOut.flush();
        }
    } catch (Exception e) {
        log.error("An exception has occured", e);
        System.exit(1);
        return;
    } finally {
        if (finalOut instanceof FileOutputStream) {
            try {
                finalOut.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters./*from  w  w w.j  a  v a  2  s . c o m*/
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}