// $Id: URLDumpPane.java,v 1.2 2004/09/30 00:33:38 caron Exp $
/*
 * Copyright 1997-2004 Unidata Program Center/University Corporation for
 * Atmospheric Research, P.O. Box 3000, Boulder, CO 80307,
 * support@unidata.ucar.edu.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package thredds.ui;

import thredds.util.IO;
import ucar.util.prefs.*;
import ucar.util.prefs.ui.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;


/**
 * A text widget to dump a web URL.
 *
 * @author John Caron
 * @version $Id: URLDumpPane.java,v 1.2 2004/09/30 00:33:38 caron Exp $
 */

public class URLDumpPane extends TextHistoryPane {
    private PreferencesExt prefs;
    private ComboBox cb;
    private GetContentsTask task;
    private HttpURLConnection currentConnection = null;

    public URLDumpPane(PreferencesExt prefs) {
      super(true);
      this.prefs = prefs;

      // combo box holds a list of urls
      cb = new ComboBox( prefs);

      JButton headButton = new JButton("Head");
      headButton.setToolTipText("Open URL connection, HEADERS only");
      headButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          String urlString = (String) cb.getSelectedItem();
          openURL( urlString, "HEAD");
          gotoTop();
          cb.addItem( urlString);
        }
      });

      JButton readButton = new JButton("Full");
      readButton.setToolTipText("Open URL connection, show content");
      readButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          String urlString = (String) cb.getSelectedItem();
          readURL( urlString);
          gotoTop();
          cb.addItem( urlString);
        }
      });

      JButton optButton = new JButton("Options");
      optButton.setToolTipText("Get server options");
      optButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          String urlString = (String) cb.getSelectedItem();
          openURL( urlString, "OPTIONS");
          gotoTop();
          cb.addItem( urlString);
        }
      });

      JPanel buttPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
      buttPanel.add( headButton);
      buttPanel.add( readButton);
      buttPanel.add( optButton);

      JPanel topPanel = new JPanel( new BorderLayout());
      topPanel.add(new JLabel("URL:"), BorderLayout.WEST);
      topPanel.add(cb, BorderLayout.CENTER);
      topPanel.add(buttPanel, BorderLayout.EAST);

      // setLayout( new BorderLayout());
      add( topPanel, BorderLayout.NORTH);
      // add( new JScrollPane(ta), BorderLayout.CENTER);
    }

  private void openURL(String urlString, String command) {
    try {
      //Open the URLConnection for reading
      URL u = new URL(urlString);
      currentConnection = (HttpURLConnection) u.openConnection();
      currentConnection.setRequestMethod(command);
      //uc.setAllowUserInteraction(true);

      int code = currentConnection.getResponseCode();
      String response = currentConnection.getResponseMessage();

      clear();
      appendLine(command+" request for "+urlString);

      // HEADERS
      appendLine(" HTTP/1.x " + code + " " + response);
      for (int j = 1; ; j++) {
        String header = currentConnection.getHeaderField(j);
        String key = currentConnection.getHeaderFieldKey(j);
        if (header == null || key == null) break;
        appendLine(" "+key + ": " + header);
      }

    } catch (MalformedURLException e) {
      append(urlString + " is not a parseable URL");
    }
    catch (IOException e) {
      e.printStackTrace();
      System.err.println(e);
    }
  }

  private void readURL(String urlString) {
    try {
      //Open the URLConnection for reading
      URL u = new URL(urlString);
      currentConnection = (HttpURLConnection) u.openConnection();
      //currentConnection.setRequestMethod("HEAD");
      //uc.setAllowUserInteraction(true);

      int code = currentConnection.getResponseCode();
      String response = currentConnection.getResponseMessage();

      clear();
      appendLine("FULL request for "+urlString);

      // HEADERS
      appendLine(" HTTP/1.x " + code + " " + response);
      for (int j = 1; ; j++) {
        String header = currentConnection.getHeaderField(j);
        String key = currentConnection.getHeaderFieldKey(j);
        if (header == null || key == null) break;
        appendLine(" "+key + ": " + header);
      }

      appendLine("");

      // read it
      java.io.InputStream is = currentConnection.getInputStream();
      ByteArrayOutputStream bout = new ByteArrayOutputStream(200000);
      thredds.util.IO.copy(is, bout);
      is.close();

      append(new String(bout.toByteArray()));

    } catch (MalformedURLException e) {
      append(urlString + " is not a parseable URL");
    }
    catch (IOException e) {
      e.printStackTrace();
      System.err.println(e);
    }
  }

    public void setURL(String urlString) {
      if (urlString == null) return;

      task = new GetContentsTask(urlString);
      thredds.ui.ProgressMonitor pm = new thredds.ui.ProgressMonitor(task);
      pm.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // System.out.println(" setURL event"+e.getActionCommand());
          if (e.getActionCommand().equals("success")) {
            ta.setText(task.contents);
          }

        }
      });
      pm.start(this, "Open URL " + urlString, 10);
      return;
    }

    void putURL(String urlString) {
      if (urlString == null) return;
      String contents = ta.getText();
      IO.Result result = thredds.util.IO.putToURL( urlString, contents);
      javax.swing.JOptionPane.showMessageDialog(this, "Status code= "+result.code+"\n"+result.message);
    }

    public void save() {
       cb.save();
    }

    public void clear() {ta.setText(null); }
    public void gotoTop() { ta.setCaretPosition(0); }
    public void setText(String text) { ta.setText(text); }
    public void append(String text) { ta.append(text); }
    public void appendLine(String text) {
      ta.append(text);
      ta.append("\n");
    }

  private class GetContentsTask extends ProgressMonitorTask {
    String urlString;
    String contents;

    GetContentsTask( String urlString) {
      this.urlString = urlString;
    }

    public void run() {
      try {
        contents = thredds.util.IO.readURLcontentsWithException(urlString);
      } catch (IOException e) {
        setError(e.getMessage());
        done = true;
        return;
      }

      success = !cancel;
      done = true;
    }
  }

  private static XMLStore xstore;
  private static URLDumpPane main;
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame("URL Dump Pane");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        try {
          main.save();
          xstore.save();
        } catch (IOException ioe) {}
        System.exit(0);
      }
    });

    // open up the preferences file(s)
    try {
      String storeFilename = XMLStore.makeStandardFilename(".unidata", "URLDumpPane.xml");
      xstore = XMLStore.createFromFile(storeFilename, null);
    } catch (java.io.IOException e) {
      e.printStackTrace();
    }
    PreferencesExt store = xstore.getPreferences();

    main = new URLDumpPane(store);

    frame.getContentPane().add(main);
    frame.pack();
    frame.setLocation(200, 200);
    frame.setSize(900, 700);
    frame.setVisible(true);
  }

}

/* Change History:
   $Log: URLDumpPane.java,v $
   Revision 1.2  2004/09/30 00:33:38  caron
   *** empty log message ***

   Revision 1.1  2004/09/24 03:26:35  caron
   merge nj22

   Revision 1.5  2004/06/12 02:08:40  caron
   validate dqc or catalog

   Revision 1.4  2004/06/04 00:51:57  caron
   release 2.0b

   Revision 1.3  2004/05/11 23:30:36  caron
   release 2.0a

   Revision 1.2  2004/03/05 23:43:25  caron
   1.3.1 release

 */