Tuesday, October 23, 2012

Learning Java the mysqlUtils() class

This evening as dinner was cooking, a mysqlUtils() class was added as a part of my continued learning. It did not take long to add these two methods, utilSetConnection() and utilDisConnect().  Existing code was cut / pasted into these two methods to speed development.

As expected, the utilSetConnection() sets the mysql connection. Internally, the database user name, password and database name are hard coded. The return from utilSetConnection is a Connection handle. Once defined in static void main () the Connection handle can be passed to other methods, such as the utilDisConnect(conn). 

The utilDisConnect() simply closes the Connection handle as conn.close(). That's it. Well other than the conn.close() has to be in a try / catch exception type processing.

Am I happy with the method names, well, not that much. The names are easily changeable to become more consistant. Also, the consideration to having the utilSetConnection() accept three arguments. These would be  three String datatypes, name, password and database name.

As other methods are coded, these would be an insert, delete, select methods, the Connection handle will be passed in along with a table name, particular mysql statement. In the case of the select * from statement, the data will need to be returned into a vector list or to a text file. Since that will require additional thinking, that is on hold for a bit. 

This is the disconnection method.

       public int utilDisConnect(Connection conn) {
           
        try{
           conn.close();
        }
        catch (Exception e){
           System.err.println ("Cannot disconnect to server");
           return (1);
        }
        System.out.println ("Disconnected");
        return (0);
    }

The test driver needs to include this statement: import com.mysql.jdbc.Connection;

Then to use:
        Connection lconn;
        lconn=(Connection) myu.utilSetConnection("frank");
        myu.utilDisConnect(lconn);

Netbeans took care of casting the (Connection) as shown above. Not sure if that is standard JAVA practice. Having to review lots of source code, these cast's could get out of hand.
    

Sunday, October 21, 2012

Continue Learning JAVA (a new approach)

From reading these blog entries, it's clear the trend is I am repeating myself quite often and not making any real progress. First there has not been a clear goal. Second, I find myself simply typing in or cut/paste from other sources. Sure these example programs are good in that it provides for repetition. With repetition, there  is some learning taking place. But not any depth. Third, there are specific programmatic weaknesses that I need to improve on. Understanding classes is one of these.

