Java

Installing the JDK on a RedHat Linux System

By default, RedHat Linux AS and AS4 servers don’t come with a JDK (Java Development Kit) installed on them. Depending on your install, if you run the java command you may get some sort of error message or a file not found message.

In this post I will describe how to install a JDK on your RedHat Linux server. It should also work on Fedora, however I have not tried it personally.

  1. First we need to download a JDK. I am downloading JDK 6u1 from http://java.sun.com/javase/downloads/index.jsp. Go to that page and click the Download button. On the new page that loads, we will download the Linux RPM in self-extracting file.

Sending Files via FTP From Your Java Applications - Part 2 of 2 - Using Jsch for SFTP

Yesterday I introduced how I send files via FTP and SFTP from my java applications. In that post I showed you how to use the Jakarta Commons Net package to FTP files. Today I will show you how to use the JSch (Java Secure Channel) library to do SFTP transfers.



Part 2 of 2 - Using JSch (Java Secure Channel)

Sending Files via FTP From Your Java Applications - Part 1 of 2 - Using Commons Net For FTP

Within the enterprise applications that I design and develop, a requirement always comes up to integrate it in some way with an external, 3rd party system. For example, in writing an insurance policy management system, the carriers often want policy details FTP’ed to them. Logistics companies typically FTP EDI files around all day. And most recently at the University for which I work, we have integrated our systems to transmit financial aid data to the government, send information related to book store vouchers to our outsourced bookstore, and we have our student data geocoded to help us analyze what profile of students are enrolling. All of these external providers want the data to be FTP’ed to them.

Using Javamail to Send Emails (Includes SMTP Auth and Attachment Support)

Last night I presented my article discussing how to use JavaMail to check a POP3 mail account and retrieve its messages. Tonight I am going to follow that up with a summary of my EmailDelivery class. This is a simple class I wrote to help me easily send emails from my Java applications. A few highlights of the class are that it:

  • Supports relaying through SMTP servers that require authentication.
  • Has convenience methods for easily adding file attachments.
  • Has a method to set the message priority (high, normal, low).
  • Allows you to easily set the to, from, cc, and bcc email addresses. Also supports passing in a comma separated list into any of these methods and have it parsed automatically for easy sending to multiple recipients.
  • Allows you to easily add header name/value pairs in the message.
  • Suppports easily setting the value stored in the Message-ID header tag of the message.

To use my classes you will first need to download the JavaBeans Activation Framework, and the Javamail libraries. Unzip the downloaded archives and put the appropriate jar file into your classpath. My example also uses Log4j to log its output. If you don’t want to configure log4j, then replace all of my log.info and log.debug calls with a call to System.out.println.

You also need Jakarta Commons Codec library from http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi. I downloaded the file labeled 1.3.zip Binary. Uncompress the zip file and put the commons codec jar file into your classpath. The name of the jar file in my example is commons-codec-1.3.jar. The Commons Codec jar file is what supports the Base 64 encoding of the file attachments.

Next, you will need to have my EmailMimeMessage class. Take the class below which is a simple extension of the standard JavaMail MimeMessage class. This class exists for the sole purpose of supporting a user defined Message-ID header tag in my examples.

package com.tima.edelivery.util;

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import org.apache.log4j.*;

/**
 * Extended MIME Message class with method to set the message ID 
 * header tag, and the updateHeaders method which ensures the 
 * Message ID gets set in the message.
 *
 * @author  Tim Archer 09/30/2003
 * @version $Revision: 1.1 $
 */
class EmailMimeMessage extends MimeMessage {
    static Logger log = Logger.getLogger(EmailMimeMessage.class);
    
    /** The value stored in the Message-ID header tag for the message.*/
    protected String messageID = "";
    
    /**
     * Create a new EmailMimeMessage object.
     * @param session The javax.mail.Session object the mail message is for.
     *
     */        
    public EmailMimeMessage(javax.mail.Session session) {
        super(session);
    }
    
