001    /*
002     * Copyright 2001-2005 The Apache Software Foundation
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package examples;
017    
018    import java.io.IOException;
019    import java.net.InetAddress;
020    import java.net.UnknownHostException;
021    import org.apache.commons.net.WhoisClient;
022    
023    /***
024     * This is an example of how you would implement the Linux fwhois command
025     * in Java using NetComponents.  The Java version is much shorter.
026     * <p>
027     ***/
028    public final class fwhois
029    {
030    
031        public static final void main(String[] args)
032        {
033            int index;
034            String handle, host;
035            InetAddress address = null;
036            WhoisClient whois;
037    
038            if (args.length != 1)
039            {
040                System.err.println("usage: fwhois handle[@<server>]");
041                System.exit(1);
042            }
043    
044            index = args[0].lastIndexOf("@");
045    
046            whois = new WhoisClient();
047            // We want to timeout if a response takes longer than 60 seconds
048            whois.setDefaultTimeout(60000);
049    
050            if (index == -1)
051            {
052                handle = args[0];
053                host = WhoisClient.DEFAULT_HOST;
054            }
055            else
056            {
057                handle = args[0].substring(0, index);
058                host = args[0].substring(index + 1);
059            }
060    
061            try
062            {
063                address = InetAddress.getByName(host);
064            }
065            catch (UnknownHostException e)
066            {
067                System.err.println("Error unknown host: " + e.getMessage());
068                System.exit(1);
069            }
070    
071            System.out.println("[" + address.getHostName() + "]");
072    
073            try
074            {
075                whois.connect(address);
076                System.out.print(whois.query(handle));
077                whois.disconnect();
078            }
079            catch (IOException e)
080            {
081                System.err.println("Error I/O exception: " + e.getMessage());
082                System.exit(1);
083            }
084        }
085    
086    }