001/*
002 * IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
003 * 
004 * http://www.izforge.com/izpack/
005 * http://developer.berlios.de/projects/izpack/
006 * 
007 * Copyright 2004 Thorsten Kamann
008 * 
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *     http://www.apache.org/licenses/LICENSE-2.0
014 *     
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 */
021
022package com.izforge.izpack.util;
023
024import java.net.InetAddress;
025import java.net.ServerSocket;
026
027import com.izforge.izpack.panels.ProcessingClient;
028import com.izforge.izpack.panels.Validator;
029
030/**
031 * A validator to check whether a port is available (free) on the localhost.
032 * 
033 * This validator can be used for rule input fields in the UserInputPanel to make sure that the port
034 * the user entered is not in use.
035 * 
036 * @author thorque
037 */
038public class PortValidator implements Validator
039{
040
041    public boolean validate(ProcessingClient client)
042    {
043        InetAddress inet = null;
044        String host = "localhost";
045        boolean retValue = false;
046        int numfields = client.getNumFields();
047
048        for (int i = 0; i < numfields; i++)
049        {
050            String value = client.getFieldContents(i);
051
052            if ((value == null) || (value.length() == 0)) { return false; }
053
054            try
055            {
056                inet = InetAddress.getByName(host);
057                ServerSocket socket = new ServerSocket(Integer.parseInt(value), 0, inet);
058                if (socket.getLocalPort() > 0)
059                {
060                    retValue = true;
061                }
062                else
063                {
064                    retValue = false;
065                }
066                if (!retValue)
067                {
068                    break;
069                }
070                socket.close();
071            }
072            catch (Exception ex)
073            {
074                retValue = false;
075            }
076        }
077        return retValue;
078    }
079
080}