    /**
     * Set the value stored in the Message-ID header tag for the message.
     * @param p_value The value of the Message-ID header tag.
     *
     */        
    void setMessageID(String p_value) {
        messageID = p_value;
    }
    
    /**
     * Calls the super.updateHeaders() method, and also ensures 
     * that the Message-ID header tag
     * gets set if the setMessageID method was called.
     *
     * @throws MessagingException If an error occurs.
     */        
    protected void updateHeaders() throws MessagingException {
        super.updateHeaders();
        if (messageID != null && messageID.length() > 0) {
            setHeader("Message-ID", messageID);
        }
    }
}



Now that you have the EmailMimeMessage class, take the code below and create the EmailDelivery class. This class has the real functionality we're after.

package com.tima.edelivery.util;

import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.*;

/**
 * Create a multipart message with the second block of the 
 * message being the given file for an attachment.
 * 
 * Has support for SMTP authentication to authenticate to an 
 * SMTP server to send the message.
 * Utilizes the apache commons codec library to Base64 encode the file attachment.
 *
 * @author  Tim Archer 09/30/2003
 * @version $Revision: 1.1 $
 */
public class EmailDelivery {
    static Logger log = Logger.getLogger(EmailDelivery.class);
    
    /** Static variable representing a high priority message. */
    public final static String HIGH_PRIORITY = "1";
    /** Static variable representing a normal priority message. */
    public final static String NORMAL_PRIORITY = "3";
    /** Static variable representing a low priority message. */
    public final static String LOW_PRIORITY = "5";
    
    EmailMimeMessage msg = null;
    Session session = null;
    Properties props = null;
    Multipart mp = null;
        
    /** The SMTP host used to send the message. */
    String smtp_host = new String("");
    /** If using SMTP authentication, then this is the username to login to the SMTP server as. */
    String smtp_username = null;
    /** If using SMTP authentication, then this is the password for the username to login to the SMTP server as. */
    String smtp_password = null;
    /** The port the SMTP server is listening on. */
    int smtp_port = 25;
    
    /** If we are to use SMTP authentication when sending the message. */
    boolean usingAuthentication = false;
    
    
    /**
     * Create a new object to send email messages.
     *
     */      
    public EmailDelivery() {
        props = System.getProperties();
        session = Session.getDefaultInstance(props, null);
        session.setDebug(false);
        msg = new EmailMimeMessage(session);
        mp = new MimeMultipart();
    }
    
    /**
     * Set the SMTP host used for sending the mail message.
     *
     * @param p_host The SMTP host to use for sending the messgae.
     * @throws MessagingException If an error occurs.
     *
     */      
    public void setSMTPHost(String p_host) throws MessagingException {
        this.setSMTPHost(p_host, null, null);
    }
    
    /**
     * Set the SMTP host used for sending the mail message.
     * This method allows a username and password to be specified for SMTP authentication.
     *
     * @param p_host The SMTP host to use for sending the messgae.
     * @param p_username The username to log into the SMTP server with.
     * @param p_password The password for the username to log into the SMTP server with.
     * @throws MessagingException If an error occurs.
     *
     */      
    public void setSMTPHost(String p_host, String p_username, String p_password) throws MessagingException {
        log.debug("EmailDelivery in setSMTPHost Method. Host: "+p_host+" Username: "+p_username);
        smtp_host = p_host;
        smtp_username = p_username;
        smtp_password = p_password;

        props.put("mail.smtp.host", smtp_host);
        
        //
        //Determine if we are using authentication or not
        //
        if ((smtp_username != null && smtp_username.length() > 0) ||
             (smtp_password != null && smtp_password.length() > 0)) {
            props.put("mail.smtp.auth", "true");
            usingAuthentication = true;
        }
        else {
            usingAuthentication = false;
        }
        log.debug("EmailDelivery in setSMTPHost Method. UsingAuthenticaton: "+usingAuthentication);
    }
 
