Først og fremmest skal der på serveren ligge en fil
der indeholder navnene på alle de filer der må/kan
downloades. Klienten udbeder sig så den fil og
har nu en liste med filnavne den kan downloade.
Nu skal du så oprette en snyde-filechooser hvor
du kan vælge mellem de angivne navne. Jeg ville
ikke personlig lave en JFileChooser, men smide
navnene i en JList som kan vises for brugeren
der så kan afmærke de filer der skal hentes.
Her er et lettere modificeret eksempel på en klasse
jeg bruger præcis til samme formål. Den kan kortes
væsentligt ned, idet der bla. er verficeret download
hvilket nok ikke er nødvendigt.Det eneste klassen
kræver er at filen "filelist" ligger på webserveren
og at der naturligvis kører en webserver på port 80.
import java.io.*;
import java.util.zip.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.security.*;
import java.security.spec.*;
/**
* The FileDownloader class is a special class designed for use
* by the Janet system to download files from a designated
* web server (see {@link Janet.StandardValues#WebServerName}).
* The communication lines use port
* {@link Janet.StandardValues#WebServerPort}.
* It is easy to modify the class to work in other applications.
* Note that the class also works as a stand-alone application.
* <br><b>Example of use:</b>
* <pre>
* FileDownloader downloader = new FileDownloader();
* downloader.show();
* </pre>
* @author Carsten Knudsen
*/
/**
* Private constructor for class FileDownloader.
**/
private FileDownloader( boolean standAlone ) {
super( "FileDownloader" );
this.standAlone = standAlone;
try {
Socket socket = new Socket( StandardValues.WebServerName,
StandardValues.WebServerPort );
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader( is );
BufferedReader fromserver = new BufferedReader( isr );
OutputStream os = socket.getOutputStream();
PrintWriter toserver = new PrintWriter( os );
toserver.print( "GET /~janet/filelist HTTP/1.0\n\n" );
toserver.flush();
String line;
boolean ready = false;
java.util.Vector vector = new java.util.Vector();
while ( ( line = fromserver.readLine() ) != null ) {
if ( line.equals( "" ) ) {
ready = true;
} // if
else if ( ready ) {
vector.add ( line );
} // else if
} // while
socket.close();
names = new String[ vector.size() ];
for (int i = 0; i < names.length; i++) {
names[ i ] = (String)vector.get( i );
} // for
} // try
catch ( UnknownHostException uhe ) {
JOptionPane.showMessageDialog( null,
"Unknown host exception: " + uhe.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE );
return;
} // catch
catch ( Exception ioe ) {
JOptionPane.showMessageDialog( null,
"IO exception: " + ioe.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE );
return;
} // catch
text = new JTextArea( 10, 10 );
text.setEditable( false );
text.append( "To select a file for downloading" +
StandardValues.CR +
" press CTRL and left mouse button over file." +
StandardValues.CR );
text.append( "To select a contiguous range of files for downloading" +
StandardValues.CR +
" click on top file then press SHIFT and click on bottom file." +
StandardValues.CR );
list = new JList( names );
list.setFont( new Font( "Monospaced", Font.PLAIN, 12 ) );
list.setVisibleRowCount( 15 );
list.setVisibleRowCount( 15 );
list.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
getContentPane().setLayout( new BorderLayout() );
getContentPane().add( new JScrollPane( list ), "Center" );
getContentPane().add( new JScrollPane( text ), "North" );
JPanel buttonPanel = new JPanel();
downloadButton = new JButton( downloadText );
downloadButton.setMargin( inset );
downloadButton.setToolTipText( "Download the selected files." );
downloadButton.setEnabled( false );
verifyButton = new JButton( verifyText );
verifyButton.setMargin( inset );
verifyButton.setToolTipText( "Download the selected files with digital signature check." );
verifyButton.setEnabled( false );
closeButton = new JButton( closeText );
closeButton.setMargin( inset );
closeButton.setToolTipText( "Close the FileDownloader down." );
selectAllButton = new JButton( selectAllText );
selectAllButton.setMargin( inset );
selectAllButton.setToolTipText( "Select all files in the file list." );
unselectAllButton = new JButton( unselectAllText );
unselectAllButton.setMargin( inset );
unselectAllButton.setToolTipText( "Unselect all files in the file list." );
ActionListener listener = new ActionListener() {
public void actionPerformed( ActionEvent ae ) {
if ( ae.getActionCommand().equals( downloadText ) ) {
download();
} // if
else if ( ae.getActionCommand().equals( verifyText ) ) {
verifydownload();
} // else if
else if ( ae.getActionCommand().equals( closeText ) ) {
dispose();
} // else if
else if ( ae.getActionCommand().equals( selectAllText ) ) {
int[] indices = new int[ names.length ];
for (int i = 0; i < names.length; i++) {
indices[ i ] = i;
} // for
list.setSelectedIndices( indices );
} // else if
else if ( ae.getActionCommand().equals( unselectAllText ) ) {
list.clearSelection();
} // else if
} // actionPerformed
}; // ActionListener
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged( ListSelectionEvent lse ) {
if ( list.getMinSelectionIndex() < 0 ) {
downloadButton.setEnabled( false );
verifyButton.setEnabled( false );
} // if
else {
downloadButton.setEnabled( true );
verifyButton.setEnabled( true );
} // else
} // valueChanged
}; // ListSelectionListener
list.addListSelectionListener( listSelectionListener );
downloadButton.addActionListener( listener );
verifyButton.addActionListener( listener );
closeButton.addActionListener( listener );
selectAllButton.addActionListener( listener );
unselectAllButton.addActionListener( listener );
buttonPanel.add( downloadButton );
buttonPanel.add( verifyButton );
buttonPanel.add( selectAllButton );
buttonPanel.add( unselectAllButton );
buttonPanel.add( closeButton );
getContentPane().add( buttonPanel, "South" );
setSize( 600, 600 );
} // constructor
private void download() {
InputStream instream = null;
OutputStream outstream = null;
for (int i = 0; i < names.length; i++) {
if ( list.isSelectedIndex( i ) ) {
try {
URL url = new URL( "
http://" + StandardValues.WebServerName + "/~janet/" + names[ i ] );
instream = url.openStream();
outstream = new FileOutputStream( names[ i ] );
byte[] buffer = new byte[ 4096 ];
int bytes_read, total_bytes = 0;
while ( ( bytes_read = instream.read( buffer ) ) != -1 ) {
outstream.write( buffer, 0, bytes_read );
total_bytes += bytes_read;
} // while
text.append( "File " + names[ i ] + " downloaded (" + total_bytes +
" bytes read)." + StandardValues.CR );
} // try
catch ( UnknownHostException uhe ) {
JOptionPane.showMessageDialog( null,
"Unknown host exception: " + uhe.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE );
} // catch
catch ( IOException ioe ) {
JOptionPane.showMessageDialog( null,
"IO exception: " + ioe.getMessage() + StandardValues.CR +
"Occured while reading " + names[ i ],
"Error",
JOptionPane.ERROR_MESSAGE );
} // catch
finally {
try {
if ( instream != null ) instream.close();
} // try
catch ( Exception e ) {}
try {
if ( outstream != null ) outstream.close();
} // try
catch ( Exception e ) {}
} // finally
} // if
} // for
} // download
private void verifydownload() {
PublicKey publicKey = null;
try {
URL keyURL = new URL( "
http://" + StandardValues.WebServerName + "/~janet/janetpublickey" );
InputStream is = keyURL.openStream();
int length = 0;
while ( is.available() != 0 ) {
byte b = (byte)is.read();
length++;
} //
is.close();
is = keyURL.openStream();
byte[] encodedKey = new byte[ length ];
is.read( encodedKey, 0, length );
is.close();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( encodedKey );
KeyFactory keyFactory = KeyFactory.getInstance( "DSA" );
publicKey = keyFactory.generatePublic( publicKeySpec );
} // try
catch ( GeneralSecurityException gse ) {
JOptionPane.showMessageDialog( null,
"General security exception: " + gse.getMessage() + StandardValues.CR,
"Error",
JOptionPane.ERROR_MESSAGE );
return;
} // catch
catch ( IOException ioe ) {
JOptionPane.showMessageDialog( null,
"IO exception: " + ioe.getMessage() + StandardValues.CR,
"Error",
JOptionPane.ERROR_MESSAGE );
return;
} // catch
InputStream instream = null;
OutputStream outstream = null;
for (int i = 0; i < names.length; i++) {
if ( list.isSelectedIndex( i ) ) {
try {
/* Create a Signature object and initialize it with the public key */
Signature dsa = Signature.getInstance( "SHA1withDSA" );
dsa.initVerify( publicKey );
URL url = new URL( "
http://servername/~username/" + names[ i ] );
instream = url.openStream();
outstream = new FileOutputStream( names[ i ] );
byte[] buffer = new byte[ 4096 ];
int bytes_read, total_bytes = 0;
while ( ( bytes_read = instream.read( buffer ) ) != -1 ) {
outstream.write( buffer, 0, bytes_read );
total_bytes += bytes_read;
dsa.update( buffer, 0, bytes_read );
} // while
text.append( "File " + names[ i ] + " downloaded (" + total_bytes +
" bytes read)." + StandardValues.CR );
/* Read associated signature */
url = new URL( "
http://" + StandardValues.WebServerName + "/~janet/" + names[ i ] + ".sig" );
try {
instream = url.openStream();
int length = 0;
while ( instream.available() != 0 ) {
byte b = (byte)instream.read();
length++;
} //
instream.close();
byte[] signature = new byte[ length ];
instream = url.openStream();
instream.read( signature, 0, length );
instream.close();
/* attempt to verify signature */
boolean verified = dsa.verify( signature );
if ( verified ) {
text.append( "Signature was verified." + StandardValues.CR );
} // if
else {
text.append( "Signature could not be verified." + StandardValues.CR );
} // else
} // try
catch ( IOException ioe ) {
text.append( "No signature file found." + StandardValues.CR );
} // catch
} // try
catch ( GeneralSecurityException gse ) {
JOptionPane.showMessageDialog( null,
"General security exception: " + gse.getMessage() + StandardValues.CR,
"Error",
JOptionPane.ERROR_MESSAGE );
} // catch
catch ( UnknownHostException uhe ) {
JOptionPane.showMessageDialog( null,
"Unknown host exception: " + uhe.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE );
} // catch
catch ( IOException ioe ) {
JOptionPane.showMessageDialog( null,
"IO exception: " + ioe.getMessage() + StandardValues.CR,
"Error",
JOptionPane.ERROR_MESSAGE );
} // catch
finally {
try {
if ( instream != null ) instream.close();
} // try
catch ( IOException ioe ) {}
try {
if ( outstream != null ) outstream.close();
} // try
catch ( IOException ioe ) {}
} // finally
} // if
} // for
} // verifydownload
/**
* The method disposes of the frame and exits if
* run as a stand-alone application.
**/
public void windowClosing( WindowEvent e ) {
if ( standAlone ) {
System.exit( 0 );
} // if
else {
dispose();
} // else
} // windowClosing
public void windowClosed( WindowEvent e ){}
public void windowDeactivated( WindowEvent e ) {}
public void windowOpened( WindowEvent e ) {}
public void windowActivated( WindowEvent e ) {}
public void windowDeiconified( WindowEvent e ) {}
public void windowIconified( WindowEvent e ) {}
/**
* Class FileDownloader works as a stand-alone application.
**/
public static void main( String[] args ) {
FileDownloader downloader = new FileDownloader( true );
downloader.show();
} // main
} // FileDownloader