olegk 2003/02/20 01:23:30
Modified: httpclient/src/examples ClientApp.java
MultipartFileUploadApp.java
Log:
ClientApp & MultipartFileUploadApp update. All examples are now compileable with
Java 1.2.2
Contributed by Michael Becke
Revision Changes Path
1.11 +150 -151 jakarta-commons/httpclient/src/examples/ClientApp.java
Index: ClientApp.java
===================================================================
RCS file: /home/cvs/jakarta-commons/httpclient/src/examples/ClientApp.java,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -r1.10 -r1.11
--- ClientApp.java 13 Feb 2003 09:14:43 -0000 1.10
+++ ClientApp.java 20 Feb 2003 09:23:29 -0000 1.11
@@ -60,191 +60,190 @@
*
*/
-import org.apache.commons.httpclient.*;
-import org.apache.commons.httpclient.methods.*;
-import java.io.*;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import javax.swing.*;
-import java.awt.event.*;
-import java.awt.*;
-import javax.swing.text.html.*;
+import java.awt.BorderLayout;
+import java.awt.FlowLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JEditorPane;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+import javax.swing.text.BadLocationException;
+import javax.swing.text.html.HTMLDocument;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.methods.GetMethod;
/**
- *
- * This is a Swing application that demonstrates
- * how to use the Jakarta HttpClient API.
+ * A simple Swing application that demonstrates how to use the Jakarta
+ * HttpClient API. This application loads HTML from servers and displays the
+ * content as text and as rendered HTML.
*
* @author Sean C. Sullivan
* @author Ortwin Gl�ck
+ * @author Michael Becke
*/
public class ClientApp {
public static void main(String[] args) {
- HttpClientMainFrame f = new HttpClientMainFrame();
+ HttpClientFrame f = new HttpClientFrame();
f.setTitle("HttpClient demo application");
f.setSize(700, 500);
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ f.addWindowListener(
+ new WindowAdapter() {
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ }
+ );
f.setVisible(true);
}
- public static class HttpClientMainFrame extends javax.swing.JFrame {
- private HttpClientPanel m_panel;
-
- public HttpClientMainFrame() {
- m_panel = new HttpClientPanel();
- this.getContentPane().add(m_panel);
- }
- }
+ public static class HttpClientFrame extends JFrame {
- public static class HttpClientPanel extends JPanel {
- private static final String strTenSpaces = " ";
- private static final String strFortySpaces =
- strTenSpaces + strTenSpaces + strTenSpaces + strTenSpaces;
- private static final String strEightySpaces =
- strFortySpaces + strFortySpaces;
-
- public HttpClientPanel() {
- final JPanel panInput = new JPanel();
- panInput.setLayout(new FlowLayout());
+ private JComboBox cmbURL;
+ private JTextArea taTextResponse;
+ private JEditorPane htmlPane;
+
+ private HttpClient client;
+
+ public HttpClientFrame() {
+ client = new HttpClient(new MultiThreadedHttpConnectionManager());
+ client.setConnectionTimeout(30000);
- final JPanel panDisplay = new JPanel();
- panDisplay.setLayout(new BorderLayout());
+ JPanel panInput = new JPanel(new FlowLayout());
String[] aURLs = {
- "http://www.apache.org/",
- "http://www.google.com/",
- "http://www.opensource.org/",
- "http://www.anybrowser.org/",
- "http://jakarta.apache.org/",
- "http://www.w3.org/"
+ "http://www.apache.org/",
+ "http://www.google.com/",
+ "http://www.opensource.org/",
+ "http://www.anybrowser.org/",
+ "http://jakarta.apache.org/",
+ "http://www.w3.org/"
};
- final JComboBox cmbURL = new JComboBox(aURLs);
+ final JButton btnGET = new JButton("GET");
+ btnGET.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent ae) {
+ String url = (String) cmbURL.getSelectedItem();
+ if (url != null && url.length() > 0) {
+ loadPage(url);
+ }
+ }
+ }
+ );
+
+ cmbURL = new JComboBox(aURLs);
cmbURL.setToolTipText("Enter a URL");
- cmbURL.setPrototypeDisplayValue(strEightySpaces);
cmbURL.setEditable(true);
cmbURL.setSelectedIndex(0);
- final JTextArea taTextResponse = new JTextArea();
+ JLabel lblURL = new JLabel("URL:");
+
+ panInput.add(lblURL);
+ panInput.add(cmbURL);
+ panInput.add(btnGET);
+
+ taTextResponse = new JTextArea();
taTextResponse.setEditable(false);
taTextResponse.setCaretPosition(0);
- final JLabel lblURL = new JLabel("URL:");
-
- final JButton btnGET = new JButton("GET");
+ htmlPane = new JEditorPane();
+ htmlPane.setContentType("text/html");
+ htmlPane.setEditable(false);
+
+ JSplitPane splitResponsePane = new JSplitPane(
+ JSplitPane.HORIZONTAL_SPLIT,
+ new JScrollPane(taTextResponse),
+ new JScrollPane(htmlPane)
+ );
+ splitResponsePane.setOneTouchExpandable(false);
+ splitResponsePane.setDividerLocation(350);
+ // it would be better to set resizeWeight, but this method does
+ // not exist in JRE 1.2.2
+// splitResponsePane.setResizeWeight(0.5);
+
+ this.getContentPane().setLayout(new BorderLayout());
+ this.getContentPane().add(panInput, BorderLayout.NORTH);
+ this.getContentPane().add(splitResponsePane, BorderLayout.CENTER);
+ }
- cmbURL.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ae)
- {
- btnGET.doClick();
- }
- });
+ /**
+ * Sets the HTML content to be displayed.
+ *
+ * @param content an HTML document
+ */
+ private void setDocumentContent(String content) {
+
+ HTMLDocument doc = new HTMLDocument();
+ try {
+ doc.remove(0, doc.getLength());
+ } catch (BadLocationException e) {
+ e.printStackTrace();
+ }
+ doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
+
+ try {
+ htmlPane.read(new ByteArrayInputStream(content.getBytes()), doc);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ htmlPane.setDocument(doc);
+ htmlPane.setCaretPosition(0);
- btnGET.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent ae) {
- final String strRawURL = (String) cmbURL.getSelectedItem();
- if (strRawURL.length() > 0) {
- final URL u;
- try {
- u = new URL(strRawURL.trim());
- Thread t = new Thread() {
- public void run() {
- HttpClient client = new HttpClient(new
MultiThreadedHttpConnectionManager());
- GetMethod get = new GetMethod();
- HeadMethod head = new HeadMethod();
- HostConfiguration hc = new HostConfiguration();
- try {
- hc.setHost(new URI(u));
- } catch(URIException e) {
- throw new RuntimeException(e.toString());
- }
- client.setHostConfiguration(hc);
- client.setConnectionTimeout(30000);
- int iGetResultCode;
- int iHeadResultCode;
- try {
- //to execute two methods in a row without
reading the first method's response
- //we *need* the
MultiThreadedHttpConnectionManager as set in the HttpClient's
- //constructor.
- iGetResultCode = client.executeMethod(get);
- iHeadResultCode =
client.executeMethod(head);
-
- final String strGetResponseBody =
- get.getResponseBodyAsString();
- get.releaseConnection();
-
- final String strHeadResponseBody =
- head.getResponseBodyAsString();
- head.releaseConnection();
-
- if (strGetResponseBody != null) {
- Runnable r = new Runnable() {
- public void run() {
- panDisplay.removeAll();
-
- taTextResponse.setText(
- strGetResponseBody);
-
taTextResponse.setCaretPosition(0);
- taTextResponse.requestFocus();
-
- JEditorPane htmlPane =
- new JEditorPane("text/html",
- strGetResponseBody);
- htmlPane.setEditable(false);
-
- final JSplitPane
splitResponsePane =
- new JSplitPane(
-
JSplitPane.HORIZONTAL_SPLIT,
- new
JScrollPane(taTextResponse),
- new
JScrollPane(htmlPane));
- splitResponsePane
- .setOneTouchExpandable(
- false);
- panDisplay.add(
- splitResponsePane,
- BorderLayout.CENTER);
-
- splitResponsePane
- .setDividerLocation(
- panDisplay.getWidth() /
2);
-
- panDisplay.validate();
- }
- };
- try {
- SwingUtilities.invokeAndWait(r);
- } catch (InvocationTargetException ex) {
- ex.printStackTrace();
- } catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- }
- }
- catch (HttpException ex) {
- ex.printStackTrace();
- } catch (IOException ex) {
- ex.printStackTrace();
+ taTextResponse.setText(content);
+ taTextResponse.setCaretPosition(0);
+ taTextResponse.requestFocus();
+ }
+
+ /**
+ * Loads the page at the given URL from a separate thread.
+ * @param url
+ */
+ private void loadPage(final String url) {
+ // create a new thread to load the URL from
+ new Thread() {
+ public void run() {
+ GetMethod get = new GetMethod(url);
+ get.setFollowRedirects(true);
+
+ try {
+ int iGetResultCode = client.executeMethod(get);
+ final String strGetResponseBody =
get.getResponseBodyAsString();
+
+ if (strGetResponseBody != null) {
+ // set the HTML on the UI thread
+ SwingUtilities.invokeLater(
+ new Runnable() {
+ public void run() {
+ setDocumentContent(strGetResponseBody);
}
}
- };
- t.start();
- } catch (MalformedURLException ignored) {
- // ignore
+ );
}
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ } finally {
+ get.releaseConnection();
}
}
- });
-
- panInput.add(lblURL);
- panInput.add(cmbURL);
- panInput.add(btnGET);
-
- this.setLayout(new BorderLayout());
-
- this.add(panInput, BorderLayout.NORTH);
- this.add(panDisplay, BorderLayout.CENTER);
+ }.start();
}
+
}
+
}
1.5 +152 -101
jakarta-commons/httpclient/src/examples/MultipartFileUploadApp.java
Index: MultipartFileUploadApp.java
===================================================================
RCS file:
/home/cvs/jakarta-commons/httpclient/src/examples/MultipartFileUploadApp.java,v
retrieving revision 1.4
retrieving revision 1.5
diff -u -r1.4 -r1.5
--- MultipartFileUploadApp.java 13 Feb 2003 09:14:43 -0000 1.4
+++ MultipartFileUploadApp.java 20 Feb 2003 09:23:29 -0000 1.5
@@ -60,16 +60,28 @@
*
*/
-import org.apache.commons.httpclient.*;
-import org.apache.commons.httpclient.methods.*;
-import java.io.*;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import javax.swing.*;
-import java.awt.event.*;
-import java.awt.*;
-import javax.swing.text.html.*;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.io.File;
+
+import javax.swing.DefaultComboBoxModel;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.JTextField;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.MultipartPostMethod;
/**
*
@@ -78,141 +90,180 @@
* for uploading files
*
* @author Sean C. Sullivan
+ * @author Michael Becke
*
*/
public class MultipartFileUploadApp {
public static void main(String[] args) {
- MultipartFileUploadMainFrame f = new MultipartFileUploadMainFrame();
+ MultipartFileUploadFrame f = new MultipartFileUploadFrame();
f.setTitle("HTTP multipart file upload application");
- f.setSize(700, 500);
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ f.pack();
+ f.addWindowListener(
+ new WindowAdapter() {
+ public void windowClosing(WindowEvent e) {
+ System.exit(0);
+ }
+ }
+ );
f.setVisible(true);
- }
-
- public static class MultipartFileUploadMainFrame extends javax.swing.JFrame {
- private MultipartFileUploadPanel m_panel;
-
- public MultipartFileUploadMainFrame() {
- m_panel = new MultipartFileUploadPanel();
- this.getContentPane().add(m_panel);
- }
- }
+ }
- public static class MultipartFileUploadPanel extends JPanel {
- private static final String strTenSpaces = " ";
- private static final String strFortySpaces =
- strTenSpaces + strTenSpaces + strTenSpaces + strTenSpaces;
- private static final String strEightySpaces =
- strFortySpaces + strFortySpaces;
+ public static class MultipartFileUploadFrame extends JFrame {
- private File targetFile = null;
-
- public MultipartFileUploadPanel() {
- final JPanel panInput = new JPanel();
+ private File targetFile;
+ private JTextArea taTextResponse;
+ private DefaultComboBoxModel cmbURLModel;
+ public MultipartFileUploadFrame() {
String[] aURLs = {
- "http://localhost:8080/foo/bar"
- };
-
- final JComboBox cmbURL = new JComboBox(aURLs);
+ "http://localhost:8080/httpclienttest/fileupload"
+ };
+
+ cmbURLModel = new DefaultComboBoxModel(aURLs);
+ final JComboBox cmbURL = new JComboBox(cmbURLModel);
cmbURL.setToolTipText("Enter a URL");
- cmbURL.setPrototypeDisplayValue(strEightySpaces);
cmbURL.setEditable(true);
cmbURL.setSelectedIndex(0);
-
- final JLabel lblTargetFile = new JLabel();
- lblTargetFile.setText("");
-
+
+ JLabel lblTargetFile = new JLabel("Selected file:");
+
+ final JTextField tfdTargetFile = new JTextField(30);
+ tfdTargetFile.setEditable(false);
+
final JButton btnDoUpload = new JButton("Upload");
btnDoUpload.setEnabled(false);
final JButton btnSelectFile = new JButton("Select a file...");
- btnSelectFile.addActionListener(new ActionListener() {
- public void actionPerformed(final ActionEvent evt) {
- final JFileChooser chooser = new JFileChooser();
+ btnSelectFile.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent evt) {
+ JFileChooser chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(false);
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setDialogTitle("Choose a file...");
- if (chooser.showOpenDialog(MultipartFileUploadPanel.this)
== JFileChooser.APPROVE_OPTION) {
+ if (
+ chooser.showOpenDialog(MultipartFileUploadFrame.this)
+ == JFileChooser.APPROVE_OPTION
+ ) {
targetFile = chooser.getSelectedFile();
- lblTargetFile.setText("Selected file: " +
targetFile.toString());
+ tfdTargetFile.setText(targetFile.toString());
btnDoUpload.setEnabled(true);
}
}
- });
-
- final JTextArea taTextResponse = new JTextArea();
+ }
+ );
+
+ taTextResponse = new JTextArea(10, 40);
taTextResponse.setEditable(false);
- taTextResponse.setCaretPosition(0);
final JLabel lblURL = new JLabel("URL:");
-
btnDoUpload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
- URL targetURL = null;
-
- try {
- targetURL = new URL(cmbURL.getSelectedItem().toString());
- } catch (MalformedURLException ex) {
- // todo - code here
- ex.printStackTrace();
+ String targetURL = cmbURL.getSelectedItem().toString();
+ // add the URL to the combo model if it's not already there
+ if (!targetURL
+ .equals(
+ cmbURLModel.getElementAt(
+ cmbURL.getSelectedIndex()))) {
+ cmbURLModel.addElement(targetURL);
}
-
- MultipartPostMethod filePost = new MultipartPostMethod();
- if (targetURL.getPath() == null) {
- filePost.setPath("/");
- } else {
- filePost.setPath(targetURL.getPath());
- }
+ MultipartPostMethod filePost =
+ new MultipartPostMethod(targetURL);
try {
- filePost.addParameter(
- targetFile.getName(),
- targetFile);
+ appendMessage("Uploading " + targetFile.getName() + " to "
+ targetURL);
+ filePost.addParameter(targetFile.getName(), targetFile);
HttpClient client = new HttpClient();
- HostConfiguration hc = new HostConfiguration();
- hc.setHost(new URI(targetURL));
- client.setHostConfiguration(hc);
- client.executeMethod(filePost);
- filePost.releaseConnection();
- } catch (FileNotFoundException ex) {
- // todo - put real code here
- ex.printStackTrace();
- } catch (HttpException ex) {
- // todo - put real code here
- ex.printStackTrace();
- } catch (java.io.IOException ex) {
- // todo - put real code here
+ client.setConnectionTimeout(5000);
+ int status = client.executeMethod(filePost);
+ if (status == HttpStatus.SC_OK) {
+ appendMessage(
+ "Upload complete, response=" +
filePost.getResponseBodyAsString()
+ );
+ } else {
+ appendMessage(
+ "Upload failed, response=" +
HttpStatus.getStatusText(status)
+ );
+ }
+ } catch (Exception ex) {
+ appendMessage("Error: " + ex.getMessage());
ex.printStackTrace();
+ } finally {
+ filePost.releaseConnection();
}
}
});
- JPanel panURLInput = new JPanel();
- panURLInput.setLayout(new FlowLayout());
- panURLInput.add(lblURL);
- panURLInput.add(cmbURL);
-
- JPanel panFile = new JPanel();
- panFile.setLayout(new FlowLayout());
- panFile.add(lblTargetFile);
- panFile.add(btnSelectFile);
-
- panInput.setLayout(new GridLayout(3, 1));
-
- panInput.add(panURLInput);
- panInput.add(panFile);
- panInput.add(btnDoUpload);
-
- this.setLayout(new BorderLayout());
+ getContentPane().setLayout(new GridBagLayout());
+ GridBagConstraints c = new GridBagConstraints();
- this.add(panInput, BorderLayout.CENTER);
+ c.anchor = GridBagConstraints.EAST;
+ c.fill = GridBagConstraints.NONE;
+ c.gridheight = 1;
+ c.gridwidth = 1;
+ c.gridx = 0;
+ c.gridy = 0;
+ c.insets = new Insets(10, 5, 5, 0);
+ c.weightx = 1;
+ c.weighty = 1;
+ getContentPane().add(lblURL, c);
+
+ c.anchor = GridBagConstraints.WEST;
+ c.fill = GridBagConstraints.HORIZONTAL;
+ c.gridwidth = 2;
+ c.gridx = 1;
+ c.insets = new Insets(5, 5, 5, 10);
+ getContentPane().add(cmbURL, c);
+
+ c.anchor = GridBagConstraints.EAST;
+ c.fill = GridBagConstraints.NONE;
+ c.insets = new Insets(10, 5, 5, 0);
+ c.gridwidth = 1;
+ c.gridx = 0;
+ c.gridy = 1;
+ getContentPane().add(lblTargetFile, c);
+
+ c.anchor = GridBagConstraints.CENTER;
+ c.fill = GridBagConstraints.HORIZONTAL;
+ c.insets = new Insets(5, 5, 5, 5);
+ c.gridwidth = 1;
+ c.gridx = 1;
+ getContentPane().add(tfdTargetFile, c);
+
+ c.anchor = GridBagConstraints.WEST;
+ c.fill = GridBagConstraints.NONE;
+ c.insets = new Insets(5, 5, 5, 10);
+ c.gridwidth = 1;
+ c.gridx = 2;
+ getContentPane().add(btnSelectFile, c);
+
+ c.anchor = GridBagConstraints.CENTER;
+ c.fill = GridBagConstraints.NONE;
+ c.insets = new Insets(10, 10, 10, 10);
+ c.gridwidth = 3;
+ c.gridx = 0;
+ c.gridy = 2;
+ getContentPane().add(btnDoUpload, c);
+
+ c.anchor = GridBagConstraints.CENTER;
+ c.fill = GridBagConstraints.BOTH;
+ c.insets = new Insets(10, 10, 10, 10);
+ c.gridwidth = 3;
+ c.gridheight = 3;
+ c.weighty = 3;
+ c.gridx = 0;
+ c.gridy = 3;
+ getContentPane().add(new JScrollPane(taTextResponse), c);
+ }
+
+ private void appendMessage(String m) {
+ taTextResponse.append(m + "\n");
}
- }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]