    /**
     * Set the port that the SMTP server is listening on.
     *
     * @param p_port The port the SMTP server is listening on.
     * @throws Exception If an error occurs.
     *
     */      
    public void setSMTPPort(int p_port) throws Exception {
        smtp_port = p_port;
        props.put("mail.smtp.port", String.valueOf(smtp_port));
    }    

    /**
     * Set who the email message is to. 

Java Class To Check a POP3 Mail Account And Retrieve Its Messages

Recently I wrote a java daemon process that monitors a POP3 email box for messages, automatically downloads the messages, and then processes them. Basically my daemon process looks for returned and bounced emails in a POP3 mailbox and then updates certain flags in our ERP system so we don't send to that email address again. In some cases people reply to the messages our ERP system sends out, and in that case my daemon process forwards those messages to an appropriate user for manual review and handling.

I’m not going to go into the details of how this daemon process work since it goes far beyond the scope of this post (and it is a huge piece of software in itself). However, I am going to share the basic java class that I use to check the POP3 mail account, download messages, and then loop through them for processing.

Simple Java Class to DES Encrypt Strings (Such as Passwords and Credit Card Numbers)

In my Java based applications I usually have the need to encrypt a string before storing it somewhere. Most commonly, I need to encrypt user passwords and credit card information before storing it in a character field in the database. I don’t want people to be able to walk away with a cleartext list of passwords or credit card numbers just by doing a simple select. Instead they’ll have to work a little harder to decrypt the values stored in the database.

To do this, I wrote a very simple utility class that takes a String, runs it through a javax.crypto.Cipher object to DES encrypt it, and finally passes it through the Jakarta Commons Codec class which encodes the encrypted bytes into a Base64 (org.apache.commons.codec.binary.Base64) byte array. I wanted to encode the encrypted string in Base64 to ensure it only contains ASCII characters before storing it in my database. The decryption just follows the previous explanation in reverse: decode base 64, unencrypt string, return unencrypted string.

A Java InputVerifier for Email Addresses

Every good application should verify that data which must conform to a specific pattern actually does when it is being entered. For example email addresses, social security numbers, phone numbers, IP addresses, etc all have basic formats that they should conform to. Fortunately, in Java Swing applications the javax.swing.InputVerifier allows us to easily do this.

The InputVerifier class itself is designed such that the programmer must create a subclass of it and override the verifyText method. This verifyText method has a signature that looks like:

protected boolean verifyText(String textToVerify)

A Java Class To Compress/Zip and Uncompress/Unzip Byte Streams

Have you ever had the requirement to compress or uncompress files or byte streams from within your java applications? This requirement seems to be a common need for me in all sorts of applications from B2B data feeds to my client applications. Within my client applications I allow users to attach files to records and I compress them to conserve space before storing them on the server. Once I compress the byte stream, I usually do one of two things. I will either store the byte stream representing the compressed file directly into a BLOB column in my database, or I will write it to a file in a common file system location.

A Simple Java Measurement Utility Library (i.e., lb to kg, in to cm)

While I was writing an EMR application, I quickly realized that my framework needed a class with static methods to help me perform measurement conversions. Namely I needed to convert pounds to kilograms and inches to centimeters.

I searched the web for a while and didn't find a stock Jakarta Commons utility, so I decided I would build my own class named MeasurementUtil. In the future, when I come up with a new measurement conversion requirement it will be placed within this class in my framework package. You'll probably look at my code and say, "well that’s extremely simple, why not just do calculation using the logic inline". The answer is simple: I wanted a basic utility class that encapsulates all of my measurement conversion logic. In reality this could probably be turned into its own package with a suite of classes, but since I only started off with the requirement for two measurement conversions, we ended up with one class for now. This is in an effort to keep it simple.

Java File Utility Class To Open Files Using JDIC

In the Swing based java applications I write, the requirement usually exists to allow the app to open up other files such as Word Documents, PDF's, HTML pages, etc. Since I try not to limit myself to just the file types defined in requirements gathering, I looked for a more general solution that will allow my apps to open any file type. After all, if on my Windows or Linux desktops I can double click on a file name to open the appropriate program, then why can't my java applications?

My first take at this was to just use the java runtime, and assume my code would only run on windows 2000 or greater. The code at that point to open a file looked like this:

String cmd = "cmd /c \"" + fileName + "\"";
log.debug("Opening file with command: "+cmd);
java.lang.Runtime.getRuntime().exec(cmd);



Well, after that was in place for a few months, we wanted allow our application to also run on Linux. Uh oh, now the code above no longer works...

I searched around for a few minutes, and found a wonderful library called the JDesktop Integration Components (JDIC).

I downloaded the JDIC build, and included the jdic.jar in my project. Now my code to open files morphed into the following:

org.jdesktop.jdic.desktop.Desktop.open(new File(fileName));



So much simpler! The JDIC will launch the given file using the associated application as defined in the OS. The javadoc for the Open command looks like:

open

public static void open(java.io.File file)
                 throws DesktopException

    Launches the associated application to open the given file.

    Parameters:
        file - the given file. 
    Throws:
        DesktopException - if the given file is not valid, 
                           or there is no associated application, or the 
                           associated application fails to be launched.



I now have a simple utility class that I include in the framework package for my applications that allows me to open files, and get the file extension of a given file. Believe it or not, the most obscure file types I ended up using this code to open were for an EMR/medical application I was writing. Within that application I had to open various videos from ultrasounds, digitized X-Rays, etc. As long as the appropriate program to view those files was on the client PC, the code I include in my application ran could open it's associated file type.



The code for this utility class is listed below. Please feel free to use it in your applications.

/**
 * Copyright (c) 2002-2004 by Timothy E. Archer.  All rights reserved.
 *
 * $Id: FileUtil.java,v 1.1 2004/07/07 02:55:03 tima Exp $
 *
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL TIMOTHY E. ARCHER BE LIABLE FOR ANY 
 * DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */
package com.tima.util;

import java.io.*;
import java.util.*;
import org.apache.log4j.*;

/**
 * General File manipulation/maintenance routines. 
 * This class provides helper functions
 * to do things like open files, etc.
 *
 * @author  Tim Archer 10/14/03
 * @version $Revision: 1.1 $
 */
public class FileUtil {
    static Logger log = Logger.getLogger(FileUtil.class);
    
