Woshiadai Dev Notebook

May 29, 2005

Using Jakarta Commons CLI

Filed under: Java

Several examples from Jakarta Commons Cookbook by Timothy M. O’Brien, O’Reilly, Nov 2004

Example 1: Parsing a Simple Command Line

import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLine;

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

    // Create a Parser
    CommandLineParser parser = new BasicParser( );
    Options options = new Options( );
    options.addOption(”h”, “help”, false, “Print this usage information”);
    options.addOption(”v”, “verbose”, false, “Print out VERBOSE information” );
    options.addOption(”f”, “file”, true, “File to save program output to”);

    // Parse the program arguments
    CommandLine commandLine = parser.parse( options, args );

    // Set the appropriate variables based on supplied options
    boolean verbose = false;
    String file = “”;

    if( commandLine.hasOption(’h') ) {
        System.out.println( “Help Message”)
        System.exit(0);
    }

    if( commandLine.hasOption(’v') ) {
        verbose = true;
    }

    if( commandLine.hasOption(’f') ) {
        file = commandLine.getOptionValue(’f');
    }
}

Example 2: Using OptionGroup

import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.CommandLine;

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

    // Create a Parser
    CommandLineParser parser = new BasicParser( );
    Options options = new Options( );
    options.addOption(”h”, “help”, false, “Print this usage information”);
    options.addOption(”v”, “verbose”, false, “Print out VERBOSE information” );

    OptionGroup optionGroup = new OptionGroup( );
    optionGroup.addOption( OptionBuilder.hasArg(true).create(’f') );
    optionGroup.addOption( OptionBuilder.hasArg(true).create(’m') );
    options.addOptionGroup( optionGroup );

    // Parse the program arguments
    CommandLine commandLine = parser.parse( options, args );

    // … do important stuff …
}

Example 3: Print Usage Info

import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;

public class SomeApp {
    private static final String USAGE = “[-h] [-v] [-f <file> | -m <email>]”;
    private static final String HEADER =
        “SomeApp - A fancy and expensive program, Copyright 2010 Blah.”;
    private static final String FOOTER =
        “For more instructions, see our website at: http://www.blah123.org”;

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

        // Create a Parser
        CommandLineParser parser = new BasicParser( );
        Options options = new Options( );
        options.addOption(”h”, “help”, false, “Print this usage
                                                                      information”);
        options.addOption(”v”, “verbose”, false, “Print out VERBOSE
                                                                         information” );

        OptionGroup optionGroup = new OptionGroup( );
        optionGroup.addOption( OptionBuilder.hasArg(true).withArgName(”file”)
                                            .withLongOpt(”file”).create(’f') );
        optionGroup.addOption( OptionBuilder.hasArg(true).withArgName(”email”)
                                            .withLongOpt(”email”).create(’m') );
        options.addOptionGroup( optionGroup );
           // Parse the program arguments
        try {
            CommandLine commandLine = parser.parse( options, args );

            if( commandLine.hasOption(’h') ) {
                printUsage( options );
                System.exit(0);
            }
   
               // … do important stuff …
        } catch( Exception e ) {
            System.out.println( “You provided bad program arguments!” );
            printUsage( options );
            System.exit(1);
        }
    }

    private static void printUsage(Options options) {
        HelpFormatter helpFormatter = new HelpFormatter( );
        helpFormatter.setWidth( 80 );
        helpFormatter.printHelp( USAGE, HEADER, options, FOOTER );
    }
}

May 3, 2005

Represent inner classes in UML

Filed under: Software Modeling

Problem: How to represent inner classes in the class diagram in UML?

I am doing TA for Software Methodology class this quarter and we use lots of UML diagrams. When grading students’ homework, I found this problem about representing inner classes in the class diagram.

After consulting the UML 1.5 spec and other resources, there are two ways.

Solution 1: (from Holub Associates: UML Reference Card)

 Nesting, Inner Class.. Identifies nesting (containment) relationships in all diagrams. In a class diagram: an “inner” class whose definition is nested within the another class definition. Typically puts the inner class in the name space of the outer class.

 

Solution 2: Use a package symbol (from UML 1.5 spec, chapter 3 UML Notations (PDF), 3.48.2)

“Note that nested notation is not the correct way to show a class declared within another class. Such a declared class is not a structural part of the enclosing class but merely has scope within the namespace of the enclosing class, which acts like a package toward the inner class. Such a namescope containment may be shown by placing a package symbol in the upper right corner of the class symbol. A tool can allow a user to click on the package symbol to open the set of elements declared within it. The “anchor notation” (a cross in a circle on the end of a line) may also be used on a line between two class boxes to show that the class with the anchor icon declares the class on the other end of the line.”

 

How can I create a new database foo in MySQL using JDBC

Filed under: Database

Problem: want to create a new database in MySQL using JDBC

Usually when people work with JDBC, they need a Connection object to the destination database, but since we need to create a new database, where to find an existing connection?

Setup: MySQL v4.1.9 + mysql-connector-java v3.1.6 + J2SE v1.4.2_06

Solution 1: Create a Connection to “mysql” admin database and use it to create the new database.

There are two preloaded databases when you install MySQL: mysql and test. mysql is the admin database that keeps metadata like access control information. We can just create a Connection object to mysql admin database and use it to create another new database.

Solution 2: Use Runtime.exec(command) to call mysql command line client.

Solution 3: Create a directory with the same name as the new database name in MySQL data directory, e.g., C:\Program Files\MySQL\MySQL Server 4.1\data. And MySQL server will “think” a new database is created. This method might have risk of corrupted metadata although I have tried this method before and no abnormal behavior was observed.

Does a database foo exist in MySQL?

Filed under: Database

Problem: I want to see if a database named “foo” exist in MySQL server

This should not be a tough problem at first sight. However, I googled the topic and did not find an official answer except several quick&dirty solutions. Please let me know if there are better and clean ways to do it right.

Setup: MySQL v4.1.9 + mysql-connector-java v3.1.6 + J2SE v1.4.2_06

Solution 1: Catch the exception for “unknown database %s” (I used this one finally).

If you create a new Connection to the URL that points to a non-existent database in MySQL, an SQLException is thrown with the message “unknown database %s” where %s is the database name. The exception has error code of 1049 (int) and SQL state of 42000 (String). Check MySQL error code list for the full list of possible errors for MySQL.

So, I just check the SQLException error code and/or SQL state to make sure this exception happens so that I know a database with the given name exist or not.

        boolean isExistRepos = true;
       
        try{
            connection = DriverManager.getConnection(reposURL, “root”, “rootpassword”);
        }catch (SQLException se){
            while(se != null && isExistRepos){
                String logMessage = “\n\n An SQL Error Occured: “
                                  + se.getMessage() + “\n\t”
                                  + “Error Code: ” + se.getErrorCode()
                                  + “\n\t” + “SQLState: “
                                  + se.getSQLState() + “\n”;
                System.err.println(logMessage);
               
                //repos does not exist and the connection cannot set up
                //MySQL error list (
http://dev.mysql.com/doc/mysql/en/error-handling.html)
                //#Error: 1049 SQLSTATE: 42000 (ER_BAD_DB_ERROR)
                //Message: Unknown database ‘%s’
                if((se.getErrorCode() == 1049) && (se.getSQLState().equalsIgnoreCase(”42000″)))
                    isExistRepos = false;
                se = se.getNextException();
            }
        }

Solution 2: Call mysql command line client using Runtime class.

I did not try it, but here is the general idea. MySQL comes with a command line client program called “mysql” where users can interact with the database server. You can type in “show databases” and a list of existing databases will be presented.

In Java, we can use Runtime.getRuntime().exec(“mysql -u root -p rootpassword”) to get a handle on a Process object, then we can use OutputStream and InputStream to input “show databases” and parse the output to see if the database foo exist in the list of databases.

Solution 3: Check if the directory corresponding to the database exists in MySQL data directory.

I just found that for each database, there exist a directory with the same name in MySQL data directory, e.g. C:\Program Files\MySQL\MySQL Server 4.1\data for my case. So, you can juse check if the directory foo exist in that directory to tell if the corresponding database exist or not. I am not sure about MySQL internals, so this solution is not stable and portable.

May 2, 2005

Firefox: 50000000

Filed under: Database

Firefox celebrates 50 million downloadsFirefox is celebrating 50 million downloads now

I have been using it for a long time now, it is quite neat and fast. You don’t have to worry about IE security holes and non-standard M$ tags anymore.

BTW, this is a test post using BlogJet. The only thing I found annoying with this desktop blog publishing tool is that it has poor support for encoding, e.g. I cannot post Simplified Chinese contents






















Get free blog up and running in minutes with Blogsome
Theme designed by Ben de Groot