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(Throwable cause) 

Source Link

Document

Constructs a new exception with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.tyro.oss.pact.spring4.pact.consumer.PactPublisher.java

public static void main(String[] args) throws Exception {
    String consumer = args[0];/*  w  ww  .j  a  va 2  s  .c  o  m*/
    String version = args[1];
    String pactFileRoot = args[2];

    if (args.length != 3) {
        throw new IllegalArgumentException(
                "publish-pact profile in the pom.xml should contain the following arguments <CONSUMER> <VERSION> <PACT-FILE-LOCATION>");
    }

    PactBrokerUrlSource pactBrokerUrlSource = new PactBrokerUrlSource();
    publishPactFiles(consumer, version, pactFileRoot, pactBrokerUrlSource.getPactUrlForPublish());
}

From source file:licenceexecuter.LicenceExecuter.java

/**
 * @param args the command line arguments
 * @throws java.text.ParseException/*from   ww  w. j  av a2 s  .com*/
 */
public static void main(String[] args) throws Throwable {
    LicenceExecuter licenceExecuter = new LicenceExecuter();
    licenceExecuter.initProperties();

    if (args != null && args.length >= 5) {
        System.out.println(Base64.encodeBase64String(args[4].getBytes()));
        System.out.println(licenceExecuter.properties.getProperty("generateKey"));
        if (Base64.encodeBase64String(args[4].getBytes())
                .equals(licenceExecuter.properties.getProperty("generateKey"))) {
            System.out.println(ControllerKey.encrypt(
                    new ObKeyExecuter().toObject(args[0] + "|" + args[1] + "|" + args[2] + "|" + args[3])));
        } else {
            throw new IllegalArgumentException("InvalidPassword");
        }
        return;
    }
    try {
        licenceExecuter.run();
    } catch (Throwable ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "PROBLEMAS NA EXECUO", "ATENO", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:fr.gael.dhus.database.util.RestoreDatabase.java

/**
 * @param args/*from   w w  w.  ja  v a 2s.c om*/
 * @throws IllegalAccessException 
 * @throws IOException 
 */
public static void main(String[] args) throws IllegalAccessException, IOException {
    if (args.length != 2) {
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Wrong arguments <source path> <destination path>.");
    }

    File dump = new File(args[0]);
    File db = new File(args[1]);

    logger.info("Restoring " + dump.getPath() + " into " + db.getPath() + ".");

    if (!db.exists())
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Input database path not found (\"" + db.getPath() + "\").");

    if (!dump.exists())
        throw new IllegalArgumentException(RestoreDatabase.class.getCanonicalName()
                + ": Input database dump path not found (\"" + db.getPath() + "\").");

    FileUtils.deleteDirectory(db);
    FileUtils.copyDirectory(dump, db);

    logger.info("Dump properly restored, please restart system now.");
}

From source file:client.tools.PutAuthShell.java

/**
 * Prompts for a user name, password, and the current password (optional).
 * // w w  w.j a v  a2s .  co  m
 * @param args
 *            the path to the configuration file.
 */
public static void main(String[] args) {
    String configPath;

    if (args.length != 1) {
        throw new IllegalArgumentException("Path to configuration file must be present!");
    }

    configPath = args[0];

    try {
        Client client = new Client(configPath, ClientExecutorType.PUT_AUTH, null);
        client.start();
        client.join();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
            | IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java

public static void main(final String[] args) throws Exception {
    // 1. check input directory
    final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports");
    if (!reportdir.isDirectory()) {
        throw new IllegalArgumentException("Expected directory, got " + args[0]);
    }/*  w  ww  .java2 s . co  m*/

    // 2. read test data from surefire output
    final File[] xmlReports = reportdir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {
            return name.endsWith("-output.txt");
        }
    });

    final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>();

    for (File xmlReport : xmlReports) {
        final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport));
        try {
            while (reportReader.ready()) {
                String line = reportReader.readLine();
                final String[] parts = line.substring(0, line.indexOf(':')).split("\\.");

                final String testClass = parts[0];
                if (!testData.containsKey(testClass)) {
                    testData.put(testClass, new TreeMap<String, Double>());
                }

                line = reportReader.readLine();

                testData.get(testClass).put(parts[1],
                        Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('['))));
            }
        } finally {
            IOUtils.closeQuietly(reportReader);
        }
    }

    // 3. build XSLX output (from template)
    final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src"
            + File.separator + "test" + File.separator + "resources" + File.separator + XLS));

    for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) {
        final Sheet sheet = workbook.getSheet(entry.getKey());

        int rows = 0;

        for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) {
            final Row row = sheet.createRow(rows++);

            Cell cell = row.createCell(0);
            cell.setCellValue(subentry.getKey());

            cell = row.createCell(1);
            cell.setCellValue(subentry.getValue());
        }
    }

    final FileOutputStream out = new FileOutputStream(
            args[0] + File.separator + "target" + File.separator + XLS);
    try {
        workbook.write(out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:client.tools.PutFolderShell.java

/**
 * Prompts the user for the folder name and permissions. The PUT folder
 * request is finally sent to server which is started here.
 * /*w ww.  j ava 2 s.c om*/
 * @param args
 *            the path to the configuration file.
 */
public static void main(String[] args) {
    String configPath;

    if (args.length != 1) {
        throw new IllegalArgumentException("Path to configuration file must be present!");
    }

    configPath = args[0];

    try {
        Client client = new Client(configPath, ClientExecutorType.PUT_FOLDER, null);
        client.start();
        client.join();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
            | IOException | ParseException e) {
        e.printStackTrace();
    }
}

From source file:net.darkmist.alib.spring.Main.java

public static void main(String[] args) {
    FileSystemXmlApplicationContext ctx;
    Runnable mb;//from   w w  w .  jav a 2  s . co m
    boolean doExit = false;
    int exitCode = 0;

    if (args.length < 1)
        usage();
    ctx = new FileSystemXmlApplicationContext(args[0]);
    mb = (Runnable) ctx.getBean(MAIN_BEAN);
    if (mb instanceof MainBean)
        ((MainBean) mb).setArgs(args, 1, args.length - 1);
    else if (args.length > 1)
        throw new IllegalArgumentException("main bean does not take arguments");
    mb.run();
    if (mb instanceof MainBean) {
        exitCode = ((MainBean) mb).getExitCode();
        doExit = true;
    }
    mb = null;
    ctx.close();
    if (doExit)
        System.exit(exitCode);
}

From source file:siia.jms.MessageListenerContainerDemo.java

public static void main(String[] args) {
    // establish common resources
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    Destination queue = new ActiveMQQueue("siia.queue");
    // setup and start listener container
    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setDestination(queue);/*from  w  w w. ja  va2  s  . c o m*/
    container.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (!(message instanceof TextMessage)) {
                    throw new IllegalArgumentException("expected TextMessage");
                }
                System.out.println("received: " + ((TextMessage) message).getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }
    });
    container.afterPropertiesSet();
    container.start();
    // send Message
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.setDefaultDestination(queue);
    jmsTemplate.convertAndSend("Hello World");
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);/* ww w .  jav  a 2s  . com*/

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:ExecuteSQL.java