    /**
     * Open up the file using the default OS's method for
     * handling the file open. 
     * This method uses the Java Desktop Integration
     * components (JDIC) to open the file with the method 
     * org.jdesktop.jdic.desktop.Desktop.open(new File(fileName));
     *
     * @param fileName The name of the file to open.
     * @throws Exception If an error occurs.
     */
    public static void openFile(String fileName) throws Exception {

        /* Old logic,
         * This method will only work on the MS windows platform 
         * (win2k and greater), and opens the file through the command:

Spruce Up Your Swing Apps With JGoodies Looks

One of the things I incorporate into all of my Java Swing applications is the JGoodies Look and Feel. I feel that it gives my Swing apps a much cleaner interface, especially when run under MS Windows. The applications will feel a little bit more like a standard Windows Application to the end user.

Furthermore, incorporating the JGoodies Look and Feel is EXTREMELY easy. I feel that may be it's best feature! You can literally download the JGoodies Looks package and integrate it into your application in less that 15 minutes. I will explain how below.

Setting up a Log4j Socket Server to Email You Errors From Your Java Programs

Most developers quickly realize that being notified of errors within their applications as soon as they happen is a great way to proactively fix problems. This approach has a few benefits. First, the developer does not have to spend time each day scouring logs looking for errors, and then trying to recreate the state of the system at that time to determine what happened. Secondly, the admin can actually call the end user almost immediately after being notified of the error, making them seem omniscient. Imagine being able to call your users as they are encountering the error. They will literally think you are superhuman and be amazed that you knew they needed help.

Syndicate content
v2.0