/*
 *
 * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 */
package samples.jndi.url.servlet;



import java.io.*;

import java.util.*;

import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.naming.*;


public class JndiUrlServlet extends HttpServlet {

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

        PrintWriter out = response.getWriter();

        response.setContentType("text/plain");
        out.println("The contents of the HTML page follows:\n");

        try {
            out.print(getContents());
        } catch(HTTPResponseException ex) {
            System.out.println("Exception : " + ex);
        }
    }

    public StringBuffer getContents() throws HTTPResponseException {

        Context           context;
        URL               url;
        StringBuffer      buffer = new StringBuffer("Nothing was found");
        String            line;
        int               responseCode;
        HttpURLConnection connection;
        InputStream       input;
        BufferedReader    dataInput;

        try {
            context      = new InitialContext();
            url          = (URL) context.lookup("java:comp/env/url/SunWeb");
            connection   = (HttpURLConnection) url.openConnection();
            responseCode = connection.getResponseCode();

            if(responseCode != HttpURLConnection.HTTP_OK) {
                throw new HTTPResponseException(
                    "HTTP response code: " + String.valueOf(responseCode));
            }

            buffer    = new StringBuffer();
            input     = connection.getInputStream();
            dataInput = new BufferedReader(new InputStreamReader(input));

            while((line = dataInput.readLine()) != null) {
                buffer.append(line);
                buffer.append('\n');
            }
        } catch(Exception ex) {
            System.out.println("Exception : " + ex);

            buffer = buffer.append("    exception    ").append(ex.toString());
        }

        return buffer;
    }    // getContents()
}