public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {// www .  ja v a  2s  .  co  m
        String driver = null, url = null, user = "", password = "";

        // Parse all the command-line arguments
        for (int n = 0; n < args.length; n++) {
            if (args[n].equals("-d"))
                driver = args[++n];
            else if (args[n].equals("-u"))
                user = args[++n];
            else if (args[n].equals("-p"))
                password = args[++n];
            else if (url == null)
                url = args[n];
            else
                throw new IllegalArgumentException("Unknown argument.");
        }

        // The only required argument is the database URL.
        if (url == null)
            throw new IllegalArgumentException("No database specified");

        // If the user specified the classname for the DB driver, load
        // that class dynamically. This gives the driver the opportunity
        // to register itself with the DriverManager.
        if (driver != null)
            Class.forName(driver);

        // Now open a connection the specified database, using the
        // user-specified username and password, if any. The driver
        // manager will try all of the DB drivers it knows about to try to
        // parse the URL and connect to the DB server.
        conn = DriverManager.getConnection(url, user, password);

        // Now create the statement object we'll use to talk to the DB
        Statement s = conn.createStatement();

        // Get a stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Loop forever, reading the user's queries and executing them
        while (true) {
            System.out.print("sql> "); // prompt the user
            System.out.flush(); // make the prompt appear now.
            String sql = in.readLine(); // get a line of input from user

            // Quit when the user types "quit".
            if ((sql == null) || sql.equals("quit"))
                break;

            // Ignore blank lines
            if (sql.length() == 0)
                continue;

            // Now, execute the user's line of SQL and display results.
            try {
                // We don't know if this is a query or some kind of
                // update, so we use execute() instead of executeQuery()
                // or executeUpdate() If the return value is true, it was
                // a query, else an update.
                boolean status = s.execute(sql);

                // Some complex SQL queries can return more than one set
                // of results, so loop until there are no more results
                do {
                    if (status) { // it was a query and returns a ResultSet
                        ResultSet rs = s.getResultSet(); // Get results
                        printResultsTable(rs, System.out); // Display them
                    } else {
                        // If the SQL command that was executed was some
                        // kind of update rather than a query, then it
                        // doesn't return a ResultSet. Instead, we just
                        // print the number of rows that were affected.
                        int numUpdates = s.getUpdateCount();
                        System.out.println("Ok. " + numUpdates + " rows affected.");
                    }

                    // Now go see if there are even more results, and
                    // continue the results display loop if there are.
                    status = s.getMoreResults();
                } while (status || s.getUpdateCount() != -1);
            }
            // If a SQLException is thrown, display an error message.
            // Note that SQLExceptions can have a general message and a
            // DB-specific message returned by getSQLState()
            catch (SQLException e) {
                System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
            }
            // Each time through this loop, check to see if there were any
            // warnings. Note that there can be a whole chain of warnings.
            finally { // print out any warnings that occurred
                SQLWarning w;
                for (w = conn.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
            }
        }
    }
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println("SQL State: " + ((SQLException) e).getSQLState());
        System.err.println(
                "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>");
    }

    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}