My blog has moved! Redirecting...

You should be automatically redirected. If not, visit http://mindsiview.wordpress.com/ and update your bookmarks.

Wednesday, December 08, 2004

The Java Communications API Revisited...

Several months ago I wrote an article for the Borland Developer Network site (http://bdn.borland.com) on the Java Communications API. Since that time I've received numerous emails about the article. To those who've emailed me, thanks for your kind words.

I've compiled the following FAQ based on some of your questions and my responses. If you're working with the Java Communications API, you might find this useful.

Question 1:
If I'm trying to send a character through serial port communication to another computer how can I verify that the signal was sent?

Answer:
I used an old WYSE serial terminal and a null modem cable to test the code. Then I set both the serial ports to COM2 (the serial port on my laptop). I also used a separate communications port monitor of the type used for network troubleshooting.

If you have access to another PC with a serial port, you should be able to hook it to the one you're running the program on (via some serial cables, a null modem adapter, and maybe a gender bender). On the second PC fire up a communications program like HyperTerm or Procomm and set it to communicate on the serial port you're connected to. This will allow you to send and receive data between the PCs.

Question 2:
Is your code correct?

Answer:
The code runs correctly using J2SE 1.4 on a Windows 2000/XP. I've also run it on Red Hat Linux 7.2 using the RXTX version of the comm.jar (there's a link to RXTX in the article).

If you compile my example, execute it, and it doesn't give you any exceptions, it should be working properly. You'll get exceptions if the program can't get handles for the COMn devices or if the comm.jar, win32comm.dll, or javax.comm.properties files can't be found.

Question 3:
is possible to send and receive at commands using java comm?

Answer:
Yes.

Question 4:
Does Java send any additional characters with its strings to the serial port?

