
/**
 * AddLocator.java
 *
 *
 * Created: Fri May  4 22:38:57 2001
 *
 * @author <a href="mailto:jan.newmarch@infotech.monash.edu.au"Jan Newmarch</a>
 * @version
 */

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.rmi.RemoteException;

import net.jini.core.lease.Lease;
import net.jini.core.lookup.ServiceItem;

import servicefinder.ServiceFinder;

public class AddLocator extends HttpServlet {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");

        out.println("<title>" + "Jini Service Information" + "</title>");
        out.println("</head>");
        out.println("<body>");

        HttpSession session = request.getSession();
	ServiceFinder finder = (ServiceFinder) 
	    session.getAttribute("ServiceFinder");
	if (finder == null) {
	    out.println("Can't find service finder");
	    out.println("</body> </html>");
	}

        String ipAddress = request.getParameter("ip");
	if (ipAddress == null) {
	    out.println("No IP address parameter supplied");
	    out.println("</body> </html>");
	}
	ipAddress = removeLeadingBlanks(ipAddress);

	out.println("<br>IP is \"" + ipAddress + "\"<br>");

        String timeoutString = request.getParameter("timeout");
	if (timeoutString == null) {
	    out.println("No timeout parameter supplied");
	    out.println("</body> </html>");
	}
	timeoutString = removeLeadingBlanks(timeoutString);
	long timeout = 0;
	out.println("timeout is \"" + timeoutString + "\"");
	if (timeoutString.equals("FOREVER")) {
	    timeout = Lease.FOREVER;
	} else {
	    try {
		timeout = Long.parseLong(timeoutString);
	    } catch(Exception e) {
		out.println("<pre>" + e.toString() + "</pre>");
		out.println("</body>\n</html>");
		return;
	    }
	}

	try {
	    finder.addLocator(ipAddress, timeout);
	} catch(RemoteException e) {
	    out.println("<pre>" + e.toString() + "</pre>");
	    out.println("</body>\n</html>");
	    return;
	}

        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException
    {
        doGet(request, response);
    }


    /**
     * Netscape Communicator 4.61 is padding the form fields with a
     * leading blank which needs to be removed
     */
    public String removeLeadingBlanks(String s) {
	int start = 0;
	while (s.charAt(start) == ' ') {
	    start++;
	}
	if (start == 0) {
	    return s;
	}
	return s.substring(start);
    }
}// AddLocator
