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:Delete.java

public static void main(String[] args) {
    String fileName = "file.txt";
    // A File object to represent the filename
    File f = new File(fileName);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
        throw new IllegalArgumentException("Delete: no such file or directory: " + fileName);

    if (!f.canWrite())
        throw new IllegalArgumentException("Delete: write protected: " + fileName);

    // If it is a directory, make sure it is empty
    if (f.isDirectory()) {
        String[] files = f.list();
        if (files.length > 0)
            throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
    }//from  w ww.  ja v a  2  s .c  om

    // Attempt to delete it
    boolean success = f.delete();

    if (!success)
        throw new IllegalArgumentException("Delete: deletion failed");
}

From source file:UDPReceive.java

public static void main(String args[]) {
    try {/*  w w w . ja  v a 2  s .  c om*/
        if (args.length != 1)
            throw new IllegalArgumentException("Wrong number of args");

        // Get the port from the command line
        int port = Integer.parseInt(args[0]);

        // Create a socket to listen on the port.
        DatagramSocket dsocket = new DatagramSocket(port);

        // Create a buffer to read datagrams into. If anyone sends us a
        // packet containing more than will fit into this buffer, the
        // excess will simply be discarded!
        byte[] buffer = new byte[2048];

        // Create a packet to receive data into the buffer
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

        // Now loop forever, waiting to receive packets and printing them.
        for (;;) {
            // Wait to receive a datagram
            dsocket.receive(packet);

            // Decode the bytes of the packet to characters, using the
            // UTF-8 encoding, and then display those characters.
            String msg = new String(buffer, 0, packet.getLength(), "UTF-8");
            System.out.println(packet.getAddress().getHostName() + ": " + msg);

            // Reset the length of the packet before reusing it.
            // Prior to Java 1.1, we'd just create a new packet each time.
            packet.setLength(buffer.length);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:de.rwhq.btree.run.PrintTree.java

public static void main(final String[] args) throws IOException {

    final File f = new File("/tmp/indexha");
    if (!f.exists())
        throw new IllegalArgumentException("File does not exist");

    final ResourceManager resourceManager = new ResourceManagerBuilder().file(f).build();
    final BTree<Integer, String> tree = BTree.create(resourceManager, IntegerSerializer.INSTANCE,
            FixedStringSerializer.INSTANCE_1000, IntegerComparator.INSTANCE);

    final Iterator<String> it = tree.getIterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }/*from  w  w  w  . ja v a 2s  .  co  m*/
}

From source file:UDPSend.java

public static void main(String args[]) {
    try {/*  w  w w  .j  a  v a2 s.c  om*/
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {/*from  ww  w  .j  a  v  a 2s . c  o  m*/
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:com.graphhopper.tools.Bzip2.java

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        throw new IllegalArgumentException("You need to specify the bz2 file!");
    }/*  ww  w  .j av  a 2s  .c  o m*/

    String fromFile = args[0];
    if (!fromFile.endsWith(".bz2")) {
        throw new IllegalArgumentException("You need to specify a bz2 file! But was:" + fromFile);
    }
    String toFile = Helper.pruneFileEnd(fromFile);

    FileInputStream in = new FileInputStream(fromFile);
    FileOutputStream out = new FileOutputStream(toFile);
    BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);
    try {
        final byte[] buffer = new byte[1024 * 8];
        int n = 0;
        while (-1 != (n = bzIn.read(buffer))) {
            out.write(buffer, 0, n);
        }
    } finally {
        out.close();
        bzIn.close();
    }
}

From source file:de.tudarmstadt.ukp.argumentation.cleaning.DataCleaner.java

public static void main(String[] args) throws Exception {
    // default path
    File dataDir = new File("data/");

    // or from parameters
    if (args.length > 0) {
        dataDir = new File(args[0]);
    }/*from   ww  w .  j ava  2  s  .  c om*/

    Collection<File> files = FileUtils.listFiles(dataDir, new String[] { "txt" }, true);

    if (files.isEmpty()) {
        throw new IllegalArgumentException("No .txt files found in " + dataDir);
    }

    for (File file : files) {
        String text = FileUtils.readFileToString(file, "utf-8");

        // cleaning
        String normalized = TextCleaningUtils.normalize(text);

        // and write back
        FileUtils.writeStringToFile(file, normalized, "utf-8");
    }
}

From source file:org.jboss.narayana.quickstart.spring.QuickstartApplication.java

public static void main(String[] args) throws Exception {
    if (args.length != 1 && args.length != 2) {
        throw new IllegalArgumentException("Invalid arguments provided. See README.md for usage examples");
    } else if (args.length == 1 && !args[0].toUpperCase().equals(CompleteAction.RECOVERY.name())) {
        throw new IllegalArgumentException("Invalid arguments provided. See README.md for usage examples");
    }/*from w w w  .  j  a v a  2 s. c  o m*/

    ApplicationContext context = SpringApplication.run(QuickstartApplication.class, args);
    QuickstartService quickstartService = context.getBean(QuickstartService.class);

    switch (CompleteAction.valueOf(args[0].toUpperCase())) {
    case COMMIT:
        quickstartService.demonstrateCommit(args[1]);
        break;
    case ROLLBACK:
        quickstartService.demonstrateRollback(args[1]);
        break;
    case CRASH:
        quickstartService.demonstrateCrash(args[1]);
        break;
    case RECOVERY:
        quickstartService.demonstrateRecovery();
    }

    ((Closeable) context).close();
}

From source file:com.xpfriend.fixture.runner.example.ExampleJob.java

/**
 *  TEST_FB ???/*w ww.  j  ava 2s  . c  o m*/
 * @param args 1:?ID?2:??NAME?
 */
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        throw new IllegalArgumentException("args.length == " + args.length);
    }
    int id = Integer.parseInt(args[0]);
    String name = args[1];

    Connection connection = getConnection();
    try {
        updateDatabase(id, name, connection);
        connection.commit();
    } finally {
        connection.close();
    }
}

From source file:org.envirocar.harvest.TrackHarvesterExecution.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    String consumerUrl = null;//  www.ja va 2s .  co  m
    if (args != null && args.length > 0) {
        consumerUrl = args[0].trim();
    } else {
        throw new IllegalArgumentException("consumerUrl needs to be provided");
    }

    ProgressListener l = new ProgressListener() {

        @Override
        public void onProgressUpdate(float progressPercent) {
            System.out.println(String.format("%f percent finished", progressPercent));
        }

    };
    new TrackHarvester(consumerUrl, l).harvestTracks();
}