package org.jcon.io;

import java.net.URL;
import java.io.*;

/**
 * Reads the contents of a URL. Useful for testing the
 * existence and contents of a server file or URL. Also
 * useful for getting the contents of a URL text file.
 *
 * @author Jack Harich
 */
public class ReadURL {

//---------- Initialization ------------------------------
public static void main(String args[]) {
    String urlString = "http://sheba/awork/" +
        "org/jcon/ba/system/ItemSystemMgr.class";
    if (args.length > 0) urlString = args[0];

    String text = ReadURL.read(urlString, 10);
    System.out.println("URL: " + urlString );
    System.out.println(text);
}
//---------- Public Methods ------------------------------
public static String read(String urlString, int numLines) {
    String text = null;
    try {
       // Read a text file given it's URL
        URL url = new URL(urlString);

        InputStream inputStream = (InputStream)url.getContent();
        text = readLines(inputStream, numLines);
        inputStream.close();

    } catch(Exception ex) {
        ex.printStackTrace();
    }
    return text;
}
//---------- Private Methods -----------------------------
// This shows if we got the text file
private static String readLines(InputStream input, int numLines) throws IOException {

    InputStreamReader inReader = new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(inReader);

    StringBuffer text = new StringBuffer();
    String line = reader.readLine();
    int count = 1;

    while (line != null) {
        line = reader.readLine();
        if (line != null) {
            text.append(line);
            text.append("\n");
        }
        if (++count > numLines) break;
    }
    reader.close();
    return text.toString();
}
//--- Std
private static void print(String text) {
    System.out.println("ReadURL" + text);
}

} // End class
