/*
  i-net software provides programming examples for illustration only, without warranty
  either expressed or implied, including, but not limited to, the implied warranties
  of merchantability and/or fitness for a particular purpose. This programming example
  assumes that you are familiar with the programming language being demonstrated and
  the tools used to create and debug procedures. i-net software support professionals
  can help explain the functionality of a particular procedure, but they will not modify
  these examples to provide added functionality or construct procedures to meet your
  specific needs.
  © i-net software 1998-2010
*/

package samples.license_key;

import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

/**
 * This sample demonstrates how you can request a trial license key from i-net software's website 
 * programmatically in a Java application.
*/
public class RequestLicenseKey {

	/**
	 * Requests a license key for the first valid IP address of this host
	 */
    public RequestLicenseKey() {
        StringBuilder licenseRequestURL = new StringBuilder("http://www.inetsoftware.de/external_services/LicenseKeyRemoteRequest_Trial.php?ip=");
        String licensekey;
        
        try {
            java.net.InetAddress inetAdr = findValidIP();
            if( inetAdr != null ) {
                licenseRequestURL.append( inetAdr.getHostAddress()); // the IP of this host
                licenseRequestURL.append("&version=9");  // use the current i-net Clear Reports major version here
                licenseRequestURL.append("&host="); // the name of this host
                licenseRequestURL.append(inetAdr.getHostName());

                // establish HTTP connection
                URL url = new URL(licenseRequestURL.toString());
                URLConnection urlConnection = url.openConnection();
                urlConnection.setDoInput(true);
                urlConnection.connect();
                InputStream in = urlConnection.getInputStream();
                byte[] inp = new byte[ 16384 ];
                int l = in.read(inp);
                in.close();
                licensekey = new String(inp, 0, l);
                System.out.println("Your licensekey for IP " + inetAdr.getHostAddress() + " is: " + licensekey);
            } else {
                System.out.println("You cannot get a license since no valid local network device could be found.");
            }
        } catch(Exception e){ 
            e.printStackTrace(); 
        }
    }
    
	/**
	 * Searches all local network interfaces and IPv4 addresses for a valid external IP
	 * @return a valid address or null, if none was found
	 * @throws SocketException thrown if the interfaces cannot be scanned
	 */
	private InetAddress findValidIP() throws SocketException{
		Enumeration<NetworkInterface> interfaces = java.net.NetworkInterface.getNetworkInterfaces();
		if( interfaces != null ){
			// check all known network interfaces
			while( interfaces.hasMoreElements() ){
				NetworkInterface eth = interfaces.nextElement();
				Enumeration<InetAddress> addresses = eth.getInetAddresses();
				if( addresses == null ){
					continue;
				}
				while( addresses.hasMoreElements() ){
					InetAddress inetAddress = addresses.nextElement();
					if( inetAddress.isLoopbackAddress() ){
						// loopbacks are not valid on a license request. If you use a loopback IP the generated
						// license will not be accepted by i-net Clear Reports 
						continue;
					}
					String ipString = inetAddress.getHostAddress();
					// an IPv4 address is required for a license key request
					if( !(inetAddress instanceof Inet4Address) || ipString.startsWith("127") ) {
						continue;
					}
					return inetAddress;
				}
			}
		}
		return null;
	}
    
    /**
     * Requests a license key
     * @param args No parameter used
     */
	public static void main(String [] args) {
        new RequestLicenseKey();
    }
}