Answer:
Java does not send additional characters down the port (I know this because I've tested it with a port monitor). It sends what your program sends.

Question 5:
Does Java send the strings in ASCII values to the port?

Answer:
As far as data encoding is concerned, unless you specify something different, you'll be sending data in the default encoding of your hardware.

Question 6:
I am trying to send serial data using a usb to serial converter since my laptop does not have a serial port. Problem is, in Windows device manager, the usb to serial converter shows up as "Prolific USB-to-Serial Comm Port (COM4)", but running ComControl.java returns:

COM4 null
msg1 - javax.comm.NoSuchPortException

Any suggestions?

Answer:
I tried the usb to serial port converter that I have (it is a Targus PA090) and it worked properly. On the PA090, the serial port cannot run faster than 9600 baud. You may want to check the baud settings on yours. You may also want to experiment with the stop bits, parity, etc. The PA090 also has a serial port reset button. If your converter has one, try resetting it. Check for the latest drivers also.

Question 7:
I've tried running your code and I'm getting a "javax.comm.NoSuchPortException" message. Any clues?

Answer:
First, check your PC to see if the COMn ports you are using have been defined. Next, check the location of win32com.dll and javax.comm.properties. They are required for the comm API to work properly in a Windows environment. Usually the javax.comm.properites file is the culprit. It needs to be located in the classpath of your java program.

Wednesday, September 22, 2004

More Than Java Development

Sorry I haven't posted in a while. I have been busy with a Great Plains implementation. Follow the link for an article about Great Plains that mentions my company. When It Rains...

More on my thoughts about Microsoft Great Plains and VBA later.

Sunday, August 01, 2004

Java Quick Tip of the Day: Reading non-Http Input Into a Servlet

Have you ever wanted to read something other than the results of a get or a post into a servlet? It's not as difficult as you think. It's really just a matter of using the getInputStream() method of the HttpServletRequest object.

Let's take a look at the following example:

public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {
 doGet(request, response);
 }
 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {
 BufferedInputStream is = 
   new BufferedInputStream(request.getInputStream());
 InputStreamReader isr = new InputStreamReader(is);
 int character;
 StringBuffer process = new StringBuffer();
 while((character = isr.read()) != -1)
 { process.append((char)character);
  }
 System.out.println(process);
 }
catch...

Looking at the code, notice that the first thing we're doing is calling the doGet() method from the doPost() method. We do this as a simple way to redirect all incoming data to the same code. We then create a BufferedInputStream object is from the request.getInputStream() method. From is we've created an InputStreamReader object isr in order to read the inputstream. Next we create a StringBuffer object process and fill it with the characters we read from the inputstream...for those of you who've used inputstreams this code should look very familar. Finally we do something with process.

Why would you ever want to do this? One example of of using this technique is when you want to turn a servlet into a webservice. I'm currently working on a how-to article on this subject. Look for it shortly.

Tuesday, July 13, 2004

IT Strategy and IT Spending

First, let me apologize in advance for spelling mistakes I make this morning. I am writing this from my BlackBerry. I'm watching an early morning storm out over the Gulf of Mexico...glad that I'm not on a boat somewhere in the middle of it. But I digress...

In the 80's and 90's no one would dare create an IT strategy without including double digit percentage increases in IT spending. While this approach may have led to some pretty nice systems, it did little to help companies' bottom lines...more likely increased IT spending hurt bottom line profits.

Today we have to take a different approach. I like to look at it as a stewardship approach. We have to carefully consider how we utilize our most scare resource-cash. We in IT have to manage it and decide when and how to best deploy it.

Our corporate executives and boards want better margins...translation: less IT spending on needless upgrades and infrastructure and a closer look at IT spending as it relates to profits.

Fortunately for us (IT execs) the industry trend is lower overall technology costs. But, lower costs are not enough. We must also deal with vendors who want to sell us uneccesary products and services. And, in some cases, we have to deal with execs who want the latest in technology regardless of the cost.

My advice: stand firm. Don't deploy technology for technology's sake. Renogotiate existing contracts. Become vendor agnostic. And, don't let vendors and well meaning execs drive YOUR IT costs.

Monday, June 28, 2004

Java Quick Tip of the Day: Using HashMaps

The next time you have to create a simple lookup table in Java, try using a HashMap. HashMap is part of the java.util package. It is an interface for storing objects as key-value pairs. HashMap is typically used for storing object relationships.

Take a look at the following example:

import java.util.*;

public class HashTest {
  static HashMap qbLookup;
  public static void main(String[] args) {
  qbLookup = new HashMap();

  qbLookup.put("Raiders", "Rich Gannon");
  qbLookup.put("Titans", "Steve McNair");
  qbLookup.put("Steelers", "Tommy Maddox");
  qbLookup.put("Colts", "Peyton Manning");

  if(args.length > 0) {
if (qbLookup.get(args[0])!=null) {
System.out.println("The starting quarterback for the "
+ args[0] + " is " + qbLookup.get(args[0]));
} else {
System.out.println("NFL Team not found, try again");
}
} else {
System.out.println("Please enter a valid NFL Team");
} } }

As you can see from the code, I created a HashMap called qbLookup. Using the put() method, I created some objects representing NFL teams and the starting quarterbacks. Although I used String objects in this example, you can use whatever kind of object you need to store and retrieve later. For example, I could've created an object that represented the entire roster of each team instead of a String object representing the quarterback.

Next, you'll see that I'm checking the arguments passed to HashTest's main() method. If I find an argument, I pass it to the get() method of the HashMap object qbLookup in order to retrieve the related object. I check to see if the get() method has returned a value and print out the appropriate message.

When you compile this code and execute it with the command java HashTest Titans you get:

The starting quarterback for the Titans is Steve McNair

I hope this example helps you see ways that you can utilize HashMaps in your own programs.

Tuesday, June 22, 2004

Monday, June 21, 2004

Do You Need a Change?

When do you know that it is time to either change your attitude or leave your company? That is a hard question to answer, but there are warning signs. Ask yourself the following:

  • Do you hate coming to work each day?
  • Do you find excuses to be out of the office?
  • Do others consider you hostile and defensive?
  • Are you always upset?
  • Have you had these feelings for more than 6 months?

If you've answered yes to 4 out of 5 of these questions, you got a problem. Do something about it. It may be that you are burned out. In the IT field it happens a lot. We’ve all been there. Big projects, unreasonable deadlines and bosses, stress at home, and too much to do with too few resources are just some of the causes of IT burnout. Sometimes you have to take some time off and get your life back in order.

When I experience burnout, I pull back a little and reassess my life. I spend more time with my family and less time at work. I stop worrying about the areas that are out of my control and focus on the ones I can control. I delegate so that others can “feel my pain” and to lighten my load a little. Also, I pray a lot.

What if you tried those ideas…and a few others…and nothing happened? Well my friend, you’re not burned out, you are checked out. What do I mean by being checked out? Checked out means that, like Elvis, you’ve left the building---only you don’t know it yet. If you’re in this situation, find a new situation. Start looking. I promise you, it’s not going to get better till you do. If you stay at your current job more money won’t help, new bosses won’t help, new responsibilities or that raise they’re promising you if you stay won’t help either. Get off your duff, brush off your resume, and find a new job. Until you do, you will continue to answer yes to the above questions.

Thursday, June 17, 2004

Is Information Technology Becoming a Commodity?

I've been reading Does IT Matter? by Nicholas Carr. He argues that IT is going to go the way of railroads, electricity, etc. Meaning that information technology will become a commodity...a cost of doing business. In my opinion a lot of factors have to fall into place for this situation to occur.

First, availability of broadband Internet services has to be cheap, reliable, and less prone to hacker attacks. I think we're a long way toward this end. Look at Internet service today versus 5 years ago. When's the last time your ISP was down compared to then? ISPs, especially commercial providers, are extremely reliable today. Additionally their costs are reasonable...though I think that broadband service could come down a bit. One of the core problems with Internet service is hacker vulnerability. From an Internet connected server standpoint we're still living in the Wild West. As server vulnerabilities are reduced and overall service improves, the Internet component of the transition of IT from strategic player to commodity will be solved.

Aside from improvements to Internet services, companies have to be willing to adopt standard ways of transferring information to each other. EDI has been around for years, but ask any EDI support person and they will tell you that each trading partner has a unique setup. XML offers hope, but it too has the same issues to deal with. A recent ComputerWorld article EDI Alive and Well After All These Years makes the point that companies aren't quickly moving away from EDI to XML. Instead, they are moving away from Value Added Networks (VANs) to FTP transfers and Internet standards for delivering EDI documents.

What makes electricity so attractive to businesses (and individuals) is that once it reaches the building, the breaker panel(s) control and parcel out the appropriate voltages. Then it becomes a matter of making sure that you have the right piece of equipment, appliance, etc. plugged into the right plug (with the right plug configuration of course). The same needs to happen with information transfers before they can be considered a commodity.

Hardware and software have to become more simplified for the end user. An example of this would be a phone. I daresay in developed countries almost everyone over the age of 3 knows how to use a phone. Whether it's a cell phone or a land-line, the average person can turn it on, dial a number, and have a conversation without much problem. Computers are not quite that simple. If you're in the IT field, how many times have you been called on to help a friend or family member with a PC problem? How often have executives in your company tried the latest high-tech gadget only to find it complex and confusing? Let's face it, interactions with computer hardware and software must improve before information technology becomes a commodity.

Let's talk about software for a moment. It can be argued that as more companies move away from in-house developed packages to so called "off-the-shelf" packages that they will become more standardized with other companies. On the surface it appears to be a valid point. In reality, today's ERP, finanical, WMS packages, whatever, have a tremendous amount of conifgurability for your organization. This means that although you and nearest competitor are running the same package, both of your implemenations can vary significantly depending on the customizations. The point, individual software implementations are a long way from being standard.

So back to the original question, is Informatiion Technology becoming a commodity? I think that parts of it such as Internet access are. But, I also think that we have a long, long way to go before IT becomes a commodity.

Tuesday, June 15, 2004

Java Quick Tip of the Day: Getting the Date in YYYYMMDD Format

There are times when you need to return a date as string in YYYYMMDD format. Here's a simple way to do it:
    import java.text.*;
    ...
    ...
    ...
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    java.util.Date date = java.util.Calendar.getInstance().getTime();
    System.out.println(sf.format(date));

Java Quick Tip of the Day: Selecting Current TimeStamp for DB2

There are times when you may want multiple programs to retrieve a current timestamp from a central location. This can be accomplished by selecting the timestamp from a database server. To return the current timestamp from DB2 execute the following query:

     ResultSet rs;
     rs = stmt.executeQuery("select distinct(current timestamp)
          from sysibm.sysdummy1");
     rs.next();
     java.util.Date today = rs.getTimestamp(1);

Notice that I used a table called "sysibm.sysdummy1". Sysdummy1 is a special purpose table for uses such as this one. Additionally, you can use any db2 table that you have access to.

Friday, June 11, 2004

Java Quick Tip Of the Day: Character Encoding and ResultSets

We recently ran into a problem where a Java program running on our IBM enterprise server was unable to properly display strings returned from a Microsoft SQL Server table. The problem was due to character encoding. Because of the SQL Server table definition, the JDBC driver was not translating the ASCII values in the string returned from a ResultSet.getString() method to EBCDIC. The solution. Explicitly define the encoding by casting the returned value of a ResultSet.getBytes() into a String (see below).
String outStr =  new String(rs.getBytes(1),"ISO-8859-1");

My Company's IT Direction

The following link is one of my on-line postings in response to an article on open source development: Open Source

RMI: Distributed Java For the Rest of Us

Follow the link to read my RMI article on Borland's Developer Network site. RMI Article

Running Java Applications as a Windows Service

Introduction

Have you ever needed to run a Java class unattended on a Windows server? There are various ways to accomplish this task. By far, the best alternative is to run your Java class as a Windows service. One of the easiest tools I’ve found for turning classes into services is the open source Java Service Wrapper project from Tanukisoftware.org (http://wrapper.tanukisoftware.org/doc/english/index.html). According to their website, the Java Service Wrapper is an application which has evolved out of a desire to solve a number of problems common to many Java applications:

  • Run as a Windows Service or Unix Daemon
  • Application Reliability
  • Standard, Out of the Box Scripting
  • On Demand Restarts
  • Flexible Configuration
  • Ease Application Installations
  • Logging

In this article, we’ll focus on the first bullet point.

Note: There are three ways you can use the Java Service Wrapper. In this article we will use the WrapperSimpleApp class to launch our application.

First Things First

Following the link above, download and install the latest version the Java Service Wrapper (for Windows users it comes in a zip file). For this example, I used version 3.0.5. I extracted the file to my C: drive and it created the following directory C:/wrapper_win32_3.0.5. Since I can’t know where you are placing the files, for the rest of the article we’ll refer to the wrapper home folder as %wrapper home%.

Looking at the tree structure, you’ll see several folders including:

  • bin: contains the batch files needed to run the Java Service Wrapper and the Wrapper.exe file.
  • conf: contains the wrapper.conf file.
  • lib: contains the wrapper.dll file, wrapper.jar, and wrappertest.jar.
  • doc: contains the documentation

The bin Folder

The bin folder contains several files with a .bat.in extension. For this example, you and I are only concerned with the App.bat.in file, the InstallApp-NT.bat.in file, and the UninstallApp-NT.bat.in file. These files need to be renamed to a .bat extension.
Once you’ve done that, run the App.bat from a command line. You should see the following results:

Now that we know the test works, let’s make one of our own Java classes work.

Creating a Windows Service

The first thing we need to do is choose a Java class to turn into a service. In this example, we’re going to use a class called MultipleSocket server. The code for this class can be downloaded from CodeCentral by clicking here. Once you’ve downloaded the code, find the bdn.jar file and move it to the [wrapper folder]/bin directory.

On my PC I set up JAVA_HOME and CLASSPATH environmental variables as well as provided a path to the %JAVA_HOME%/bin folder to make it easier to run java classes from the command line. I’m going to assume that you’ve done the same thing. If you haven’t, then you’ll need to provide the full path to the java.exe file in the next examples.

Let’s test the bdn.jar file to make sure that everything’s ok. At a command prompt, type:


java -cp bdn.jar bdn.MultipleSocketServer

After you hit the enter key you should see a screen similar to this:

Note: Use Ctrl-C to exit the program.

The next thing we need to do is to modify the wrapper.conf file. As mentioned earlier, this file can be found in the %wrapper home%/conf directory. In this file we are going to make the following changes:

change:


wrapper.java.mainclass=org.tanukisoftware.wrapper.test.Main

to


wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp

add:


wrapper.java.classpath.3=bdn.jar

below:


wrapper.java.classpath.1=../lib/wrapper.jar
wrapper.java.classpath.2=../lib/wrappertest.jar

change:


#wrapper.app.parameter.1=

to


wrapper.app.parameter.1=bdn.MultipleSocketServer

change:


  wrapper.ntservice.name=@app.name@
  wrapper.ntservice.displayname=@app.long.name@
  wrapper.ntservice.description=@app.description@
 

to:


  wrapper.ntservice.name=MultipleSocketserver
  wrapper.ntservice.displayname=MultipleSocketServer
  wrapper.ntservice.description=MultipleSocketServer Test
  

And save the file.

Now let’s test our creation. At the command prompt run:


%wrapper home%/bin/App

You should see the following:

Now that we’ve tested our class, let’s turn it into a fullfledged service. At the command prompt run:


%wrapper home%/bin/InstallApp-NT.bat

You should see the following:

Let’s make sure that Windows recognizes the MultipleSocketServer class as a Service. Click on the “services” icon, found in the administrative tools option of the control panel. You should see a screen similar to this:

Notice that the MultipleSocketServer service is not started. To start it, you can select it and click start, or you can run the App.bat file again. Once you’ve started the MultipleSocketService, it will continue to run until you stop it, disable it, or run the UnistallApp-NT.bat file. Congratulations…you have just built a Java based Windows service.

Summary

The Java Service Wrapper from Tanukisoftware.org is an excellent open source set of programs that allow you to turn your Java classes into Windows services. It provides three methods for accomplishing this task. We discussed only one method here, but I encourage you to read through the documentation and experiment with the other methods as well.


The source code for MultipleSocketServer.java can be found at CodeCentral.

The Java Communications API

Follow the link below to read my article on the Java Communications API posted on the Borland Developer Network. Java Communications API
Technorati search