Ignore:
Timestamp:
2005-10-14T15:19:36+13:00 (19 years ago)
Author:
mdewsnip
Message:

(MAJOR CHANGE) This is the remote Greenstone building functionality implemented for the West Yorkshire Fire and Rescue Service. It allows collections to be built without having a local version of Greenstone, using either a stand-alone version of the GLI or the applet.

The collections are stored on the server (allowing people to collaborate on collections -- but not at the same time), and only what is necessary to let the user edit the collection is downloaded. Any changes to the collection are uploaded to the server.

An access restriction mechanism is implemented which uses the standard Greenstone user database to control who has access to collections.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/gli/src/org/greenstone/gatherer/remote/RemoteGreenstoneServer.java

    r10562 r10726  
    66 * University of Waikato, New Zealand.
    77 *
    8  * Author: David Bainbridge, Greenstone Digital Library, University of Waikato
     8 * Author: Michael Dewsnip, NZDL Project, University of Waikato
    99 *
    1010 * Copyright (C) 2005 New Zealand Digital Library Project
     
    3030import java.io.*;
    3131import java.net.*;
     32import java.util.*;
     33import java.util.zip.*;
     34import javax.swing.*;
    3235import org.greenstone.gatherer.Configuration;
    3336import org.greenstone.gatherer.DebugStream;
     37import org.greenstone.gatherer.Dictionary;
     38import org.greenstone.gatherer.GAuthenticator;
    3439import org.greenstone.gatherer.Gatherer;
    35 import org.greenstone.gatherer.file.FileNode;
     40import org.greenstone.gatherer.collection.CollectionManager;
    3641import org.greenstone.gatherer.shell.GShell;
     42import org.greenstone.gatherer.util.Utility;
     43import org.greenstone.gatherer.util.ZipTools;
    3744
    3845
    3946public class RemoteGreenstoneServer
    4047{
    41     static public boolean deleteCollectionFile(String collection_name, File collection_file)
    42     {
    43     return true;
    44     }
    45 
    46 
    47     static public boolean downloadCollection(String collection_name)
    48     {
    49     return true;
    50     }
    51 
    52 
    53     static public boolean downloadCollectionConfigurations()
    54     {
    55     return true;
    56     }
    57 
    58 
    59     static public boolean downloadCollectionFile(String collection_name, File collection_file)
    60     {
    61     return true;
    62     }
    63 
    64 
    65     static public Boolean moveCollectionFile(String collection_name, File source_collection_file, File target_collection_file)
    66     {
    67     return null;
    68     }
    69 
    70 
    71     static public Boolean newCollectionDirectory(String collection_name, File new_collection_directory)
    72     {
    73     return null;
    74     }
    75 
    76 
    77     static public boolean uploadCollectionFile(String collection_name, File collection_file)
    78     {
    79     return true;
    80     }
    81 
    82 
    83     static public boolean uploadCollectionFiles(String collection_name, File[] collection_files)
    84     {
    85     return true;
    86     }
    87 
    88 
    89     static public Boolean uploadFilesIntoCollection(String collection_name, File[] source_files, File target_collection_directory)
    90     {
    91     return null;
    92     }
    93 
    94 
    95     static public void download_url_zip(String col_name, String dir, GShell source, String accept_expr, String reject_expr)
    96     {
    97     try {
    98         String download_cgi  = Gatherer.cgiBase + "download";
    99 
    100         // Send col_name and dir arguments to download cgi
    101         String col_name_encoded = URLEncoder.encode(col_name,"UTF-8");
    102         String dir_encoded = URLEncoder.encode(dir,"UTF-8");
    103         String cgi_args = "c=" + col_name_encoded;
    104         cgi_args += "&dir=" + dir_encoded + "&a=" + accept_expr + "&r=" + reject_expr;
    105 
    106         URL download_url = new URL(download_cgi);
    107 
    108         System.err.println("**** download cgi = '" + download_cgi + "'");
    109         System.err.println("**** cgi args = '" + cgi_args + "'");
    110 
    111         URLConnection dl_connection = download_url.openConnection();
    112         dl_connection.setDoOutput(true);       
    113         OutputStream dl_os = dl_connection.getOutputStream();
    114 
    115         PrintWriter dl_out = new PrintWriter(dl_os);
    116         dl_out.println(cgi_args);
    117         dl_out.close();
    118 
    119         // Download result from running cgi script
    120         InputStream dl_is = dl_connection.getInputStream();
    121         BufferedInputStream dl_bis = new BufferedInputStream(dl_is);
    122         DataInputStream dl_dbis = new DataInputStream(dl_bis);
    123            
    124         // set up output stream for zip download
    125         String col_dir;
    126         if (col_name.startsWith("/")) {
    127         col_dir = Configuration.gsdl_path;
     48    // ----------------------------------------------------------------------------------------------------
     49    //   PUBLIC LAYER
     50    // ----------------------------------------------------------------------------------------------------
     51
     52
     53    static public String deleteCollection(String collection_name)
     54    {
     55    return performAction(new RemoteGreenstoneServerDeleteCollectionAction(collection_name));
     56    }
     57
     58
     59    static public String deleteCollectionFile(String collection_name, File collection_file)
     60    {
     61    return performAction(new RemoteGreenstoneServerDeleteCollectionFileAction(collection_name, collection_file));
     62    }
     63
     64
     65    static public String downloadCollection(String collection_name)
     66    {
     67    return performAction(new RemoteGreenstoneServerDownloadCollectionAction(collection_name));
     68    }
     69
     70
     71    static public String downloadCollectionArchives(String collection_name)
     72    {
     73    return performAction(new RemoteGreenstoneServerDownloadCollectionArchivesAction(collection_name));
     74    }
     75
     76
     77    static public String downloadCollectionConfigurations()
     78    {
     79    return performAction(new RemoteGreenstoneServerDownloadCollectionConfigurationsAction());
     80    }
     81
     82
     83    static public String downloadCollectionFile(String collection_name, File collection_file)
     84    {
     85    return performAction(new RemoteGreenstoneServerDownloadCollectionFileAction(collection_name, collection_file));
     86    }
     87
     88
     89    static public String getScriptOptions(String script_name, String script_arguments)
     90    {
     91    return performAction(new RemoteGreenstoneServerGetScriptOptionsAction(script_name, script_arguments));
     92    }
     93
     94
     95    static public String moveCollectionFile(String collection_name, File source_collection_file, File target_collection_file)
     96    {
     97    return performAction(new RemoteGreenstoneServerMoveCollectionFileAction(collection_name, source_collection_file, target_collection_file));
     98    }
     99
     100
     101    static public String newCollectionDirectory(String collection_name, File new_collection_directory)
     102    {
     103    return performAction(new RemoteGreenstoneServerNewCollectionDirectoryAction(collection_name, new_collection_directory));
     104    }
     105
     106
     107    static public String runScript(String collection_name, String script_name, String script_arguments, GShell shell)
     108    {
     109    return performAction(new RemoteGreenstoneServerRunScriptAction(collection_name, script_name, script_arguments, shell));
     110    }
     111
     112
     113    static public String uploadCollectionFile(String collection_name, File collection_file)
     114    {
     115    return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, new File[] { collection_file }));
     116    }
     117
     118
     119    static public String uploadCollectionFiles(String collection_name, File[] collection_files)
     120    {
     121    return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, collection_files));
     122    }
     123
     124
     125    static public String uploadFilesIntoCollection(String collection_name, File[] source_files, File target_collection_directory)
     126    {
     127    return performAction(new RemoteGreenstoneServerUploadFilesIntoCollectionAction(collection_name, source_files, target_collection_directory));
     128    }
     129
     130
     131    // ----------------------------------------------------------------------------------------------------
     132
     133
     134    static public void exit()
     135    {
     136    System.err.println("Exiting, number of jobs on queue: " + remote_greenstone_server_action_queue.size());
     137
     138    // If there are still jobs on the queue we must wait for the jobs to finish
     139    while (remote_greenstone_server_action_queue.size() > 0) {
     140        synchronized (remote_greenstone_server_action_queue) {
     141        try {
     142            DebugStream.println("Waiting for queue to become empty...");
     143            remote_greenstone_server_action_queue.wait(500);
     144        }
     145        catch (InterruptedException exception) {}
     146        }
     147    }
     148    }
     149
     150
     151    // ----------------------------------------------------------------------------------------------------
     152    //   QUEUE LAYER
     153    // ----------------------------------------------------------------------------------------------------
     154
     155
     156    /** Returns null if we cannot wait for the action to finish, "" if the action failed, or the action output. */
     157    static private String performAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
     158    {
     159    // Add the action to the queue
     160    remote_greenstone_server_action_queue.addAction(remote_greenstone_server_action);
     161
     162    // If we're running in the GUI thread we must return immediately
     163    // We cannot wait for the action to complete because this will block any GUI updates
     164    if (SwingUtilities.isEventDispatchThread()) {
     165        System.err.println("WARNING: In event dispatch thread, returning immediately...");
     166        return null;
     167    }
     168
     169    // Otherwise wait until the action is processed
     170    while (!remote_greenstone_server_action.processed) {
     171        synchronized (remote_greenstone_server_action) {
     172        try {
     173            DebugStream.println("Waiting for action to complete...");
     174            remote_greenstone_server_action.wait(500);
     175        }
     176        catch (InterruptedException exception) {}
     177        }
     178    }
     179
     180    // Return "" if the action failed
     181    if (!remote_greenstone_server_action.processed_successfully) {
     182        return "";
     183    }
     184    // Otherwise return the action output
     185    return remote_greenstone_server_action.action_output;
     186    }
     187
     188
     189    static private RemoteGreenstoneServerActionQueue remote_greenstone_server_action_queue = new RemoteGreenstoneServerActionQueue();
     190
     191
     192    static private class RemoteGreenstoneServerActionQueue
     193    extends Thread
     194    {
     195    /** The queue of waiting jobs. */
     196    private ArrayList queue = null;
     197
     198
     199    public RemoteGreenstoneServerActionQueue()
     200    {
     201        if (Gatherer.isGsdlRemote) {
     202        queue = new ArrayList();
     203        start();
     204        }
     205    }
     206
     207
     208    synchronized public void addAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
     209    {
     210        queue.add(remote_greenstone_server_action);
     211        notifyAll();
     212    }
     213
     214
     215    public int size()
     216    {
     217        return queue.size();
     218    }
     219
     220
     221    public void run()
     222    {
     223        while (true) {
     224        // If there are jobs on the queue, get the next in line and process it
     225        if (queue.size() > 0) {
     226            RemoteGreenstoneServerAction remote_greenstone_server_action = (RemoteGreenstoneServerAction) queue.get(0);
     227
     228            try {
     229            remote_greenstone_server_action.perform();
     230
     231            // No exceptions were thrown, so the action was successful
     232            remote_greenstone_server_action.processed_successfully = true;
     233            }
     234            catch (RemoteGreenstoneServerActionCancelledException exception) {
     235            remote_greenstone_server_action.processed_successfully = false;
     236            }
     237            catch (Exception exception) {
     238            DebugStream.printStackTrace(exception);
     239            JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", exception.getMessage()), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
     240            remote_greenstone_server_action.processed_successfully = false;
     241            }
     242
     243            // We're done with this action, for better or worse
     244            remote_greenstone_server_action.processed = true;
     245            progress_bar.setAction(null);
     246            queue.remove(0);
     247        }
     248
     249        // Otherwise the queue is empty
     250        else {
     251            // Wait until we are notify()ed by addAction that there is a new job on the queue
     252            synchronized (this) {
     253            try {
     254                wait();
     255            }
     256            catch (InterruptedException exception) { }
     257            }
     258        }
     259        }
     260    }
     261    }
     262
     263
     264    // ----------------------------------------------------------------------------------------------------
     265    //   PROGRESS BAR
     266    // ----------------------------------------------------------------------------------------------------
     267
     268
     269    static private RemoteGreenstoneServerProgressBar progress_bar = new RemoteGreenstoneServerProgressBar();
     270
     271
     272    static private class RemoteGreenstoneServerProgressBar
     273    extends JProgressBar
     274    {
     275    public RemoteGreenstoneServerProgressBar()
     276    {
     277        setBackground(Configuration.getColor("coloring.collection_tree_background", false));
     278        setForeground(Configuration.getColor("coloring.collection_tree_foreground", false));
     279        setString(Dictionary.get("FileActions.No_Activity"));
     280        setStringPainted(true);
     281    }
     282
     283
     284    public void setAction(String action)
     285    {
     286        if (action != null) {
     287        DebugStream.println(action);
     288        }
     289
     290        // We cannot call this from the GUI thread otherwise the progress bar won't start
     291        if (SwingUtilities.isEventDispatchThread()) {
     292        System.err.println("ERROR: RemoteGreenstoneServerProgressBar.setAction() called from event dispatch thread!");
     293        return;
     294        }
     295
     296        // Set the string on the progress bar, and start or stop it
     297        if (action == null) {
     298        setString(Dictionary.get("FileActions.No_Activity"));
     299        setIndeterminate(false);
    128300        }
    129301        else {
    130         col_dir = Gatherer.getCollectDirectoryPath();
    131         }
    132 
    133         String zip_fname = col_dir + col_name + ".zip";
    134         FileOutputStream zip_fos = new FileOutputStream(zip_fname);
     302        setString(action);
     303        setIndeterminate(true);
     304        }
     305    }
     306    }
     307
     308
     309    static public RemoteGreenstoneServerProgressBar getProgressBar()
     310    {
     311    return progress_bar;
     312    }
     313
     314
     315    // ----------------------------------------------------------------------------------------------------
     316    //   ACTIONS
     317    // ----------------------------------------------------------------------------------------------------
     318
     319
     320    static private abstract class RemoteGreenstoneServerAction
     321    {
     322    public String action_output = null;
     323    public boolean processed = false;
     324    public boolean processed_successfully;
     325
     326    abstract public void perform()
     327        throws Exception;
     328    }
     329
     330
     331    static private class RemoteGreenstoneServerActionCancelledException
     332    extends Exception
     333    {
     334    }
     335
     336
     337    /**
     338     * --------------------------------------------------------------------------------------------
     339     *    DELETE COLLECTION
     340     * --------------------------------------------------------------------------------------------
     341     */
     342    static private class RemoteGreenstoneServerDeleteCollectionAction
     343    extends RemoteGreenstoneServerAction
     344    {
     345    private String collection_name;
     346
     347    public RemoteGreenstoneServerDeleteCollectionAction(String collection_name)
     348    {
     349        this.collection_name = collection_name;
     350    }
     351
     352    public void perform()
     353        throws Exception
     354    {
     355        progress_bar.setAction("Deleting collection " + collection_name + "...");
     356
     357        String delete_collection_command = "cmd=delete-collection";
     358        delete_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     359        action_output = sendCommandToServer(delete_collection_command, null);
     360    }
     361    }
     362
     363
     364    /**
     365     * --------------------------------------------------------------------------------------------
     366     *    DELETE COLLECTION FILE
     367     * --------------------------------------------------------------------------------------------
     368     */
     369    static private class RemoteGreenstoneServerDeleteCollectionFileAction
     370    extends RemoteGreenstoneServerAction
     371    {
     372    private String collection_name;
     373    private File collection_file;
     374
     375    public RemoteGreenstoneServerDeleteCollectionFileAction(String collection_name, File collection_file)
     376    {
     377        this.collection_name = collection_name;
     378        this.collection_file = collection_file;
     379    }
     380
     381    public void perform()
     382        throws Exception
     383    {
     384        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     385        String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
     386        collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     387        progress_bar.setAction("Deleting collection file " + collection_file_relative_path + "...");
     388
     389        String delete_collection_file_command = "cmd=delete-collection-file";
     390        delete_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     391        delete_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
     392        action_output = sendCommandToServer(delete_collection_file_command, null);
     393    }
     394    }
     395
     396
     397    /**
     398     * --------------------------------------------------------------------------------------------
     399     *    DOWNLOAD COLLECTION
     400     * --------------------------------------------------------------------------------------------
     401     */
     402    static private class RemoteGreenstoneServerDownloadCollectionAction
     403    extends RemoteGreenstoneServerAction
     404    {
     405    private String collection_name;
     406
     407    public RemoteGreenstoneServerDownloadCollectionAction(String collection_name)
     408    {
     409        this.collection_name = collection_name;
     410    }
     411
     412    public void perform()
     413        throws Exception
     414    {
     415        progress_bar.setAction("Downloading remote collection " + collection_name + "...");
     416
     417        String download_collection_command = "cmd=download-collection";
     418        download_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     419        String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + ".zip";
     420        action_output = downloadFile(download_collection_command, zip_file_path);
     421
     422        // Delete the existing (local) collection
     423        Gatherer.c_man.deleteCollection(collection_name);
     424
     425        // Unzip the collection just downloaded
     426        ZipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
     427    }
     428    }
     429
     430
     431    /**
     432     * --------------------------------------------------------------------------------------------
     433     *    DOWNLOAD COLLECTION ARCHIVES
     434     * --------------------------------------------------------------------------------------------
     435     */
     436    static private class RemoteGreenstoneServerDownloadCollectionArchivesAction
     437    extends RemoteGreenstoneServerAction
     438    {
     439    private String collection_name;
     440
     441    public RemoteGreenstoneServerDownloadCollectionArchivesAction(String collection_name)
     442    {
     443        this.collection_name = collection_name;
     444    }
     445
     446    public void perform()
     447        throws Exception
     448    {
     449        progress_bar.setAction("Downloading collection archives for " + collection_name + "...");
     450
     451        String download_collection_archives_command = "cmd=download-collection-archives";
     452        download_collection_archives_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     453        String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + "-archives.zip";
     454        action_output = downloadFile(download_collection_archives_command, zip_file_path);
     455
     456        // Delete the existing (local) collection archives
     457        Utility.delete(new File(Gatherer.c_man.getCollectionArchivesDirectoryPath()));
     458
     459        // Unzip the collection archives just downloaded
     460        ZipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
     461    }
     462    }
     463
     464
     465    /**
     466     * --------------------------------------------------------------------------------------------
     467     *    DOWNLOAD COLLECTION CONFIGURATIONS
     468     * --------------------------------------------------------------------------------------------
     469     */
     470    static private class RemoteGreenstoneServerDownloadCollectionConfigurationsAction
     471    extends RemoteGreenstoneServerAction
     472    {
     473    public RemoteGreenstoneServerDownloadCollectionConfigurationsAction()
     474    {
     475    }
     476
     477    public void perform()
     478        throws Exception
     479    {
     480        progress_bar.setAction("Downloading collection configurations...");
     481
     482        // Delete the existing (local) collect directory
     483        Utility.delete(new File(Gatherer.getCollectDirectoryPath()));
     484        new File(Gatherer.getCollectDirectoryPath()).mkdirs();
     485
     486        String download_collection_configurations_command = "cmd=download-collection-configurations";
     487        String zip_file_path = Gatherer.getCollectDirectoryPath() + "collections.zip";
     488        action_output = downloadFile(download_collection_configurations_command, zip_file_path);
     489
     490        // Unzip the collection configurations just downloaded
     491        ZipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
     492    }
     493    }
     494
     495
     496    /**
     497     * --------------------------------------------------------------------------------------------
     498     *    DOWNLOAD COLLECTION FILE
     499     * --------------------------------------------------------------------------------------------
     500     */
     501    static private class RemoteGreenstoneServerDownloadCollectionFileAction
     502    extends RemoteGreenstoneServerAction
     503    {
     504    private String collection_name;
     505    private File collection_file;
     506
     507    public RemoteGreenstoneServerDownloadCollectionFileAction(String collection_name, File collection_file)
     508    {
     509        this.collection_name = collection_name;
     510        this.collection_file = collection_file;
     511    }
     512
     513    public void perform()
     514        throws Exception
     515    {
     516        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     517        String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
     518        collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     519        progress_bar.setAction("Downloading collection file " + collection_file_relative_path + "...");
     520
     521        String download_collection_file_command = "cmd=download-collection-file";
     522        download_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     523        download_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
     524        String zip_file_name = collection_name + "-" + collection_file.getName() + ".zip";
     525        String zip_file_path = collection_directory_path + zip_file_name;
     526        action_output = downloadFile(download_collection_file_command, zip_file_path);
     527
     528        // Unzip the collection file just downloaded
     529        ZipTools.unzipFile(zip_file_path, collection_directory_path);
     530    }
     531    }
     532
     533
     534    /**
     535     * --------------------------------------------------------------------------------------------
     536     *    GET SCRIPT OPTIONS
     537     * --------------------------------------------------------------------------------------------
     538     */
     539    static private class RemoteGreenstoneServerGetScriptOptionsAction
     540    extends RemoteGreenstoneServerAction
     541    {
     542    private String script_name;
     543    private String script_arguments;
     544
     545    public RemoteGreenstoneServerGetScriptOptionsAction(String script_name, String script_arguments)
     546    {
     547        this.script_name = script_name;
     548        this.script_arguments = script_arguments;
     549    }
     550
     551    public void perform()
     552        throws Exception
     553    {
     554        progress_bar.setAction("Getting options for " + script_name + "...");
     555
     556        String get_script_options_command = "cmd=get-script-options";
     557        get_script_options_command += "&script=" + script_name;
     558        get_script_options_command += "&xml=";
     559        get_script_options_command += "&language=" + Configuration.getLanguage();
     560        get_script_options_command += script_arguments;
     561        action_output = sendCommandToServer(get_script_options_command, null);
     562    }
     563    }
     564
     565
     566    /**
     567     * --------------------------------------------------------------------------------------------
     568     *    MOVE COLLECTION FILE
     569     * --------------------------------------------------------------------------------------------
     570     */
     571    static private class RemoteGreenstoneServerMoveCollectionFileAction
     572    extends RemoteGreenstoneServerAction
     573    {
     574    private String collection_name;
     575    private File source_collection_file;
     576    private File target_collection_file;
     577
     578    public RemoteGreenstoneServerMoveCollectionFileAction(String collection_name, File source_collection_file, File target_collection_file)
     579    {
     580        this.collection_name = collection_name;
     581        this.source_collection_file = source_collection_file;
     582        this.target_collection_file = target_collection_file;
     583    }
     584
     585    public void perform()
     586        throws Exception
     587    {
     588        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     589        String source_collection_file_relative_path = getPathRelativeToDirectory(source_collection_file, collection_directory_path);
     590        source_collection_file_relative_path = source_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     591        String target_collection_file_relative_path = getPathRelativeToDirectory(target_collection_file, collection_directory_path);
     592        target_collection_file_relative_path = target_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     593        progress_bar.setAction("Moving file " + source_collection_file_relative_path + " -> " + target_collection_file_relative_path + "...");
     594
     595        String move_collection_file_command = "cmd=move-collection-file";
     596        move_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     597        move_collection_file_command += "&source=" + URLEncoder.encode(source_collection_file_relative_path, "UTF-8");
     598        move_collection_file_command += "&target=" + URLEncoder.encode(target_collection_file_relative_path, "UTF-8");
     599        action_output = sendCommandToServer(move_collection_file_command, null);
     600    }
     601    }
     602
     603
     604    /**
     605     * --------------------------------------------------------------------------------------------
     606     *    NEW COLLECTION DIRECTORY
     607     * --------------------------------------------------------------------------------------------
     608     */
     609    static private class RemoteGreenstoneServerNewCollectionDirectoryAction
     610    extends RemoteGreenstoneServerAction
     611    {
     612    private String collection_name;
     613    private File new_collection_directory;
     614
     615    public RemoteGreenstoneServerNewCollectionDirectoryAction(String collection_name, File new_collection_directory)
     616    {
     617        this.collection_name = collection_name;
     618        this.new_collection_directory = new_collection_directory;
     619    }
     620
     621    public void perform()
     622        throws Exception
     623    {
     624        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     625        String new_collection_directory_relative_path = getPathRelativeToDirectory(new_collection_directory, collection_directory_path);
     626        new_collection_directory_relative_path = new_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     627        progress_bar.setAction("Creating new directory " + new_collection_directory_relative_path + "...");
     628
     629        String new_collection_directory_command = "cmd=new-collection-directory";
     630        new_collection_directory_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     631        new_collection_directory_command += "&directory=" + URLEncoder.encode(new_collection_directory_relative_path, "UTF-8");
     632        action_output = sendCommandToServer(new_collection_directory_command, null);
     633    }
     634    }
     635
     636
     637    /**
     638     * --------------------------------------------------------------------------------------------
     639     *    RUN SCRIPT
     640     * --------------------------------------------------------------------------------------------
     641     */
     642    static private class RemoteGreenstoneServerRunScriptAction
     643    extends RemoteGreenstoneServerAction
     644    {
     645    private String collection_name;
     646    private String script_name;
     647    private String script_arguments;
     648    private GShell shell;
     649
     650    public RemoteGreenstoneServerRunScriptAction(String collection_name, String script_name, String script_arguments, GShell shell)
     651    {
     652        this.collection_name = collection_name;
     653        this.script_name = script_name;
     654        this.script_arguments = script_arguments;
     655        this.shell = shell;
     656    }
     657
     658    public void perform()
     659        throws Exception
     660    {
     661        progress_bar.setAction("Running " + script_name + "...");
     662
     663        String run_script_command = "cmd=run-script";
     664        run_script_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     665        run_script_command += "&script=" + script_name;
     666        run_script_command += "&language=" + Configuration.getLanguage();
     667        run_script_command += script_arguments;
     668        action_output = sendCommandToServer(run_script_command, shell);
     669    }
     670    }
     671
     672
     673    /**
     674     * --------------------------------------------------------------------------------------------
     675     *    UPLOAD COLLECTION FILE
     676     * --------------------------------------------------------------------------------------------
     677     */
     678    static private class RemoteGreenstoneServerUploadCollectionFilesAction
     679    extends RemoteGreenstoneServerAction
     680    {
     681    private String collection_name;
     682    private File[] collection_files;
     683
     684
     685    public RemoteGreenstoneServerUploadCollectionFilesAction(String collection_name, File[] collection_files)
     686    {
     687        this.collection_name = collection_name;
     688        this.collection_files = collection_files;
     689    }
     690
     691
     692    public void perform()
     693        throws Exception
     694    {
     695        progress_bar.setAction("Uploading collection files...");
     696
     697        // Determine the file paths relative to the collection directory
     698        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     699        String[] collection_file_relative_paths = new String[collection_files.length];
     700        for (int i = 0; i < collection_files.length; i++) {
     701        collection_file_relative_paths[i] = getPathRelativeToDirectory(collection_files[i], collection_directory_path);
     702        }
     703
     704        // Zip up the files to send to the server
     705        String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
     706        String zip_file_path = collection_directory_path + zip_file_name;
     707        ZipTools.zipFiles(zip_file_path, collection_directory_path, collection_file_relative_paths);
     708
     709        // Upload the zip file
     710        String upload_collection_file_command = "cmd=upload-collection-file";
     711        upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     712        upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
     713        upload_collection_file_command += "&directory=";
     714        upload_collection_file_command += "&zip=true";
     715        action_output = uploadFile(upload_collection_file_command, zip_file_path);
     716    }
     717    }
     718
     719
     720    /**
     721     * --------------------------------------------------------------------------------------------
     722     *    UPLOAD FILES INTO COLLECTION
     723     * --------------------------------------------------------------------------------------------
     724     */
     725    static private class RemoteGreenstoneServerUploadFilesIntoCollectionAction
     726    extends RemoteGreenstoneServerAction
     727    {
     728    private String collection_name;
     729    private File[] source_files;
     730    private File target_collection_directory;
     731
     732
     733    public RemoteGreenstoneServerUploadFilesIntoCollectionAction(String collection_name, File[] source_files, File target_collection_directory)
     734    {
     735        this.collection_name = collection_name;
     736        this.source_files = source_files;
     737        this.target_collection_directory = target_collection_directory;
     738    }
     739
     740
     741    public void perform()
     742        throws Exception
     743    {
     744        String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
     745        String target_collection_directory_relative_path = getPathRelativeToDirectory(target_collection_directory, collection_directory_path);
     746        target_collection_directory_relative_path = target_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
     747        progress_bar.setAction("Uploading files into collection...");
     748
     749        String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
     750        String zip_file_path = Gatherer.getCollectDirectoryPath() + zip_file_name;
     751        DebugStream.println("Zip file path: " + zip_file_path);
     752
     753        String base_directory_path = source_files[0].getParentFile().getAbsolutePath();
     754        DebugStream.println("Base directory path: " + base_directory_path);
     755        String[] source_file_relative_paths = new String[source_files.length];
     756        for (int i = 0; i < source_files.length; i++) {
     757        DebugStream.println("Source file path: " + source_files[i]);
     758        source_file_relative_paths[i] = getPathRelativeToDirectory(source_files[i], base_directory_path);
     759        }
     760
     761        ZipTools.zipFiles(zip_file_path, base_directory_path, source_file_relative_paths);
     762
     763        String upload_collection_file_command = "cmd=upload-collection-file";
     764        upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
     765        upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
     766        upload_collection_file_command += "&directory=" + URLEncoder.encode(target_collection_directory_relative_path, "UTF-8");
     767        upload_collection_file_command += "&zip=true";
     768        action_output = uploadFile(upload_collection_file_command, zip_file_path);
     769    }
     770    }
     771
     772
     773    // ----------------------------------------------------------------------------------------------------
     774    //   AUTHENTICATION LAYER
     775    // ----------------------------------------------------------------------------------------------------
     776
     777
     778    static private PasswordAuthentication remote_greenstone_server_authentication = null;
     779    // static private PasswordAuthentication remote_greenstone_server_authentication = new PasswordAuthentication(System.getProperty("user.name"), new char[] { });
     780
     781
     782    static private class RemoteGreenstoneServerAuthenticateTask
     783    extends Thread
     784    {
     785    public void run()
     786    {
     787        remote_greenstone_server_authentication = new RemoteGreenstoneServerAuthenticator().getAuthentication();
     788    }
     789
     790
     791    static private class RemoteGreenstoneServerAuthenticator
     792        extends GAuthenticator
     793    {
     794        public PasswordAuthentication getAuthentication()
     795        {
     796        return getPasswordAuthentication();
     797        }
     798
     799        protected String getMessageString()
     800        {
     801        return Dictionary.get("RemoteGreenstoneServer.Authentication_Message");
     802        }
     803    }
     804    }
     805
     806
     807    static private void authenticateUser()
     808    throws RemoteGreenstoneServerActionCancelledException
     809    {
     810    // If we don't have any authentication information then ask for it now
     811    if (remote_greenstone_server_authentication == null) {
     812        try {
     813        // We have to do this on the GUI thread
     814        SwingUtilities.invokeAndWait(new RemoteGreenstoneServerAuthenticateTask());
     815        }
     816        catch (Exception exception) {
     817        DebugStream.printStackTrace(exception);
     818        }
     819
     820        // If it is still null then the user has cancelled the authentication, so the action is cancelled
     821        if (remote_greenstone_server_authentication == null) {
     822        throw new RemoteGreenstoneServerActionCancelledException();
     823        }
     824    }
     825    }
     826
     827
     828    // ----------------------------------------------------------------------------------------------------
     829    //   REQUEST LAYER
     830    // ----------------------------------------------------------------------------------------------------
     831
     832
     833    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     834    static private String downloadFile(String gliserver_args, String file_path)
     835    throws Exception
     836    {
     837    while (true) {
     838        // Check that Configuration.gliserver_url is set
     839        if (Configuration.gliserver_url == null) {
     840        throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
     841        }
     842
     843        // Ask for authentication information (if necessary), then perform the action
     844        authenticateUser();
     845        String gliserver_url_string = Configuration.gliserver_url.toString();
     846        String command_output = downloadFileInternal(gliserver_url_string, gliserver_args, file_path);
     847
     848        // Check the first line to see if authentication has failed; if so, go around the loop again
     849        if (command_output.startsWith("ERROR: Authentication failed:")) {
     850        JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
     851        remote_greenstone_server_authentication = null;
     852        continue;
     853        }
     854        // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
     855        else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
     856        if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
     857            // The user has decided to cancel the action
     858            throw new RemoteGreenstoneServerActionCancelledException();
     859        }
     860
     861        // The user has decided to steal the lock... rerun the command with "&steal_lock="
     862        gliserver_args += "&steal_lock=";
     863        continue;
     864        }
     865        // Handle other types of errors by throwing an exception
     866        else if (command_output.startsWith("ERROR: ")) {
     867        throw new Exception(command_output.substring("ERROR: ".length()));
     868        }
     869
     870        // There were no exceptions thrown so the action must have succeeded
     871        return command_output;
     872    }
     873    }
     874
     875
     876    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     877    static private String sendCommandToServer(String gliserver_args, GShell shell)
     878    throws Exception
     879    {
     880    while (true) {
     881        // Check that Configuration.gliserver_url is set
     882        if (Configuration.gliserver_url == null) {
     883        throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
     884        }
     885
     886        // Ask for authentication information (if necessary), then perform the action
     887        authenticateUser();
     888        String gliserver_url_string = Configuration.gliserver_url.toString();
     889        String command_output = sendCommandToServerInternal(gliserver_url_string, gliserver_args, shell);
     890        // System.err.println("Command output: " + command_output);
     891
     892        // Check the first line to see if authentication has failed; if so, go around the loop again
     893        if (command_output.startsWith("ERROR: Authentication failed:")) {
     894        JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
     895        remote_greenstone_server_authentication = null;
     896        continue;
     897        }
     898        // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
     899        else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
     900        if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
     901            // The user has decided to cancel the action
     902            throw new RemoteGreenstoneServerActionCancelledException();
     903        }
     904
     905        // The user has decided to steal the lock... rerun the command with "&steal_lock="
     906        gliserver_args += "&steal_lock=";
     907        continue;
     908        }
     909        // Handle other types of errors by throwing an exception
     910        else if (command_output.startsWith("ERROR: ")) {
     911        throw new Exception(command_output.substring("ERROR: ".length()));
     912        }
     913
     914        // There were no exceptions thrown so the action must have succeeded
     915        return command_output;
     916    }
     917    }
     918
     919
     920    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     921    static private String uploadFile(String gliserver_args, String file_path)
     922    throws Exception
     923    {
     924    while (true) {
     925        // Check that Configuration.gliserver_url is set
     926        if (Configuration.gliserver_url == null) {
     927        throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
     928        }
     929
     930        // Ask for authentication information (if necessary), then perform the action
     931        authenticateUser();
     932        String gliserver_url_string = Configuration.gliserver_url.toString();
     933        String command_output = uploadFileInternal(gliserver_url_string, gliserver_args, file_path);
     934        // System.err.println("Command output: " + command_output);
     935
     936        // Check the first line to see if authentication has failed; if so, go around the loop again
     937        if (command_output.startsWith("ERROR: Authentication failed:")) {
     938        JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
     939        remote_greenstone_server_authentication = null;
     940        continue;
     941        }
     942        // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
     943        else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
     944        if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
     945            // The user has decided to cancel the action
     946            throw new RemoteGreenstoneServerActionCancelledException();
     947        }
     948
     949        // The user has decided to steal the lock... rerun the command with "&steal_lock="
     950        gliserver_args += "&steal_lock=";
     951        continue;
     952        }
     953        // Handle other types of errors by throwing an exception
     954        else if (command_output.startsWith("ERROR: ")) {
     955        throw new Exception(command_output.substring("ERROR: ".length()));
     956        }
     957
     958        // There were no exceptions thrown so the action must have succeeded
     959        return command_output;
     960    }
     961    }
     962
     963
     964    // ----------------------------------------------------------------------------------------------------
     965    //   NETWORK LAYER
     966    // ----------------------------------------------------------------------------------------------------
     967
     968
     969    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     970    static private String downloadFileInternal(String download_cgi, String cgi_args, String file_path)
     971    throws Exception
     972    {
     973    DebugStream.println("gliserver URL: " + download_cgi);
     974    System.err.println("gliserver args: " + cgi_args);
     975
     976    // Add username and password
     977    cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
     978    cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
     979
     980    URL download_url = new URL(download_cgi);
     981    URLConnection dl_connection = download_url.openConnection();
     982    dl_connection.setDoOutput(true);
     983    OutputStream dl_os = dl_connection.getOutputStream();
     984
     985    PrintWriter dl_out = new PrintWriter(dl_os);
     986    dl_out.println(cgi_args);
     987    dl_out.close();
     988
     989    // Download result from running cgi script
     990    InputStream dl_is = dl_connection.getInputStream();
     991    BufferedInputStream dl_bis = new BufferedInputStream(dl_is);
     992    DataInputStream dl_dbis = new DataInputStream(dl_bis);
     993
     994    String first_line = "";
     995    byte[] buf = new byte[1024];
     996    int len = dl_dbis.read(buf);
     997    if (len >= 0) {
     998        String first_chunk = new String(buf, 0, len);
     999        first_line = first_chunk.substring(0, ((first_chunk.indexOf("\n") != -1) ? first_chunk.indexOf("\n") : len));
     1000
     1001        // Save the data to file
     1002        FileOutputStream zip_fos = new FileOutputStream(file_path);
    1351003        BufferedOutputStream zip_bfos = new BufferedOutputStream(zip_fos);
    136        
    137         byte[] buf = new byte[1024];
    138         int len;
    139 
    140         while ((len = dl_dbis.read(buf)) >= 0 && !source.hasSignalledStop()) {
    141         zip_bfos.write(buf,0,len);
    142         }
    143 
    144         dl_dbis.close();
    145         dl_bis.close();
    146         dl_is.close();
     1004
     1005        while (len >= 0) {
     1006        zip_bfos.write(buf, 0, len);
     1007        len = dl_dbis.read(buf);
     1008        }
    1471009
    1481010        zip_bfos.close();
    1491011        zip_fos.close();
    150 
    151         if(source.hasSignalledStop()) {
    152         //A cancel has been called. Delete the zip file.
    153         DebugStream.println("download_url_zip() cancelled. Cleaning up.");
    154         if(new File(zip_fname).delete()) {
    155             DebugStream.println("Zip file " + zip_fname + " deleted");
     1012    }
     1013
     1014    dl_dbis.close();
     1015    dl_bis.close();
     1016    dl_is.close();
     1017    return first_line;
     1018    }
     1019
     1020
     1021    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     1022    static private String sendCommandToServerInternal(String gliserver_url_string, String cgi_args, GShell shell)
     1023    throws Exception
     1024    {
     1025    DebugStream.println("gliserver URL: " + gliserver_url_string);
     1026    System.err.println("gliserver args: " + cgi_args);
     1027
     1028    // Add username and password
     1029    cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
     1030        cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
     1031
     1032    URL gliserver_url = new URL(gliserver_url_string + "?" + cgi_args);
     1033    URLConnection gliserver_connection = gliserver_url.openConnection();
     1034
     1035    // Read the output of the command from the server, and return it
     1036    StringBuffer command_output_buffer = new StringBuffer(2048);
     1037    InputStream gliserver_is = gliserver_connection.getInputStream();
     1038    BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
     1039    String gliserver_output_line = gliserver_in.readLine();
     1040    while (gliserver_output_line != null) {
     1041        if (shell != null) {
     1042        shell.fireMessage(gliserver_output_line);
     1043        if (shell.hasSignalledStop()) {
     1044            throw new RemoteGreenstoneServerActionCancelledException();
    1561045        }
    157         else {
    158             DebugStream.println("Zip file " + zip_fname + " NOT deleted (no big deal). Does it exist?");
    159         }
    160         }
    161     }
    162     catch (Exception error) {
    163         error.printStackTrace();
    164     }
    165     DebugStream.println("Exited download_url_zip");
    166     }
    167 
    168 
    169     static public void upload_url_zip(String col_name, String dir, String delete_type, GShell source)
    170     {
    171     final String lineEnd = "\r\n";
    172     final String twoHyphens = "--";
    173     final String boundary =  "*****";
     1046        }
     1047        command_output_buffer.append(gliserver_output_line + "\n");
     1048        gliserver_output_line = gliserver_in.readLine();
     1049    }
     1050    gliserver_in.close();
     1051
     1052    return command_output_buffer.toString();
     1053    }
     1054
     1055
     1056    /** Returns the command output if the action completed, throws some kind of exception otherwise. */
     1057    static private String uploadFileInternal(String upload_cgi, String cgi_args, String file_path)
     1058    throws Exception
     1059    {
     1060    DebugStream.println("gliserver URL: " + upload_cgi);
     1061    System.err.println("gliserver args: " + cgi_args);
     1062
     1063    // Add username and password
     1064    cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
     1065    cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
     1066
     1067    // Open a HTTP connection to the URL
     1068    URL url = new URL(upload_cgi);
     1069    HttpURLConnection gliserver_connection = (HttpURLConnection) url.openConnection();
     1070
     1071    gliserver_connection.setDoInput(true);         // Allow Inputs
     1072    gliserver_connection.setDoOutput(true);        // Allow Outputs
     1073    gliserver_connection.setUseCaches(false);      // Don't use a cached copy.
     1074
     1075    gliserver_connection.setRequestProperty("Connection", "Keep-Alive");       
     1076
     1077    DataOutputStream dos = new DataOutputStream(gliserver_connection.getOutputStream());
     1078    dos.writeBytes(cgi_args + "\n");
     1079
     1080    // Send zip file to server
     1081    File file = new File(file_path);
     1082    FileInputStream fileInputStream = new FileInputStream(file);
     1083
     1084    // create a buffer of maximum size
    1741085    final int maxBufferSize = 1024;
    175 
    176     String col_dir;
    177     if (col_name.startsWith("/")) {
    178         col_dir = Configuration.gsdl_path;
    179     }
    180     else {
    181         col_dir = Gatherer.getCollectDirectoryPath();
    182     }
    183 
    184     String zip_fname = col_dir + col_name + ".zip";
    185     String upload_cgi = Gatherer.cgiBase + "upload";
    186 
    187     HttpURLConnection conn = null;
    188 
    189     try {
    190         // Send zip file to server
    191         File file = new File(zip_fname);
    192         FileInputStream fileInputStream = new FileInputStream(file);
    193 
    194         // open a URL connection to the Servlet
    195         URL url = new URL(upload_cgi);
    196         System.err.println("**** Uploading to: " + upload_cgi);
    197 
    198         // Open a HTTP connection to the URL
    199         conn = (HttpURLConnection) url.openConnection();
    200 
    201         conn.setDoInput(true);         // Allow Inputs
    202         conn.setDoOutput(true);        // Allow Outputs
    203         conn.setUseCaches(false);      // Don't use a cached copy.
    204         conn.setRequestMethod("POST"); // Use a post method.
    205 
    206         conn.setRequestProperty("Connection", "Keep-Alive");       
    207         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
    208 
    209         DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
    210 
    211         dos.writeBytes(twoHyphens + boundary + lineEnd);
    212         dos.writeBytes("Content-Disposition: form-data; name=\"c\"" + lineEnd + lineEnd);
    213         dos.writeBytes(col_name + lineEnd);
    214         System.err.println("**** c="+col_name);
    215 
    216         dos.writeBytes(twoHyphens + boundary + lineEnd);
    217         dos.writeBytes("Content-Disposition: form-data; name=\"dir\"" + lineEnd + lineEnd);
    218         dos.writeBytes(dir + lineEnd); 
    219         System.err.println("**** dir="+dir);
    220    
    221         dos.writeBytes(twoHyphens + boundary + lineEnd);
    222         dos.writeBytes("Content-Disposition: form-data; name=\"del\"" + lineEnd + lineEnd);
    223         dos.writeBytes(delete_type + lineEnd); 
    224         System.err.println("**** del="+delete_type);
    225 
    226         dos.writeBytes(twoHyphens + boundary + lineEnd);
    227         dos.writeBytes("Content-Disposition: form-data; name=\"zip\";"
    228                + " filename=\"" + zip_fname +"\"" + lineEnd);
    229         dos.writeBytes(lineEnd);
    230         System.err.println("**** zip (filename)="+zip_fname);
    231 
    232         // create a buffer of maximum size                 
    233         int bytesAvailable = fileInputStream.available();
    234         int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    235         byte[] buffer = new byte[bufferSize];
    236        
    237         // read file and write it into form...
    238         int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    239 
    240         while (bytesRead > 0) {
    241         // Check to see if action has been cancelled.
    242         if (source != null && source.hasSignalledStop()) {
    243             break;
    244         }
    245         dos.write(buffer, 0, bufferSize);
    246         bytesAvailable = fileInputStream.available();
    247         bufferSize = Math.min(bytesAvailable, maxBufferSize);
    248         bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    249         }
    250        
    251         // send multipart form data necesssary after file data...
    252        
    253         dos.writeBytes(lineEnd);
    254         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    255        
    256         // close streams
    257        
    258         fileInputStream.close();
    259         dos.flush();
    260         dos.close();
    261 
    262         // delete zip file
    263         boolean file_deleted = file.delete();
    264         if (file_deleted) {
    265         System.err.println("Zip file " + file.toString() + " deleted");
    266         }
    267         else {
    268         System.err.println("Zip file " + file.toString() + " NOT deleted");
    269         }
    270     }
    271     catch (MalformedURLException ex) {
    272         System.err.println("Failed on: "+ex);
    273     }
    274    
    275     catch (IOException ioe) {
    276         System.err.println("Failed on: "+ioe);
    277     }
    278    
    279     // Read server response
    280     try {
    281         InputStreamReader isr = new InputStreamReader(conn.getInputStream() );
    282         BufferedReader bisr = new BufferedReader (isr);
    283         String str;
    284         while (( str = bisr.readLine()) != null) {
    285         System.err.println(str);
    286         }
    287         bisr.close();
    288        
    289     }
    290     catch (IOException ioex) {
    291         System.err.println("From (ServerResponse): "+ioex);
    292     }
     1086    int bytesAvailable = fileInputStream.available();
     1087    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
     1088    byte[] buffer = new byte[bufferSize];
     1089
     1090    // read file and write it into form...
     1091    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
     1092    while (bytesRead > 0) {
     1093        dos.write(buffer, 0, bufferSize);
     1094        bytesAvailable = fileInputStream.available();
     1095        bufferSize = Math.min(bytesAvailable, maxBufferSize);
     1096        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
     1097    }
     1098
     1099    // close streams
     1100    fileInputStream.close();
     1101    dos.flush();
     1102    dos.close();
     1103
     1104    // Read the output of the command from the server, and return it
     1105    String command_output = "";
     1106    InputStream gliserver_is = gliserver_connection.getInputStream();
     1107    BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
     1108    String gliserver_output_line = gliserver_in.readLine();
     1109    while (gliserver_output_line != null) {
     1110        command_output += gliserver_output_line + "\n";
     1111        gliserver_output_line = gliserver_in.readLine();
     1112    }
     1113    gliserver_in.close();
     1114
     1115    return command_output;
     1116    }
     1117
     1118
     1119    // ----------------------------------------------------------------------------------------------------
     1120    //   UTILITIES
     1121    // ----------------------------------------------------------------------------------------------------
     1122
     1123
     1124    static private String getPathRelativeToDirectory(File file, String directory_path)
     1125    {
     1126    String file_path = file.getAbsolutePath();
     1127    if (!file_path.startsWith(directory_path)) {
     1128        System.err.println("ERROR: File path " + file_path + " is not a child of " + directory_path);
     1129        return file_path;
     1130    }
     1131
     1132    String relative_file_path = file_path.substring(directory_path.length());
     1133    if (relative_file_path.startsWith(File.separator)) {
     1134        relative_file_path = relative_file_path.substring(File.separator.length());
     1135    }
     1136    return relative_file_path;
    2931137    }
    2941138}
Note: See TracChangeset for help on using the changeset viewer.