So what the go forward plan is stop using the example program method. Instead, (and I've already started) is to put together utility type classes, then call these from a test program. Figure lots of the basics will eventually coded into these utility classes and can be used over again. This will be helpful in that I'll have to code these only once and not get frustrated having to constantly find and re-code. An example is the dateUtils class.

As expected, this dateUtils class contains methods that return the time and date in various formats. These are most commonly used formats that I use are dd-MMM-yy,  hh:mm:ss  both combined, also POSIX time (number of seconds since UNIX epoch). One additional method accepts a hh:mm:ss and adds this to the current time. The return is the future time.

So in the test driver (uitest.java - the file with public static void main(String[] args) { ... }, I declare the following:


        dateUtils du = new dateUtils();
       
Calling each of the methods in the dateUtils file are done as follows:

        System.out.println(du.utilGetDateTime());
        System.out.println(du.utilDate());
        System.out.println(du.utilTime());
        System.out.println(du.utilEpoch());
        System.out.println(du.utilAddSecs(120));
        System.out.println(du.utilAddTime("12:34:56"));

Is this helpful? I think so. Of course there is a naming nomenclature irregularity as the class file is dateUtils.java and each method is called util(Something). It all works but a better naming convention may be in order. What has been helpful is all of the date / time formatting is done inside each of the methods so there was good experience gained.




Saturday, October 13, 2012

Continue learning JAVA (more)

The interest the other night was to have two threads running and doing the same work. One thread is called AntennaThread, the other ReceiverThread. With unlimited time and some real focus, this program would do more than simply System.out.println() the fact it is in a thread along with a date / time stamp. The threads are running in an endless loop with a Thread.sleep(1000) in between each call to do work. There was a similar example out there in Internet land, so a cut/paste with a few adaptions made quick work.

The code sample was coded to run a socket connection out to some url on a port number. Having that work in a thread is a fairly good idea. Provides good overall JAVA experience with treads. So for my needs, the socket code was hacked out and replaced with a call to run an AntennaThread and ReceiverThread. A util class was coded to support the normal set / get methods, specifically a set method to set a polling interval [util.setPolling()] (within the endless loop), funny I had forgot to instantiate the method so my util.getPolling() always returned 0. It polled really quick!

A util.getTime() was added which returns the date / time as 12-Oct-12 12:30:00. Pretty helpful when logging Antenna or Receiver events. The recent work with Calendar c = new Calendar() and Date d = new Date() along with the SimpleDateFormat was very helpful. Every JAVA programmer needs to be familiar with that.

Driving factor behind this interest comes from a typical satellite ground control system. There are antennas the need to be pointed, receivers that need to have frequencies set and a multitude of other devices that require various setting and configurations. It is best to have this automated. The existing system I work on uses complex multi-thread driven device handlers to do this work. Interest is, can this be done with JAVA in a similar high level design.

This file is called t1.java and is a Netbeans project so it can be called up and worked on as needed. Additional work is to bring the socket code back in and have it read some url out there and simply stream in the url text. Even better is to extend the thread into a jPanel / jInternalFrame with a jTextField as the display. Oh, it will need a button or two in order to stop the thread. That would be pretty cool.

Monday, October 8, 2012

Continue learning JAVA

And it has been quite awhile since the last post, and that was a post of Andrew Jackson State Park. So as the months passed by and things at work have got more challenging, it was time to dust off the JAVA books and continue with learning the language.

Quite awhile ago (years in fact) I picked up this Deitel & Deitel, JAVA How to Program Third Edition. At first I was planning on tossing this book for reasons of not being really that happy with it. After manually typing in some of the demo programs, my mind was changed. It dealt with the technology I am most interested in. This would be JTables, JSpinners and interfacing with MySql.

When I took a JAVA class at Ventura College years ago, I was able to pick up JAVA in a nutshell, Third Edition that covers JAVA 1.2 and 1.3. So that tells you how long ago that JAVA class was. As a reference manual for simple things like strings, arrays, lists, calendar, dates, this is not too bad for reference as long as the code is not that sophisticated.

Finally, after scrubbing Amazon dot com for a decent JAVA book (more modern) I settled on Cay Horstmann, Core JAVA, Volume II, Advance Features, Eight Edition. Well, in my hasty nature, his Volume I book did not even register so I clicked the buy button, next thing you know Volume II arrived. Overall, pretty happy with that book.

So, what kind of progress has been made. As far as the JAVA / MySql interface, I'm pretty happy and feel fairly competent in that area. The Deitel & Deitel book had some good examples that were typed in and ran seemingly right out of the box. Here is the cut/paste from the code that connects as user frank with the same password.


public class AddressBook extends JFrame {
    private ControlPanel controls;
    private ScrollingPanel scrollArea;
    private JTextArea output;
    private String url;
    private Connection connect;
    private JScrollPane textpane;

    ... cut ...


        String driver = "com.mysql.jdbc.Driver", 
        url = "jdbc:mysql://localhost:3306/address",
        user = "frank", 
        password = "frank";
                
        try{
        Class.forName(driver);
        connect = DriverManager.getConnection(url, user, password);
        output.append("Connection Successful");
        System.out.println("Connection Successful");
        }
        catch(ClassNotFoundException cn){
            output.append("Connection not successful\n"+cn.toString());
            System.out.println("Connection not Successful"+cn.toString());

        }
        catch(SQLException sq){
            output.append("Connection not successful\n"+sq.toString());
            System.out.println("Connection not Successful"+sq.toString());

        }
        catch(Exception ex){
            output.append("Connection not successful\n"+ex.toString());
            System.out.println("Connection not Successful"+ex.toString());

        }

This particular file that was typed in had several methods. The nerds would find this pretty straight forward. For me it was informative as the "Connection c" is the connection that is set in the code snippet above is passed in as an argument to each of the below methods. That is not a new concept for me, I'm used to coding functions, passing in all kinds of arguments, datatypes, opaque handles, etc. It is nice to know there is no difference with a JAVA Connection.


    public ControlPanel(Connection c, ScrollingPanel s, JTextArea t){
        setLayout(new GridLayout(1,5));
        
        findName = new JButton("Find");
        findName.addActionListener(new FindRecord(c,s,t));
        add(findName);
        
        addName = new JButton("Add");
        addName.addActionListener(new AddRecord(c,s,t));
        add(addName);
        
        updateName = new JButton("Update");
        updateName.addActionListener(new UpdateRecord(c,s,t));
        add(updateName);
        
        clear = new JButton("clear");
        clear.addActionListener(new ClearFields(s));
        add(clear);
        
        help = new JButton("help");
        help.addActionListener(new Help(t));
        add(help);
      
        System.out.println("ControlPanel:");

    }
}

So, in closing of this blog entry, the number one (only) take-away is the knowledge to connect to a database and the connection handle can be passed to other functions. My knowledge gap is to really understand Classes in JAVA. I have the concept down fairly well, since there are no structures, it is just kind of strange. With C++ no problem, got that understood (for not to sophisticated applications).