Changeset 7739


Ignore:
Timestamp:
2004-07-16T13:48:18+12:00 (20 years ago)
Author:
davidb
Message:

General restructuring to allow GLI to be run as an applet.
Main area of change: making code look in the JAR file first
for a file rather than assume on local file system.
Stores data locally on system in '.gli' or Greenstone/GLI
folder in users home space for subsequent uses of applet.

Location:
trunk/gli/src/org/greenstone/gatherer
Files:
8 edited

Legend:

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

    r7696 r7739  
    6767    static final private String ARGUMENT_NAME = "name";
    6868    /** The name of the general Gatherer configuration file. */
    69     static final private String CONFIG_XML = "config.xml";
     69    static public String CONFIG_XML = "config.xml";
    7070    /** The name of the general Gatherer configuration file for running with GS3. */
    71     static final private String GS3_CONFIG_XML = "config3.xml";
     71    static public String GS3_CONFIG_XML = "config3.xml";
    7272
    7373    static final private String CURRENT_CONFIGURATION_VERSION = "2.51u";
     
    8787    static final private String OTHER_INFO = "Info";
    8888    /** The name of the general Gatherer configuration template. */
    89     static final private String TEMPLATE_CONFIG_XML = "xml/config.xml";
     89    static public String TEMPLATE_CONFIG_XML = "xml/config.xml";
    9090    /** The first of three patterns used during tokenization, this pattern handles a comma separated list. */
    9191    static final private String TOKENIZER_PATTERN1 = " ,\n\t";
     
    191191        Gatherer.println("exec_address != null -> " + exec_address);
    192192    }
     193
    193194    ///ystem.err.println("Perl path.");
    194195    this.perl_path = perl_path;
    195196    // Ensure the perl path includes exe under windoze
    196     if(Utility.isWindows() && !perl_path.toLowerCase().endsWith(".exe")) {
    197         if(!perl_path.endsWith(File.separator)) {
    198         perl_path = perl_path + File.separator;
    199         }
    200         perl_path = perl_path + "perl.exe";
     197    if (!Gatherer.isGsdlRemote) {
     198        if(Utility.isWindows() && !perl_path.toLowerCase().endsWith(".exe")) {
     199        if(!perl_path.endsWith(File.separator)) {
     200            perl_path = perl_path + File.separator;
     201        }
     202        perl_path = perl_path + "perl.exe";
     203        }
    201204    }
    202205
     
    215218        config_xml = new File(config_xml_name);
    216219        if(config_xml.exists()) {
    217         general_config = Utility.parse(config_xml_name, false);
     220        general_config = Utility.parse(config_xml_name, true);
    218221        }
    219222    }
  • trunk/gli/src/org/greenstone/gatherer/Gatherer.java

    r7679 r7739  
    2626 */
    2727package org.greenstone.gatherer;
    28 
    29 /**************************************************************************************
    30  * Written:      ??/??/02
    31  * Revised:      ??/??/02 - Commented
    32  *               ??/??/03 - Added support for local library server
    33  *               20/07/03 - Rewrote argument parsing so that spaces no longer cause GLI to die. Also added time out when starting local library.
    34  **************************************************************************************/
    3528
    3629//import com.l2fprod.gui.*;
     
    6760import sun.misc.*;
    6861
    69 /** Containing the main() method for the Gatherer, this class is the starting point for the rest of the application. It first parses the command line arguments, preparing to update the configuration as required. Next it loads several important support classes such as the Configuration and Dictionary. Finally it creates the other important managers and sends them on their way.
     62/** Containing the top-level "core" for the Gatherer, this class is the
     63 * common core for the GLI application and applet. It first parses the
     64 * command line arguments, preparing to update the configuration as
     65 * required. Next it loads several important support classes such as the
     66 * Configuration and Dictionary. Finally it creates the other important
     67 * managers and sends them on their way.
    7068 * @author John Thompson, Greenstone Digital Library, University of Waikato
    7169 * @version 2.3
     
    122120    static public boolean GS3 = false;
    123121
     122    static public boolean isGsdlRemote = false;
     123    static public String cgiBase = "";
     124
    124125    // feedback stuff
    125126    /** is the feedback feature enabled? */
     
    139140    }
    140141
    141     public Gatherer() {
     142    public Gatherer()
     143    {
    142144    this.self = this;
    143     }
    144 
    145     /** Run method. Make the three main modules, c_man, f_man and g_man, and any other necessary classes such as Dictionary.
    146      * @param size The desired size of the Gatherer window as a <strong>Dimension</strong>.
    147      * @param gsdl_path The path to the gsdl directory, gathered from the startup arguments, and presented as a <strong>String</strong>.
    148      * @param gsdl3_path The path to the gsdl3 directory, gathered from the startup arguments, and presented as a <strong>String</strong>.
    149      * @param exec_path The path to the library executable, gathered from the startup arguments, and presented as a <strong>String</strong>.
    150      * @param debug_enabled <i>true</i> to print verbose debug messages to "debug.txt", <i>false</i> otherwise.
    151      * @param perl_path The path to the PERL compiler as a <strong>String</strong>. Necessary for windows platform versions.
    152      * @param no_load <i>true</i> to prevent the previously opened collection from reopening.
    153      * @param splash A reference to the splash screen.
    154      * @param open_collection
    155      * @param mirroring_enabled
    156      * @param wget_version_str
    157      * @param wget_path
    158      * @see java.io.FileOutputStream
    159      * @see java.io.PrintStream
    160      * @see java.lang.Exception
    161      * @see java.lang.StringBuffer
    162      * @see java.util.Calendar
    163      * @see org.greenstone.gatherer.Configuration
    164      * @see org.greenstone.gatherer.Dictionary
    165      * @see org.greenstone.gatherer.Gatherer.CTRLCHandler
    166      * @see org.greenstone.gatherer.GAuthenticator
    167      * @see org.greenstone.gatherer.collection.CollectionManager
    168      * @see org.greenstone.gatherer.file.FileManager
    169      * @see org.greenstone.gatherer.gui.GUIManager
    170      * @see org.greenstone.gatherer.gui.Splash
    171      */
    172     public void run(Dimension size, String gsdl_path, String gsdl3_path, String exec_path, boolean debug_enabled, String perl_path, boolean no_load, Splash splash, String open_collection, String site_name, String servlet_path, boolean mirroring_enabled, String wget_version_str, String wget_path) {
     145
     146    init_images();
     147    }
     148
     149    protected void init_images()
     150    {
     151    Class base = this.getClass();
     152    Utility.BLANK_ICON = new ImageIcon(base.getResource("/images/blank.gif"));
     153    Utility.ERROR_ICON = new ImageIcon(base.getResource("/images/error.gif"));
     154    Utility.HELP_ICON  = new ImageIcon(base.getResource("/images/help.gif"));
     155    Utility.ON_ICON    = new ImageIcon(base.getResource("/images/check.gif"));
     156    Utility.OFF_ICON   = new ImageIcon(base.getResource("/images/cross.gif"));
     157
     158    Utility.base = base;
     159    }
     160
     161
     162    public GUIManager init(Dimension size, String gsdl_path, String gsdl3_path,
     163               String exec_path, boolean debug_enabled, String perl_path,
     164               boolean no_load, String open_collection,
     165               String site_name, String servlet_path,
     166               boolean mirroring_enabled, String wget_version_str,
     167               String wget_path)
     168    {
    173169
    174170    // This will hopefully catch ctrl-c and terminate, and exit gracefully. However it is platform specific, and may not be supported by some JVMs.
     
    239235        }
    240236
    241         // Perl path is a little different as it is perfectly ok to start the Gatherer without providing a perl path
    242         boolean found_perl = false;
    243         if (config.perl_path != null) {
    244         // See if the file pointed to actually exists
    245         File perl_file = new File(config.perl_path);
    246         found_perl = perl_file.exists();
    247         perl_file = null;
    248         }
    249         if (config.perl_path == null || !found_perl) {
    250         // Run test to see if we can run perl as is.
    251         PerlTest perl_test = new PerlTest();
    252         if (perl_test.found()) {
    253             // If so replace the perl path with the system default (or null for unix).
    254             config.perl_path = perl_test.toString();
    255             found_perl = true;
    256         }
    257         }
    258         if (!found_perl) {
    259         // Time for an error message.
    260         missingPERL();
     237        if (Gatherer.isGsdlRemote) {
     238        Gatherer.println("Not checking for perl path/exe");
     239        }
     240        else {
     241        // Perl path is a little different as it is perfectly ok to
     242        // start the Gatherer without providing a perl path
     243        boolean found_perl = false;
     244        if (config.perl_path != null) {
     245            // See if the file pointed to actually exists
     246            File perl_file = new File(config.perl_path);
     247            found_perl = perl_file.exists();
     248            perl_file = null;
     249        }
     250        if (config.perl_path == null || !found_perl) {
     251            // Run test to see if we can run perl as is.
     252            PerlTest perl_test = new PerlTest();
     253            if (perl_test.found()) {
     254            // If so replace the perl path with the system
     255            // default (or null for unix).
     256            config.perl_path = perl_test.toString();
     257            found_perl = true;
     258            }
     259        }
     260        if (!found_perl) {
     261            // Time for an error message.
     262            missingPERL();
     263        }
    261264        }
    262265
     
    300303        config.setWGetVersion(wget_version_str);
    301304        }
    302         // Size and place the frame on the screen
    303         Rectangle bounds = config.getBounds("general.bounds", true);
    304         if (bounds == null) {
    305         // Choose a sensible default value
    306         bounds = new Rectangle(0, 0, 640, 480);
    307         }
    308 
    309         // Ensure width and height are reasonable
    310         size = bounds.getSize();
    311         if (size.width < 640) {
    312         size.width = 640;
    313         }
    314         else if (size.width > config.screen_size.width) {
    315         size.width = config.screen_size.width;
    316         }
    317         if (size.height < 480) {
    318         size.height = 480;
    319         }
    320         else if (size.height > config.screen_size.height) {
    321         size.height = config.screen_size.height;
    322         }
     305
    323306        // Set default font
    324307        setUIFont(config.getFont("general.font", true), config.getFont("general.tooltip_font", true));
     
    352335        }
    353336
    354         // Create GUI Manager (last) or else suffer the death of a thousand NPE's
    355         splash.toFront();
    356         g_man = new GUIManager(size);
    357         g_man.display();
    358 
    359         // Place the window in the desired location on the screen, if this is do-able (not under most linux window managers apparently. In fact you're lucky if they listen to any of your screen size requests).
    360         g_man.setLocation(bounds.x, bounds.y);
    361         g_man.setVisible(true);
    362 
    363         // After the window has been made visible, check that it is in the correct place
    364         // sometimes java places a window not in the correct place,
    365         // but with an offset. If so, we work out what the offset is
    366         // and change the desired location to take that into account
    367         Point location = g_man.getLocation();
    368         int x_offset = bounds.x - location.x;
    369         int y_offset = bounds.y - location.y;
    370         // If not, offset the window to move it into the correct location
    371         if (x_offset > 0 || y_offset > 0) {
    372         ///ystem.err.println("changing the location to "+(bounds.x + x_offset)+" "+ (bounds.y + y_offset));
    373         g_man.setLocation(bounds.x + x_offset, bounds.y + y_offset);
    374         }
    375 
    376         // The 'after-display' triggers several events which don't occur until after the visual components are actually available on screen. Examples of these would be the various html renderings, as they can't happen offscreen.
    377         g_man.afterDisplay();
    378 
     337    }
     338    catch (Exception error) {
     339        error.printStackTrace();
     340    }
     341
     342    // Create GUI Manager (last) or else suffer the death of a thousand NPE's
     343    g_man = new GUIManager(size);
     344
     345    return g_man;
     346    }
     347
     348
     349
     350    public void run(Dimension size, Splash splash, GUIManager g_man)
     351    {
     352    // Size and place the frame on the screen
     353    Rectangle bounds = config.getBounds("general.bounds", true);
     354    if (bounds == null) {
     355        // Choose a sensible default value
     356        bounds = new Rectangle(0, 0, 640, 480);
     357    }
     358   
     359    // Ensure width and height are reasonable
     360    size = bounds.getSize();
     361    if (size.width < 640) {
     362        size.width = 640;
     363    }
     364    else if (size.width > config.screen_size.width) {
     365        size.width = config.screen_size.width;
     366    }
     367    if (size.height < 480) {
     368        size.height = 480;
     369    }
     370    else if (size.height > config.screen_size.height) {
     371        size.height = config.screen_size.height;
     372    }
     373   
     374    if (splash != null) { splash.toFront(); }
     375
     376    g_man.display();
     377
     378    // Place the window in the desired location on the screen, if this is do-able (not under most linux window managers apparently. In fact you're lucky if they listen to any of your screen size requests).
     379    g_man.setLocation(bounds.x, bounds.y);
     380    g_man.setVisible(true);
     381
     382    // After the window has been made visible, check that it is in the correct place
     383    // sometimes java places a window not in the correct place,
     384    // but with an offset. If so, we work out what the offset is
     385    // and change the desired location to take that into account
     386    Point location = g_man.getLocation();
     387    int x_offset = bounds.x - location.x;
     388    int y_offset = bounds.y - location.y;
     389    // If not, offset the window to move it into the correct location
     390    if (x_offset > 0 || y_offset > 0) {
     391        ///ystem.err.println("changing the location to "+(bounds.x + x_offset)+" "+ (bounds.y + y_offset));
     392        g_man.setLocation(bounds.x + x_offset, bounds.y + y_offset);
     393    }
     394
     395    // The 'after-display' triggers several events which don't occur until after the visual components are actually available on screen. Examples of these would be the various html renderings, as they can't happen offscreen.
     396    g_man.afterDisplay();
     397
     398    if (splash != null) {
    379399        // Hide the splash screen
    380400        splash.hide();
     
    382402        splash = null;
    383403    }
    384     catch (Exception error) {
    385         error.printStackTrace();
    386     }
    387     }
     404    }
     405
    388406
    389407    /** Exits the Gatherer after ensuring that things needing saving are saved.
     
    444462
    445463    if(apps.size() == 0) {
    446         System.exit(0);
     464        if (!Gatherer.isGsdlRemote) {
     465        System.exit(0);
     466        }
    447467    }
    448468    else {
     
    543563        ///ystem.err.println("No browser command available.");
    544564    }
    545     }
    546    
    547     /** The entry point into the Gatherer. Parses arguments.
    548      * @param args A collection of arguments that may include: initial screen size, dictionary, path to the GSDL etc.
    549      * @see java.io.File
    550      * @see java.io.FileInputStream
    551      * @see java.lang.Exception
    552      * @see java.util.Properties
    553      * @see org.greenstone.gatherer.Dictionary
    554      * @see org.greenstone.gatherer.Gatherer
    555      * @see org.greenstone.gatherer.gui.Splash
    556      * @see org.greenstone.gatherer.util.StaticStrings
    557      */
    558     static public void main(String[] args) {
    559     // A serious hack, but its good enough to stop crappy 'Could not lock user prefs' error messages.
    560     // Thanks to Walter Schatz from the java forums.
    561     System.setProperty("java.util.prefs.syncInterval","2000000"); // One message every 600 hours!
    562 
    563     // Override the exception handler with a new one which we can easily quiet the exceptions from.
    564     // System.setProperty("sun.awt.exception.handler", "GLIExceptionHandler");
    565 
    566     // Ensure platform specific LAF
    567     try {
    568         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    569     }
    570     catch(Exception exception) {
    571         exception.printStackTrace();
    572     }
    573    
    574     Gatherer gatherer = new Gatherer();
    575     boolean debug = false;
    576     boolean feedback_enabled = false;
    577     boolean mirroring_enabled = false;
    578     boolean no_load = false;
    579     Dictionary dictionary = new Dictionary(null, null); // Default dictionary. Only used for starting error messages.
    580     Dimension size = new Dimension(800, 540);
    581     String exec_path = null;
    582     String extra = null;
    583     String filename = null;
    584     String gsdl_path = null;
    585     String gsdl3_path = null;
    586     String perl_path = null;
    587     String site_name = null; // for GS3
    588     String servlet_path = null;
    589     String wget_path = null;
    590     String wget_version_str = StaticStrings.NO_WGET_STR;
    591     // Parse arguments
    592     int argument_index = 0;
    593     String next_token = null;
    594     while(argument_index < args.length || next_token != null) {
    595         // 1. We start by attempting to parse an argument name. An argument must start with a '-', and should not contain spaces. If anything else is encountered it is ignored.
    596         String argument_name = null;
    597         if(next_token == null) {
    598         next_token = args[argument_index];
    599         argument_index++;
    600         }
    601         if(next_token.startsWith(StaticStrings.MINUS_CHARACTER)) {
    602         // Trim second '-' just to be kind to Unixy-type people
    603         if(next_token.startsWith(StaticStrings.MINUS_CHARACTER + StaticStrings.MINUS_CHARACTER)) {
    604             argument_name = next_token.substring(1);
    605         }
    606         else {
    607             argument_name = next_token;
    608         }
    609         }
    610         next_token = null;
    611         // 2. If we now have an argument name we continue by attempting to parse a value. A value is taken to be the sequence of space seperated Strings between the last argument name and up to but not including the next argument name. Of course an argument needn't have any value (ie -debug, -help), in which case value will be null.
    612         if(argument_name != null) {
    613         String argument_value = null;
    614         StringBuffer argument_value_buffer = new StringBuffer("");
    615         while(argument_index < args.length && next_token == null) {
    616             next_token = args[argument_index];
    617             argument_index++;
    618             // If we just parsed an arbitary String then append it to value, followed by a single space
    619             if(!next_token.startsWith(StaticStrings.MINUS_CHARACTER)) {
    620             argument_value_buffer.append(next_token);
    621             argument_value_buffer.append(StaticStrings.SPACE_CHARACTER);
    622             next_token = null;
    623             }
    624             // If the argument token retrieved is an argument name, then leave it in next_token, which will cause the argument parsing process to move onto the next step.
    625         }
    626         // If a value now exists in argument buffer, retrieve it. Remove the last character as it will be an erroneous space.
    627         if(argument_value_buffer.length() > 0) {
    628             argument_value = argument_value_buffer.substring(0, argument_value_buffer.length() - 1);
    629         }
    630        
    631         // 3. We now have the argument name, and any associated value. We are ready to store the data in the appropriate variables.
    632         Gatherer.println("Parsed Argument: name=" + argument_name + (argument_value != null ? (", value=" + argument_value) : ", no value"));
    633         // 3a. First those arguments that have no associated value
    634         if(argument_value == null) {
    635             if(argument_name.equals(StaticStrings.HELP_ARGUMENT)) {
    636             printUsage(dictionary);
    637             System.exit(0);
    638             }
    639             // Run GLI in debug mode. Produces debug log plus extra messages.
    640             else if(argument_name.equals(StaticStrings.DEBUG_ARGUMENT)) {
    641             debug = true;
    642             }
    643             // Run GLI with feedback enabled.
    644             else if(argument_name.equals(StaticStrings.FEEDBACK_ARGUMENT)) {
    645             feedback_enabled = true;
    646             }
    647             // Forces no loading on previous collection.
    648             else if(argument_name.equals(StaticStrings.NO_LOAD_ARGUMENT)) {
    649             no_load = true;
    650             filename = null;
    651             }
    652             // Run the GLI with mirroring enabled
    653             else if(argument_name.equals(StaticStrings.MIRROR_ARGUMENT)) {
    654             mirroring_enabled = true;
    655             }
    656             /* I've got a sneak suspicion Aqua look and feel is not free domain
    657                // Specify the use of Greenstone LAF.
    658                else if(argument_name.equals(StaticStrings.SKIN_ARGUMENT)) {
    659                // SkinLF
    660                try {
    661                SkinLookAndFeel.setSkin(SkinLookAndFeel.loadThemePackDefinition(SkinUtils.toURL(new File(SKIN_DEFINITION_FILE))));
    662                SkinLookAndFeel.enable();
    663                }
    664                catch (Exception error) {
    665                ///ystem.err.println("Error: " + error);
    666                error.printStackTrace();
    667                }
    668                }
    669             */
    670         }
    671         // 3b. Now for those that do
    672         else {
    673             // Parse the path to the GSDL. Required argument.
    674             if(argument_name.equals(StaticStrings.GSDL_ARGUMENT)) {
    675             if(argument_value.endsWith(File.separator)) {
    676                 gsdl_path = argument_value;
    677             }
    678             else {
    679                 gsdl_path = argument_value + File.separator;
    680             }
    681             }
    682             // GSDL3 path
    683             if(argument_name.equals(StaticStrings.GSDL3_ARGUMENT)) {
    684             if(argument_value.endsWith(File.separator)) {
    685                 gsdl3_path = argument_value;
    686             }
    687             else {
    688                 gsdl3_path = argument_value + File.separator;
    689             }
    690             }
    691             else if (argument_name.equals(StaticStrings.SITE_ARGUMENT)) {
    692             site_name = argument_value;
    693             }
    694             else if (argument_name.equals(StaticStrings.SERVLET_ARGUMENT)) {
    695             servlet_path = argument_value;
    696             }
    697             // Specify a collection to load initially. Could be used for file associations.
    698             else if(argument_name.equals(StaticStrings.LOAD_ARGUMENT)) {
    699             filename = argument_value;
    700             no_load = false;
    701             }
    702             // Parse the url to a running web server, or a file path to the local library server.
    703             else if(argument_name.equals(StaticStrings.LIBRARY_ARGUMENT)) {
    704             exec_path = argument_value;
    705             // If there is no colon in first five characters of the exec_path (which would either be an existing protocol, or a windows file path to say a local library), we can append the protocol http://.
    706             if(argument_value.lastIndexOf(StaticStrings.COLON_CHARACTER, 5) == -1) {
    707                 exec_path = StaticStrings.HTTP_PROTOCOL_STR + argument_value;
    708             }
    709             else {
    710                 exec_path = argument_value;
    711             }
    712             // If the user has given us an address, but it ends with a '/' we assume we're using the greenstone library.cgi
    713             if(exec_path.startsWith(StaticStrings.HTTP_PROTOCOL_STR) && exec_path.endsWith(StaticStrings.URL_SEPARATOR_CHARACTER)) {
    714                 exec_path = exec_path + StaticStrings.LIBRARY_STR;
    715             }
    716             }
    717             // Parse the path to PERL. If not provided its assumes perl should be availble on the PATH.
    718             else if(argument_name.equals(StaticStrings.PERL_ARGUMENT)) {
    719             perl_path = argument_value;
    720             // Test whether this points to the Perl bin directory or the Perl executable itself.
    721             File perl_file = new File(perl_path);
    722             if(perl_file.isDirectory()) {
    723                 // If this is windows we create a child file perl.exe, otherwise we create perl
    724                 if(Utility.isWindows()) {
    725                 perl_file = new File(perl_file, Utility.PERL_EXECUTABLE_WINDOWS);
    726                 }
    727                 else {
    728                 perl_file = new File(perl_file, Utility.PERL_EXECUTABLE_UNIX);
    729                 }
    730                 // And store this new path.
    731                 perl_path = perl_file.getAbsolutePath();
    732                 perl_file = null;
    733             }
    734             // Otherwise its fine as it is
    735             }
    736             // Test for the presence of a WGet version. This is only useful if the user has enabled mirroring. Note that mirroring can be enabled by running the GLI with -mirror, editing the config.xml for GLI, or through a new option on the connections page of the preferences.
    737             else if(argument_name.equals(StaticStrings.WGET_ARGUMENT)) {
    738             wget_version_str = StaticStrings.WGET_STR;
    739             wget_path = argument_value;
    740             }
    741         }
    742         }
    743         // Argument name was null, nothing to be done.
    744     }
    745     next_token = null;
    746     // Arguments all parsed.
    747 
    748     if (feedback_enabled) {
    749         // if feedback is enabled, set up the recorder dialog
    750         Locale currLocale = Locale.getDefault(); // use the default locale for now - this will be changed by the Gatherer run method
    751         ActionRecorderDialog dlg = new ActionRecorderDialog (currLocale);
    752         gatherer.feedback_enabled = true;
    753         gatherer.feedback_dialog = dlg;
    754     }
    755    
    756     // Splash screen.
    757     Splash splash = new Splash();
    758     // dictionary.destroy();
    759     gatherer.run(size, gsdl_path, gsdl3_path, exec_path, debug, perl_path, no_load, splash, filename, site_name, servlet_path, mirroring_enabled, wget_version_str, wget_path);
    760565    }
    761566
     
    901706    }
    902707    catch (Exception error) {
    903         Gatherer.println("config.xml is not a well formed XML document.");
     708        Gatherer.println(Configuration.CONFIG_XML+" is not a well formed XML document.");
    904709        Gatherer.printStackTrace(error);
    905710    }
     
    1164969            Gatherer.println("found mozilla or netscape, trying remote it");
    1165970            // mozilla and netscape, try using a remote command to get things in the same window
    1166             String [] new_commands = new String[] {prog_name, "-raise", "-remote", "openURL("+url+")"};
     971            String [] new_commands = new String[] {prog_name, "-raise", "-remote", "openURL("+url+",new-tab)"};
    1167972            if(debug != null) {
    1168973            printArray(new_commands);
     
    12711076    }
    12721077    }
    1273 
    1274 //      static public class GLIExceptionHandler {
    1275 //      public void handle(Throwable thrown) {
    1276 //          if(always_show_exceptions || debug != null) {
    1277 //          thrown.printStackTrace();
    1278 //          }
    1279 //      }
    1280 //      }
    12811078}
  • trunk/gli/src/org/greenstone/gatherer/cdm/CollectionDesignManager.java

    r7601 r7739  
    4444import org.greenstone.gatherer.cdm.TranslationView;
    4545import org.greenstone.gatherer.util.GSDLSiteConfig;
     46import org.greenstone.gatherer.util.Utility;
    4647
    4748/** This manager provides access to submanagers, which in turn provide tools for the designing of Greenstone collections via the information stored in etc/collect.cfg. This class acts as a hub for the managers that handle specific parts of the configuration such as classifiers, format strings and language settings.
     
    211212      ///ystem.err.println("Would have released collection if necessary.");
    212213      boolean collection_released = false;
    213       if(format_manager.formatsChanged() && Gatherer.c_man.built() && Gatherer.config.exec_file != null) {
     214      String col_name = Gatherer.c_man.getCollection().getName();
     215      boolean formats_changed = format_manager.formatsChanged();
     216
     217      if(formats_changed && Gatherer.c_man.built() && Gatherer.config.exec_file != null) {
    214218      // Release the collection
    215       Gatherer.self.configServer(GSDLSiteConfig.RELEASE_COMMAND + Gatherer.c_man.getCollection().getName());
     219      Gatherer.self.configServer(GSDLSiteConfig.RELEASE_COMMAND + col_name);
    216220      // This is very important -- it ensures that the above command has finished
    217221      Gatherer.self.configServer("");
     
    222226      collect_config.save();
    223227
     228      if (Gatherer.isGsdlRemote) {
     229      if(formats_changed && Gatherer.c_man.built()) {
     230          // upload etc/collect.cfg to server to reflect changes
     231          Utility.zipup(col_name,Utility.CONFIG_FILE);
     232          Utility.upload_url_zip(col_name,"etc");
     233      }
     234      }
     235
    224236      // Readd collection
    225237      ///ystem.err.println("Would have added collection if it had been released.");
    226238      if(collection_released) {
    227       // Then re-add it to force format commands to be processed
    228       Gatherer.self.configServer(GSDLSiteConfig.ADD_COMMAND + Gatherer.c_man.getCollection().getName());
     239      // Now re-add collection to server to force format commands to be processed
     240      Gatherer.self.configServer(GSDLSiteConfig.ADD_COMMAND + col_name);
    229241      // This is very important -- it ensures that the above command has finished
    230242      Gatherer.self.configServer("");
    231      // Unset formats changed
    232      format_manager.setFormatsChanged(false);
    233       }
    234     }
     243      }
     244
     245      if (formats_changed) {
     246      // Unset formats changed
     247      format_manager.setFormatsChanged(false);
     248      }
     249   }
    235250
    236251//     /** Ensures that the collection is now public. Useful for collections that are based on another, or that are about to be exported */
  • trunk/gli/src/org/greenstone/gatherer/collection/BuildOptions.java

    r7022 r7739  
    33import java.io.*;
    44import java.lang.ref.*;
     5import java.net.*;
    56import java.util.*;
    67import org.apache.xerces.parsers.DOMParser;
     
    377378    private Element loadArguments(String filename, String lang) {
    378379    Element arguments_element = null;
     380    InputStream input_stream = null;
     381
    379382    // Run the required program.
    380383    try {
    381384        String args[];
    382         if(Utility.isWindows()) {
    383         args = new String[6];
    384         args[0] = Gatherer.config.perl_path;
    385         args[1] = "-S";
    386         args[2] = Gatherer.config.getScriptPath() + filename;
    387         args[3] = "-xml";
    388         args[4] = "-language";
    389         args[5] = lang;
     385        if (Gatherer.isGsdlRemote) {
     386            String launch  = Gatherer.cgiBase + "launch";
     387            launch += "?cmd=" + filename;
     388            launch += "&xml=&language="+lang;
     389
     390            System.err.println("*** launch = " + launch);
     391
     392            URL launch_url = new URL(launch);
     393            URLConnection launch_connection = launch_url.openConnection();
     394            input_stream = launch_connection.getInputStream();
    390395        }
    391396        else {
    392         args = new String[4];
    393         args[0] = Gatherer.config.getScriptPath() + filename;
    394         args[1] = "-xml";
    395         args[2] = "-language";
    396         args[3] = lang;
    397         }
    398         // Create the process.
    399         Runtime runtime = Runtime.getRuntime();
    400         Process process = runtime.exec(args);
    401         //InputStream input_stream = process.getErrorStream();
    402         InputSource source = new InputSource(new InputStreamReader(process.getErrorStream(), "UTF-8"));
    403         DOMParser parser = new DOMParser();
    404         parser.parse(source);
    405         Document document = parser.getDocument();
     397        if(Utility.isWindows()) {
     398            args = new String[6];
     399            args[0] = Gatherer.config.perl_path;
     400            args[1] = "-S";
     401            args[2] = Gatherer.config.getScriptPath() + filename;
     402            args[3] = "-xml";
     403            args[4] = "-language";
     404            args[5] = lang;
     405        }
     406        else {
     407            args = new String[4];
     408            args[0] = Gatherer.config.getScriptPath() + filename;
     409            args[1] = "-xml";
     410            args[2] = "-language";
     411            args[3] = lang;
     412        }
     413
     414        // Create the process.
     415        Runtime runtime = Runtime.getRuntime();
     416        Process process = runtime.exec(args);
     417
     418        input_stream = process.getErrorStream();
     419        }
     420
     421        Document document = Utility.parse(input_stream,false);
     422
     423        //DOMParser parser = new DOMParser();
     424        //parser.parse(source);
     425        //Document document = parser.getDocument();
    406426        arguments_element = document.getDocumentElement();
    407427    }
  • trunk/gli/src/org/greenstone/gatherer/collection/CollectionManager.java

    r7605 r7739  
    158158
    159159    String args[];
    160     if(Utility.isWindows()) {
    161         args = new String[9];
     160    if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
     161        args = new String[8];
    162162        args[0] = Gatherer.config.perl_path;
    163163        args[1] = "-S";
     
    168168        args[6] = "-collectdir";
    169169        args[7] = collect_dir;
    170         args[8] = collection.getName();
    171170    }
    172171    else {
    173         args = new String[7];
     172        args = new String[6];
    174173        args[0] = Gatherer.config.getScriptPath() + "buildcol.pl";
    175174        args[1] = "-gli";
     
    178177        args[4] = "-collectdir";
    179178        args[5] = collect_dir;
    180         args[6] = collection.getName();
    181179    }
    182180    args = ArrayTools.add(args, collection.build_options.getBuildValues());
     181    args = ArrayTools.add(args, collection.getName());
    183182    GShell shell = new GShell(args, GShell.BUILD, BUILDING, this, build_monitor, GShell.GSHELL_BUILD);
    184183    shell.addGShellListener(Gatherer.g_man.create_pane);
     
    259258    String collect_dir = getCollectDirectory();
    260259   
    261     if(Utility.isWindows()) {
     260    if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
    262261        command = new String[6];
    263262        command[0] = Gatherer.config.perl_path;
     
    338337        makeCollection(description, email, name, title);
    339338        progress.setProgress(1);
    340         // *******************8
     339        // *******************
    341340        String a_dir;
    342341        if (Gatherer.GS3) {
     
    837836        String args[];
    838837        String lang = Gatherer.config.getLanguage();
    839         if(Utility.isWindows()) {
    840         args = new String[9];
     838        if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
     839        args = new String[8];
    841840        args[0] = Gatherer.config.perl_path;
    842841        args[1] = "-S";
     
    847846        args[6] = "-collectdir";
    848847        args[7] = collect_dir;
    849         args[8] = collection.getName();
    850848        }
    851849        else {
    852         args = new String[7];
     850        args = new String[6];
    853851        args[0] = Gatherer.config.getScriptPath() + "import.pl";
    854852        args[1] = "-gli";
     
    857855        args[4] = "-collectdir";
    858856        args[5] = collect_dir;
    859         args[6] = collection.getName();
    860857        }
    861858        collect_dir = null;
    862859        args = ArrayTools.add(args, collection.build_options.getImportValues());
     860        args = ArrayTools.add(args, collection.getName());
     861
    863862        GShell shell = new GShell(args, GShell.IMPORT, BUILDING, this, import_monitor, GShell.GSHELL_IMPORT);
    864863        shell.addGShellListener(Gatherer.g_man.create_pane);
     
    10431042    // Run the mkcol command.
    10441043    String command[];
    1045     if(Utility.isWindows()) {
     1044    if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
    10461045        if(description == null || title == null) {
    1047         command = new String[6];
     1046        command = new String[8];
    10481047        command[0] = Gatherer.config.perl_path;
    10491048        command[1] = "-S";
     
    10511050        command[3] = "-collectdir";
    10521051        command[4] = collect_dir;
    1053         command[5] = name;
     1052        command[5] = "-win31compat";
     1053        command[6] = (Gatherer.isGsdlRemote) ? "false" : "true";
     1054        command[7] = name;
    10541055        }
    10551056        // Users are no longer required to supply an email
    10561057        else if(email == null) {
    1057         command = new String[10];
    1058         command[0] = Gatherer.config.perl_path;
    1059         command[1] = "-S";
    1060         command[2] = Gatherer.config.getScriptPath() + "mkcol.pl";
    1061         command[3] = "-collectdir";
    1062         command[4] = collect_dir;
    1063         command[5] = "-title";
    1064         command[6] = title;
    1065         command[7] = "-about";
    1066         command[8] = description;
    1067         command[9] = name;
    1068         }
    1069         else {
    10701058        command = new String[12];
    10711059        command[0] = Gatherer.config.perl_path;
     
    10741062        command[3] = "-collectdir";
    10751063        command[4] = collect_dir;
     1064        command[5] = "-win31compat";
     1065        command[6] = (Gatherer.isGsdlRemote) ? "false" : "true";
     1066        command[7] = "-title";
     1067        command[8] = title;
     1068        command[9] = "-about";
     1069        command[10] = description;
     1070        command[11] = name;
     1071        }
     1072        else {
     1073        command = new String[14];
     1074        command[0] = Gatherer.config.perl_path;
     1075        command[1] = "-S";
     1076        command[2] = Gatherer.config.getScriptPath() + "mkcol.pl";
     1077        command[3] = "-collectdir";
     1078        command[4] = collect_dir;
     1079        command[5] = "-win31compat";
     1080        command[6] = (Gatherer.isGsdlRemote) ? "false" : "true";
     1081        command[7] = "-title";
     1082        command[8] = title;
     1083        command[9] = "-creator";
     1084        command[10] = email;
     1085        command[11] = "-about";
     1086        command[12] = description;
     1087        command[13] = name;
     1088        }
     1089    }
     1090    else {
     1091        if(description == null || title == null) {
     1092        command = new String[6];
     1093        command[0] = "mkcol.pl";
     1094        command[1] = "-collectdir";
     1095        command[2] = collect_dir;
     1096        command[3] = "-win31compat";
     1097        command[4] = (Gatherer.isGsdlRemote) ? "false" : "true";
     1098        command[5] = name;
     1099        }
     1100        else if(email == null) {
     1101        command = new String[10];
     1102        command[0] = "mkcol.pl";
     1103        command[1] = "-collectdir";
     1104        command[2] = collect_dir;
     1105        command[3] = "-win31compat";
     1106        command[4] = (Gatherer.isGsdlRemote) ? "false" : "true";
     1107        command[5] = "-title";
     1108        command[6] = title;
     1109        command[7] = "-about";
     1110        command[8] = description;
     1111        command[9] = name;
     1112        }
     1113        else {
     1114        command = new String[12];
     1115        command[0] = "mkcol.pl";
     1116        command[1] = "-collectdir";
     1117        command[2] = collect_dir;
     1118        command[3] = "-win31compat";
     1119        command[4] = (Gatherer.isGsdlRemote) ? "false" : "true";
    10761120        command[5] = "-title";
    10771121        command[6] = title;
     
    10811125        command[10] = description;
    10821126        command[11] = name;
    1083         }
    1084     }
    1085     else {
    1086         if(description == null || title == null) {
    1087         command = new String[4];
    1088         command[0] = "mkcol.pl";
    1089         command[1] = "-collectdir";
    1090         command[2] = collect_dir;
    1091         command[3] = name;
    1092         }
    1093         else if(email == null) {
    1094         command = new String[8];
    1095         command[0] = "mkcol.pl";
    1096         command[1] = "-collectdir";
    1097         command[2] = collect_dir;
    1098         command[3] = "-title";
    1099         command[4] = title;
    1100         command[5] = "-about";
    1101         command[6] = description;
    1102         command[7] = name;
    1103         }
    1104         else {
    1105         command = new String[10];
    1106         command[0] = "mkcol.pl";
    1107         command[1] = "-collectdir";
    1108         command[2] = collect_dir;
    1109         command[3] = "-title";
    1110         command[4] = title;
    1111         command[5] = "-creator";
    1112         command[6] = email;
    1113         command[7] = "-about";
    1114         command[8] = description;
    1115         command[9] = name;
    11161127        }
    11171128    }
  • trunk/gli/src/org/greenstone/gatherer/gui/GUIManager.java

    r7661 r7739  
    201201    else if(esrc == menu_bar.file_exit) {
    202202        //menu_bar.exit();
     203        System.err.println("*** menu bar file exit called");
    203204        exit();
    204205    }
     
    515516    catch (Exception e) {
    516517        Gatherer.printStackTrace(e);
    517         // The GUI failing to build is a app killer
     518        // The GUI failing to build is an app killer
    518519        e.printStackTrace();
    519520        System.exit(1);
     
    524525    public void exit() {
    525526    // Tell everyone who cares that they are losing focus
     527    System.err.println("**** GUIManager exit called!");
     528
    526529    if(!Gatherer.c_man.ready() || design_pane.canSave()) {
    527         boolean cont = true;
    528         if(Gatherer.c_man.ready() && !Gatherer.c_man.saved()) {
    529         cont = showSaveCollectionBox(false, true);
     530
     531        if (Gatherer.isGsdlRemote) {           
     532        // consider saving???
     533        System.err.println("**** Hiding GUI panel");
     534        hide();
    530535        }
    531536        else {
    532         // Deal to help
    533         if(help != null) {
    534             help.destroy();
    535             help = null;
     537
     538        boolean cont = true;
     539        if(Gatherer.c_man.ready() && !Gatherer.c_man.saved()) {
     540            System.err.println("***** c_man not saved");
     541            cont = showSaveCollectionBox(false, true);
    536542        }
    537         Gatherer.self.exit();
     543        else {
     544            // Deal to help
     545            if(help != null) {
     546            help.destroy();
     547            help = null;
     548            }
     549            System.err.println("**** Calling Gatherer.self.exit");
     550            Gatherer.self.exit();
     551        }
    538552        }
    539553    }
     
    970984    protected void processWindowEvent(WindowEvent event) {
    971985    if(event.getID() == WindowEvent.WINDOW_CLOSING) {
     986        System.err.println("***** Processing Window Event ... closing");
    972987        exit();
    973988    }
  • trunk/gli/src/org/greenstone/gatherer/shell/GShell.java

    r7325 r7739  
    3838
    3939import java.io.*;
     40import java.net.*;
    4041import java.util.ArrayList;
     42import java.util.Enumeration;
    4143import javax.swing.*;
    4244import javax.swing.event.*;
     
    4850import org.greenstone.gatherer.shell.GShellListener;
    4951import org.greenstone.gatherer.shell.GShellProgressMonitor;
     52import org.greenstone.gatherer.util.StaticStrings;
     53import org.greenstone.gatherer.util.Utility;
    5054
    5155/** The <strong>GShell</strong> is reponsible for running a separately threaded process in the command shell. This is necessary for executing the Perl Scripts and also for other system related funcitonality.
     
    103107    static public boolean processRunning(Process process) {
    104108    boolean process_running = false;
     109
    105110    try {
    106111        process.exitValue(); // This will throw an exception if the process hasn't ended yet.
     
    149154       } */
    150155
     156
     157
     158    protected boolean got_stream_char(InputStreamReader isr, StringBuffer line_buffer,
     159                      BufferedOutputStream bos) throws IOException
     160    {
     161    // Hopefully this doesn't block if the process is trying to write to STDOUT/STDERR.
     162
     163    boolean input_status = false;
     164
     165    if(isr.ready()) {
     166        input_status = true;
     167        int c = isr.read();
     168        if(c == '\n' || c == '\r') {
     169        if(line_buffer.length() > 0) {
     170            String line = line_buffer.toString();
     171            Gatherer.println("* " + line + " *");
     172            fireMessage(type, typeAsString(type) + "> " + line, status, bos);
     173            line = null;
     174            line_buffer = new StringBuffer();
     175        }
     176        }
     177        else {
     178        line_buffer.append((char)c);
     179        }
     180    }
     181
     182    return input_status;
     183    }
     184
     185
     186    protected StringBuffer get_stream_char(InputStreamReader isr, StringBuffer line_buffer,
     187                   BufferedOutputStream bos) throws IOException
     188    {
     189    int c = isr.read();
     190    ///atherer.println("isr: '" + (char) c + "'");
     191    if(c == '\n' || c == '\r') {
     192        if(line_buffer.length() > 0) {
     193        String line = line_buffer.toString();
     194        // Gatherer.println("* " + line + " *");
     195        fireMessage(type, typeAsString(type) + "> " + line, status, bos);
     196        line_buffer = new StringBuffer();
     197        }
     198    }
     199    else {
     200        line_buffer.append((char)c);
     201    }
     202
     203    return line_buffer;
     204    }
     205
     206    protected void runRemote(String[] args, BufferedOutputStream bos)
     207    {
     208    try {
     209
     210        String perl_cmd = args[0];
     211        int perl_cmd_root = perl_cmd.lastIndexOf(File.separator);
     212       
     213        if (perl_cmd_root > 0) {
     214        String perl_cmd_cut = perl_cmd.substring(perl_cmd_root+1);
     215        perl_cmd = perl_cmd_cut;
     216        }
     217
     218        String launch  = Gatherer.cgiBase + "launch";
     219        launch = launch + "?cmd=" + perl_cmd;
     220
     221        for(int i = 1; i<args.length; i++) {
     222           
     223        String arg = args[i];
     224
     225        if (arg.equals("-collectdir") || arg.equals("-importdir")
     226            || arg.equals("-builddir")) {
     227            // skip it
     228            i++;
     229            continue;
     230        }
     231       
     232        launch += "&";
     233       
     234        if(arg.startsWith(StaticStrings.MINUS_CHARACTER)) {
     235            String name = arg.substring(1);
     236            launch = launch + name + "=";
     237            if (i+1<args.length-1) {
     238            if (!args[i+1].startsWith(StaticStrings.MINUS_CHARACTER)) {
     239                i++;
     240                String val = args[i];
     241                launch = launch + val;
     242            }
     243            }
     244        }
     245        else {
     246            launch = launch + "c=" + arg;
     247        }
     248        }
     249
     250        System.err.println("**** launch url = " + launch);
     251
     252        URL launch_url = new URL(launch);
     253        URLConnection launch_connection = launch_url.openConnection();
     254        InputStream stdis = launch_connection.getInputStream();
     255        InputStreamReader stdisr = new InputStreamReader(stdis, "UTF-8"  );
     256   
     257        BufferedReader stdbr = new BufferedReader(stdisr);
     258   
     259        if (type == GShell.NEW) {
     260        while(true) {
     261            String line = stdbr.readLine();
     262            if (line == null) { break; }
     263        }       
     264        }
     265        else {
     266        while(!hasSignalledStop()) {
     267            String line = stdbr.readLine();
     268            if (line == null) { break; }
     269            fireMessage(type, typeAsString(type) + "> " + line, status, bos);
     270        }       
     271        }
     272        stdbr.close();
     273   
     274        status = OK;
     275        fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Success"), status, null);
     276    }
     277    // Exception
     278    catch (Exception exception) {
     279        Gatherer.println("Exception in GShell.runRemove() - unexpected");
     280        Gatherer.printStackTrace(exception);
     281        status = ERROR;
     282    }
     283    }
     284
     285
     286    protected void runLocal(String[] args, BufferedOutputStream bos)
     287    {
     288    try {
     289        String command = "";
     290        for(int i = 0; i < args.length; i++) {
     291        command = command + args[i] + " ";
     292        }
     293       
     294        Gatherer.println("Command: "+command);
     295        ///ystem.err.println("Command: " + command);
     296        fireMessage(type, Dictionary.get("GShell.Command") + ": " + command, status, null);
     297       
     298        Runtime rt = Runtime.getRuntime();
     299        Process prcs = rt.exec(args);
     300       
     301        InputStreamReader eisr = new InputStreamReader( prcs.getErrorStream(), "UTF-8" );
     302        InputStreamReader stdisr = new InputStreamReader( prcs.getInputStream(), "UTF-8"  );
     303        //BufferedReader ebr = new BufferedReader( eisr );
     304        //BufferedReader stdinbr = new BufferedReader( stdinisr );
     305        // Captures the std err of a program and pipes it into std in of java
     306   
     307        StringBuffer eline_buffer = new StringBuffer();
     308        StringBuffer stdline_buffer = new StringBuffer();
     309   
     310        while(type != GShell.NEW && processRunning(prcs) && !hasSignalledStop()) {
     311        // Hopefully this doesn't block if the process is trying to write to STDOUT.
     312        if((eisr!=null) && eisr.ready()) {
     313            eline_buffer = get_stream_char(eisr,eline_buffer,bos);
     314        }
     315        // Hopefully this won't block if the process is trying to write to STDERR
     316        else if(stdisr.ready()) {
     317            stdline_buffer = get_stream_char(stdisr,stdline_buffer,bos);
     318        }
     319        else {
     320            try {
     321            sleep(100);
     322            }
     323            catch(Exception exception) {
     324            }
     325        }
     326        }
     327   
     328        if(!hasSignalledStop()) {
     329        // Of course, just because the process is finished doesn't
     330        // mean the incoming streams are empty. Unfortunately I've
     331        // got no chance of preserving order, so I'll process the
     332        // error stream first, then the out stream
     333        while(eisr.ready()) {
     334            eline_buffer = get_stream_char(eisr,eline_buffer,bos);
     335        }
     336       
     337        while(stdisr.ready()) {
     338            stdline_buffer = get_stream_char(stdisr,stdline_buffer,bos);
     339        }
     340       
     341        // Ensure that any messages still remaining in the string buffers are fired off.
     342        if(eline_buffer.length() > 0) {
     343            String eline = eline_buffer.toString();
     344            //Gatherer.println("Last bit of eline: " + eline);
     345            fireMessage(type, typeAsString(type) + "> " + eline, status, bos);
     346            eline = null;
     347        }
     348       
     349        if(stdline_buffer.length() > 0) {
     350            String stdline = stdline_buffer.toString();
     351            //Gatherer.println("Last bit of stdline: " + stdline);
     352            fireMessage(type, typeAsString(type) + "> " + stdline, status, null);
     353            stdline = null;
     354        }
     355        }
     356        else {
     357        System.err.println("We've been asked to stop.");
     358        }
     359   
     360   
     361        if(!hasSignalledStop()) {
     362        // Now display final message based on exit value
     363       
     364        prcs.waitFor();
     365
     366        if(prcs.exitValue() == 0) {
     367            status = OK;
     368            fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Success"), status, null);
     369        }
     370        else {
     371            status = ERROR;
     372            fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Failure"), status, null);
     373        }
     374       
     375        eisr.close();
     376        stdisr.close();
     377        }
     378        else {
     379        // I need to somehow kill the child process. Unfortunately
     380        // Thread.stop() and Process.destroy() both fail to do
     381        // this. But now, thankx to the magic of Michaels 'close the
     382        // stream suggestion', it works fine (no it doesn't!)
     383        prcs.getInputStream().close();
     384        prcs.getErrorStream().close();
     385        prcs.getOutputStream().close();
     386        prcs.destroy();
     387        status = CANCELLED;
     388        }
     389    }
     390    // Exception
     391    catch (Exception exception) {
     392        Gatherer.println("Exception in GShell.runLocal() - unexpected");
     393        Gatherer.printStackTrace(exception);
     394        status = ERROR;
     395    }
     396    }
     397   
     398   
     399
    151400    /** Any threaded class must include this method to allow the thread body to be run. */
    152401    public void run() {
     402
     403    String col_name = args[args.length-1];     
     404
    153405    // Determine if the user has asked for an outfile.
    154406    String out_name = null;
     
    170422        }
    171423    }
     424
     425    if (Gatherer.isGsdlRemote) {
     426        if (type == IMPORT) {
     427        // zip up import folder
     428        Utility.zipup(col_name,"import");
     429        // upload it to gsdl server
     430        Utility.upload_url_zip(col_name,"import");
     431
     432        // upload etc/collect.cfg to server
     433        Utility.zipup(col_name,Utility.CONFIG_FILE);
     434        Utility.upload_url_zip(col_name,"etc");
     435        }
     436    }
     437
     438
    172439    // Issue a processBegun event
    173440    fireProcessBegun(type, status);
    174     try {
    175         String command = "";
    176         for(int i = 0; i < args.length; i++) {
    177         command = command + args[i] + " ";
    178         }
    179         Gatherer.println("Command: "+command);
    180         ///ystem.err.println("Command: " + command);
    181         fireMessage(type, Dictionary.get("GShell.Command") + ": " + command, status, null);
    182        
    183         Runtime rt = Runtime.getRuntime();
    184         Process prcs = rt.exec(args);
    185         InputStreamReader eisr = new InputStreamReader( prcs.getErrorStream(), "UTF-8" );
    186         InputStreamReader stdisr = new InputStreamReader( prcs.getInputStream(), "UTF-8"  );
    187         //BufferedReader ebr = new BufferedReader( eisr );
    188         //BufferedReader stdinbr = new BufferedReader( stdinisr );
    189         // Captures the std err of a program and pipes it into std in of java
    190        
    191         StringBuffer eline_buffer = new StringBuffer();
    192         StringBuffer stdline_buffer = new StringBuffer();
    193         while(type != GShell.NEW && processRunning(prcs) && !hasSignalledStop()) {
    194         // Hopefully this doesn't block if the process is trying to write to STDOUT.
    195         if(eisr.ready()) {
    196             int c = eisr.read();
    197             ///atherer.println("eisr: '" + (char) c + "'");
    198             if(c == '\n' || c == '\r') {
    199             if(eline_buffer.length() > 0) {
    200                 String eline = eline_buffer.toString();
    201                 ///atherer.println("* " + eline + " *");
    202                 fireMessage(type, typeAsString(type) + "> " + eline, status, bos);
    203                 eline = null;
    204                 eline_buffer = new StringBuffer();
    205             }
    206             }
    207             else {
    208             eline_buffer.append((char)c);
    209             }
    210         }
    211         // Hopefully this won't block if the process is trying to write to STDERR
    212         else if(stdisr.ready()) {
    213             int c = stdisr.read();
    214             ///atherer.println("eisr: '" + (char) c + "'");
    215             if(c == '\n' || c == '\r') {
    216             if(stdline_buffer.length() > 0) {
    217                 String stdline = stdline_buffer.toString();
    218                 ///atherer.println("+ " + stdline + " +");
    219                 fireMessage(type, typeAsString(type) + "> " + stdline, status, null);
    220                 stdline = null;
    221                 stdline_buffer = new StringBuffer();
    222             }
    223             }
    224             else {
    225             stdline_buffer.append((char)c);
    226             }
    227         }
    228         else {
    229             try {
    230             sleep(100);
    231             }
    232             catch(Exception exception) {
    233             }
    234         }
    235         }
    236         if(!hasSignalledStop()) {
    237         // Of course, just because the process is finished doesn't mean the incoming streams are empty. Unfortunately I've got no chance of preserving order, so I'll process the error stream first, then the out stream
    238         while(eisr.ready()) {
    239             int c = eisr.read();
    240             ///atherer.println("eisr: '" + (char) c + "'");
    241             if(c == '\n' || c == '\r') {
    242             if(eline_buffer.length() > 0) {
    243                 String eline = eline_buffer.toString();
    244                 ///atherer.println("* " + eline + " *");
    245                 fireMessage(type, typeAsString(type) + "> " + eline, status, bos);
    246                 eline = null;
    247                 eline_buffer = new StringBuffer();
    248             }
    249             }
    250             else {
    251             eline_buffer.append((char)c);
    252             }
    253         }
    254         while(stdisr.ready()) {
    255             int c = stdisr.read();
    256             ///atherer.println("eisr: '" + (char) c + "'");
    257             if(c == '\n' || c == '\r') {
    258             if(stdline_buffer.length() > 0) {
    259                 String stdline = stdline_buffer.toString();
    260                 ///atherer.println("+ " + stdline + " +");
    261                 fireMessage(type, typeAsString(type) + "> " + stdline, status, null);
    262                 stdline = null;
    263                 stdline_buffer = new StringBuffer();
    264             }
    265             }
    266             else {
    267             stdline_buffer.append((char)c);
    268             }
    269         }
     441    if (Gatherer.isGsdlRemote) {
     442        runRemote(args,bos);
     443    }
     444    else {
     445        runLocal(args,bos);
     446    }
     447
     448    if(status == OK) {
     449        if (type == NEW) {
     450        if (Gatherer.isGsdlRemote) {
     451            Utility.download_url_zip(col_name,".");
     452            Utility.unzip(col_name);
     453        }
     454        }
     455        else if(type == IMPORT) {
    270456       
    271         // Ensure that any messages still remaining in the string buffers are fired off.
    272         if(eline_buffer.length() > 0) {
    273             String eline = eline_buffer.toString();
    274             ///atherer.println("Last bit of eline: " + eline);
    275             fireMessage(type, typeAsString(type) + "> " + eline, status, bos);
    276             eline = null;
    277         }
     457        // download the archives directory (if gsdl server is remote)           
     458        if (Gatherer.isGsdlRemote) {
     459            Utility.delete(Gatherer.c_man.getCollectionArchive()); // remove current archives
     460            Utility.download_url_zip(col_name,"archives");
     461            Utility.unzip(col_name);
     462        }
     463
     464        // extract any new metadata from the archive directory.
     465        fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Parsing_Metadata_Start"), status, null);
     466        new GreenstoneArchiveParser(progress, this);
     467        fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Parsing_Metadata_Complete"), status, null);
     468        }
     469
     470        else if(type == BUILD) {
    278471       
    279         if(stdline_buffer.length() > 0) {
    280             String stdline = stdline_buffer.toString();
    281             ///atherer.println("Last bit of stdline: " + stdline);
    282             fireMessage(type, typeAsString(type) + "> " + stdline, status, null);
    283             stdline = null;
    284         }
    285         }
    286         else {
    287         System.err.println("We've been asked to stop.");
    288         }
    289        
    290         if(!hasSignalledStop()) {
    291         // Now display final message based on exit value
    292         prcs.waitFor();
    293        
    294         if(prcs.exitValue() == 0) {
    295             status = OK;
    296             fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Success"), status, null);
    297         }
    298         else {
    299             status = ERROR;
    300             fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Failure"), status, null);
    301         }
    302         }
    303         else {
    304         // I need to somehow kill the child process. Unfortunately Thread.stop() and Process.destroy() both fail to do this. But now, thankx to the magic of Michaels 'close the stream suggestion', it works fine (no it doesn't!)
    305         prcs.getInputStream().close();
    306         prcs.getErrorStream().close();
    307         prcs.getOutputStream().close();
    308         prcs.destroy();
    309         status = CANCELLED;
    310         }
    311     }
    312     // Exception
    313     catch (Exception exception) {
    314         Gatherer.println("Exception in GShell.run() - unexpected");
    315         Gatherer.printStackTrace(exception);
    316         status = ERROR;
    317     }
    318     // If no error occured, and this was an import process we now extract any new metadata from the archive directory.
    319     if(status == OK && type == IMPORT) {
    320         fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Parsing_Metadata_Start"), status, null);
    321         new GreenstoneArchiveParser(progress, this);
    322         fireMessage(type, typeAsString(type) + "> " + Dictionary.get("GShell.Parsing_Metadata_Complete"), status, null);
    323     }
     472        // download the building directory (if gsdl server is remote)           
     473        if (Gatherer.isGsdlRemote) {
     474            Utility.delete(Gatherer.c_man.getCollectionBuild()); // remove current build dir
     475            Utility.download_url_zip(col_name,"building");
     476            Utility.unzip(col_name);
     477        }
     478
     479        }
     480    }
     481
    324482    if(hasSignalledStop()) {
    325483        status = CANCELLED;
  • trunk/gli/src/org/greenstone/gatherer/util/Utility.java

    r7674 r7739  
    4141import java.net.*;
    4242import java.util.*;
     43import java.util.zip.*;
    4344import javax.swing.*;
    4445import javax.swing.tree.*;
     
    6869    static final public String ARCHIVE_DIR = "archives" + File.separator;
    6970    /** Definition of an important directory name, in this case the base dir, or the working directory of the Gatherer. */
    70     static final public String BASE_DIR  = System.getProperty("user.dir") + File.separator;
     71    static public String BASE_DIR  = System.getProperty("user.dir") + File.separator;
    7172    static final public String BUILD_CFG_FILENAME = "build.cfg";
    7273    /** Definition of an important directory name, in this case the building directory for the collection. */
    7374    static final public String BUILD_DIR = "building" + File.separator;
    7475    /** Definition of an important directory name, in this case the public web cache for the Gatherer. */
    75     static final public String CACHE_DIR = BASE_DIR + "cache" + File.separator;
     76    static public String CACHE_DIR = BASE_DIR + "cache" + File.separator;
    7677    static final public String CFG_COLLECTIONMETA_COLLECTIONNAME = "collectionmeta\tcollectionname";
    7778    static final public String CFG_COLLECTIONMETA_COLLECTIONEXTRA = "collectionmeta\tcollectionextra";
     
    108109    static final public String GLI_EXTENSION = ".col";
    109110    /** Definition of an important directory name, in this case the location of help documentation. */
    110     static final public String HELP_DIR = BASE_DIR + "help" + File.separator;
     111    static public String HELP_DIR = BASE_DIR + "help" + File.separator;
    111112    /** Definition of an important directory name, in this case the images directory for the collection. */
    112113    static final public String IMAGES_DIR = "images" + File.separator;
     
    125126    static final public String META_DIR = "metadata" + File.separator; // Col. Copy
    126127    /** Definition of an important directory name, in this case the location of the default metadata sets. */
    127     static final public String METADATA_DIR = BASE_DIR + "metadata" + File.separator;
     128    static public String METADATA_DIR = BASE_DIR + "metadata" + File.separator;
     129    /** Definition of an important zip file, in this case zipped up version of metadata file stored in JAR file */
     130    static final public String METADATA_ZIP = "metadata.zip";
    128131    /** The location the gatherer expects to find metadata set information. */
    129132    static final public String METADATA_SET_TEMPLATE = "xml/template.mds";
     
    142145    static final public String PROGRAM_VERSION = "v2.51";
    143146    /** Definition of an important directory name, in this case the location of the recycled files location. */
    144     static final public String RECYCLE = BASE_DIR + "recycle" + File.separator;
     147    static public String RECYCLE = BASE_DIR + "recycle" + File.separator;
    145148    /** Definition of an important directory name, in this case the location of image and other resources. */
    146     static final public String RES_DIR = BASE_DIR + "resource" + File.separator;
     149    static public String RES_DIR = BASE_DIR + "resource" + File.separator;
    147150    static final public String SERVER_EXE = "server.exe";
    148151    /** Definition of an important directory name, in this case the location of opening (or welcome) screen html. */
    149     static final public String WELCOME_DIR = BASE_DIR + "welcome" + File.separator;
     152    static public String WELCOME_DIR = BASE_DIR + "welcome" + File.separator;
    150153    static final public String WORKSPACE_TREE = "Workspace";
    151154    static final public String XML_DIRECTORY = "xml" + File.separator;
     155
    152156    // These are out of alphabetic order to avoid forward reference error.
    153157    /** The default icon to produce a 'help-icon' sized blank space before a menu entry. */
    154     static final public ImageIcon BLANK_ICON = new ImageIcon(ClassLoader.getSystemResource("images/blank.gif"));
     158    static public Class base = null;
     159    static public ImageIcon BLANK_ICON = null;
    155160    /** The default error icon image. */
    156     static final public ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("images/error.gif"));
    157     static final public ImageIcon HELP_ICON = new ImageIcon(ClassLoader.getSystemResource("images/help.gif"));
     161    static public ImageIcon ERROR_ICON = null;
     162    static public ImageIcon HELP_ICON = null;
    158163    /** The image for a toggle button whose state is 'on'. */
    159     static final public ImageIcon ON_ICON = new ImageIcon(ClassLoader.getSystemResource("images/check.gif"));
     164    static public ImageIcon ON_ICON = null;
    160165    /** The image for a toggle button whose state is 'off'. */
    161     static final public ImageIcon OFF_ICON = new ImageIcon(ClassLoader.getSystemResource("images/cross.gif"));
     166    static public ImageIcon OFF_ICON = null;
    162167   
    163168    /** Decodes a string of text so its safe to use in a Greenstone configuration file. Esentially replaces "\n" with a newline.
     
    205210    static public boolean delete(File file) {
    206211    boolean result = true;
    207     // If files a directory, delete files children.
     212    // If file is a directory, delete the file's children.
    208213    if(file.isDirectory()) {
    209214        File files[] = file.listFiles();
     
    217222    }
    218223    return result;
     224    }
     225
     226    static public boolean delete(String filename) {
     227    return delete(new File(filename));
    219228    }
    220229
     
    469478    return getSitesDir(gsdl3_path) + site_name + File.separator + COL_DIR;
    470479    }
     480
    471481   
    472482    /** Method which constructs a collection's top level directory
     
    481491    return getCollectDir(gsdl3_path, site_name) + coll_name + File.separator;
    482492    }
     493
     494    public static String getCollectionDir() {
     495    String this_col_dir;
     496
     497    String col_name = Gatherer.c_man.getCollection().getName();
     498
     499    if (Gatherer.GS3) {
     500        this_col_dir = getCollectionDir(Gatherer.config.gsdl3_path, Gatherer.config.site_name, col_name);
     501    } else {
     502        this_col_dir = getCollectionDir(Gatherer.config.gsdl_path, col_name);
     503       
     504    }
     505
     506    return this_col_dir;
     507    }
     508
    483509   
    484510    /** Method which constructs the configuration file given a certain collection.
     
    557583     */
    558584    static public String getHelpFolder() {
    559     String help_folder = HELP_DIR + Gatherer.config.getLanguage() + File.separator;
    560     File help_folder_file = new File(help_folder);
     585
     586    String help_folder = "help/" + Gatherer.config.getLanguage() + "/";
     587    URL help_folder_url = base.getResource("/"+help_folder);
     588
    561589    // If that file can't be found, default to english
    562     if(!help_folder_file.exists()) {
    563         help_folder = HELP_DIR + StaticStrings.ENGLISH_LANGUAGE_STR  + File.separator;
    564     }
     590    if(help_folder_url==null) {
     591        help_folder = "help/" + StaticStrings.ENGLISH_LANGUAGE_STR  + "/";
     592    }
     593
    565594    return help_folder;
    566595    }
    567 
    568596
    569597    /** Method to retrieve an image icon with the given filename found in classpath or the resouces directory.
     
    577605    ImageIcon image = null;
    578606    try {
    579         image = new ImageIcon(ClassLoader.getSystemResource("images/" + Dictionary.get("Version") + "/" + filename));
     607        image = new ImageIcon(base.getResource("/images/" + Dictionary.get("Version") + "/" + filename));
    580608    }
    581609    catch(NullPointerException exception) {
    582         image = new ImageIcon(ClassLoader.getSystemResource("images/" + filename));
     610        image = new ImageIcon(base.getResource("/images/" + filename));
    583611    }
    584612    if(image == null) {
     
    647675    return col_dir + META_DIR;
    648676    }
     677
     678    static public void extractFromJar(String filename, String dst_dir)
     679    {
     680    try {
     681        // setup input stream for slurping out file
     682        InputStream fis = base.getResourceAsStream("/"+filename);
     683        BufferedInputStream fbis = new BufferedInputStream(fis);
     684        DataInputStream fdbis = new DataInputStream(fbis);
     685           
     686        // set up output stream for writing to disk
     687        String ofname = dst_dir + filename;
     688        FileOutputStream fos = new FileOutputStream(ofname);
     689        BufferedOutputStream bfos = new BufferedOutputStream(fos);
     690
     691        byte[] buf = new byte[1024];
     692        int len;
     693        int total_bytes = 0;
     694        while ((len = fdbis.read(buf)) >= 0) {
     695        bfos.write(buf,0,len);
     696        total_bytes += len;
     697        }
     698
     699        fdbis.close();
     700        bfos.close();
     701    }
     702    catch (Exception error) {
     703        error.printStackTrace();
     704    }
     705    }
     706
     707
     708    /** Method which unzips a given metadata resoure
     709     * @param zip_fname The name of the zip file as a <strong>String</strong>.
     710     * @param dst_dir The destination directory for unzipping, also as a <strong>String</strong>.
     711     * @param use_classloader Used to determine whether or not to look in resource bundle.
     712     */
     713    static public void unzipFromJar(String jar_zip_fname, String dst_dir) {
     714
     715    File file = null;
     716    if (!dst_dir.endsWith(File.separator)) {
     717        dst_dir += File.separator;
     718    }
     719
     720    extractFromJar(jar_zip_fname,dst_dir);
     721
     722    String zip_ofname = dst_dir + jar_zip_fname;
     723    File zip_file = new File(zip_ofname);
     724
     725    try {
     726        ZipFile zipfile = new ZipFile(zip_file);
     727       
     728        Enumeration e = zipfile.entries();
     729        while (e.hasMoreElements()) {
     730        ZipEntry zipentry = (ZipEntry) e.nextElement();
     731        String zentryname = dst_dir + zipentry.getName();
     732        Gatherer.println("    Unzipping: " + zentryname);
     733
     734        if (zipentry.isDirectory()) {
     735            // Create named directory
     736            boolean success = (new File(zentryname)).mkdir();
     737            if (!success) {
     738            System.err.println("Error: unable to create directory '"+zentryname+"'");
     739            }
     740        }
     741        else {
     742            // Write out file to disk
     743
     744            // set up input stream
     745            InputStream zis = zipfile.getInputStream(zipentry);
     746            BufferedInputStream bzis = new BufferedInputStream(zis);
     747            DataInputStream dbzis = new DataInputStream(bzis);
     748           
     749            // set up output stream
     750            FileOutputStream fzos = new FileOutputStream(zentryname);
     751            BufferedOutputStream bfzos = new BufferedOutputStream(fzos);
     752           
     753            byte[] buf = new byte[1024];
     754            int len;
     755            while ((len = dbzis.read(buf)) >= 0) {
     756            bfzos.write(buf,0,len);
     757            }
     758           
     759            dbzis.close();
     760            bfzos.close();
     761        }
     762        }
     763    }
     764    catch (ZipException error) {
     765        System.err.println("Error: Unable to open '"+zip_file.getAbsolutePath()+"'");
     766        Gatherer.printStackTrace(error);
     767    }
     768
     769    catch (Exception error) {
     770        error.printStackTrace();
     771    }
     772    }
     773   
     774
     775    static public void download_url_zip(String col_name, String dir)
     776    {
     777    try {
     778        String download_cgi  = Gatherer.cgiBase + "download";
     779
     780        // Send col_name and dir arguments to download cgi
     781
     782        String col_name_encoded = URLEncoder.encode(col_name,"UTF-8");
     783        String dir_encoded = URLEncoder.encode(dir,"UTF-8");
     784        String cgi_args = "c=" + col_name_encoded;
     785        cgi_args += "&dir=" + dir_encoded;
     786
     787        URL download_url = new URL(download_cgi);
     788
     789        System.err.println("*** download cgi = '" + download_cgi + "'");
     790        System.err.println("*** cgi args = '" + cgi_args + "'");
     791
     792        URLConnection dl_connection = download_url.openConnection();
     793        dl_connection.setDoOutput(true);       
     794        OutputStream dl_os = dl_connection.getOutputStream();
     795
     796        PrintWriter dl_out = new PrintWriter(dl_os);
     797        dl_out.println(cgi_args);
     798        dl_out.close();
     799
     800        // Download result from running cgi script
     801        InputStream dl_is = dl_connection.getInputStream();
     802        BufferedInputStream dl_bis = new BufferedInputStream(dl_is);
     803        DataInputStream dl_dbis = new DataInputStream(dl_bis);
     804           
     805        // set up output stream for zip download
     806        String col_dir = Utility.getCollectDir(Gatherer.config.gsdl_path);
     807        String zip_fname = col_dir + col_name + ".zip";
     808        FileOutputStream zip_fos = new FileOutputStream(zip_fname);
     809        BufferedOutputStream zip_bfos = new BufferedOutputStream(zip_fos);
     810       
     811        byte[] buf = new byte[1024];
     812        int len;
     813
     814        while ((len = dl_dbis.read(buf)) >= 0) {
     815        zip_bfos.write(buf,0,len);
     816        }
     817
     818        dl_dbis.close();
     819        zip_bfos.close();
     820
     821    }
     822    catch (Exception error) {
     823        error.printStackTrace();
     824    }
     825    }
     826
     827
     828    static public void upload_url_zip(String col_name, String dir)
     829    {
     830    final String lineEnd = "\r\n";
     831    final String twoHyphens = "--";
     832    final String boundary =  "*****";
     833    final int maxBufferSize = 1024;
     834
     835    String col_dir = Utility.getCollectDir(Gatherer.config.gsdl_path);
     836    String zip_fname = col_dir + col_name + ".zip";
     837    String upload_cgi = Gatherer.cgiBase + "upload";
     838
     839    HttpURLConnection conn = null;
     840       
     841    try {
     842        // Send zip file to server
     843
     844        File file = new File(zip_fname) ;       
     845        FileInputStream fileInputStream = new FileInputStream(file);
     846       
     847        // open a URL connection to the Servlet
     848        URL url = new URL(upload_cgi);
     849               
     850        // Open a HTTP connection to the URL
     851        conn = (HttpURLConnection) url.openConnection();
     852       
     853        conn.setDoInput(true);         // Allow Inputs
     854        conn.setDoOutput(true);        // Allow Outputs
     855        conn.setUseCaches(false);      // Don't use a cached copy.
     856        conn.setRequestMethod("POST"); // Use a post method.
     857       
     858        conn.setRequestProperty("Connection", "Keep-Alive");       
     859        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
     860       
     861        DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
     862
     863        dos.writeBytes(twoHyphens + boundary + lineEnd);
     864        dos.writeBytes("Content-Disposition: form-data; name=\"c\"" + lineEnd + lineEnd);
     865        dos.writeBytes(col_name + lineEnd);
     866
     867        dos.writeBytes(twoHyphens + boundary + lineEnd);
     868        dos.writeBytes("Content-Disposition: form-data; name=\"dir\"" + lineEnd + lineEnd);
     869        dos.writeBytes(dir + lineEnd);
     870       
     871        dos.writeBytes(twoHyphens + boundary + lineEnd);
     872        dos.writeBytes("Content-Disposition: form-data; name=\"zip\";"
     873               + " filename=\"" + zip_fname +"\"" + lineEnd);
     874        dos.writeBytes(lineEnd);
     875       
     876               
     877        // create a buffer of maximum size
     878                   
     879        int bytesAvailable = fileInputStream.available();
     880        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
     881        byte[] buffer = new byte[bufferSize];
     882       
     883        // read file and write it into form...
     884
     885        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
     886       
     887        while (bytesRead > 0) {
     888        dos.write(buffer, 0, bufferSize);
     889        bytesAvailable = fileInputStream.available();
     890        bufferSize = Math.min(bytesAvailable, maxBufferSize);
     891        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
     892        }
     893       
     894        // send multipart form data necesssary after file data...
     895       
     896        dos.writeBytes(lineEnd);
     897        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
     898       
     899        // close streams
     900       
     901        fileInputStream.close();
     902        dos.flush();
     903        dos.close();
     904       
     905       
     906    }
     907    catch (MalformedURLException ex) {
     908        System.err.println("Failed on: "+ex);
     909    }
     910   
     911    catch (IOException ioe) {
     912        System.err.println("Failed on: "+ioe);
     913    }
     914   
     915    // Read server response
     916
     917    try {
     918        InputStreamReader isr = new InputStreamReader(conn.getInputStream() );
     919        BufferedReader bisr = new BufferedReader (isr);
     920        String str;
     921        while (( str = bisr.readLine()) != null) {
     922        System.err.println(str);
     923        }
     924        bisr.close();
     925       
     926    }
     927    catch (IOException ioex) {
     928        System.err.println("From (ServerResponse): "+ioex);
     929    }
     930    }
     931
     932    static protected void zipFunc (ZipOutputStream zos, String file_path, int prefix_strip)
     933    {
     934    // Using try is required because of file io.
     935    try {
     936        // Create a Zip Entry and put it into the archive (no data yet).
     937
     938        // Strip off col_dir prefix
     939        String zip_path = file_path.substring(prefix_strip);
     940
     941        ZipEntry fileEntry = new ZipEntry(zip_path);
     942        zos.putNextEntry(fileEntry);
     943
     944        // Create a file input stream and a buffered input stream.
     945        FileInputStream fis = new FileInputStream(file_path);
     946        BufferedInputStream bis = new BufferedInputStream(fis);
     947       
     948        // Create a byte array object named data and declare byte count variable.
     949        byte[] data = new byte[1024];
     950        int byteCount;
     951        // Create a loop that reads from the buffered input stream and writes
     952        // to the zip output stream until the bis has been entirely read.
     953        while ((byteCount = bis.read(data, 0, 1024)) > -1) {
     954        zos.write(data, 0, byteCount);
     955        }
     956    }
     957    catch (IOException e) {
     958        e.printStackTrace();
     959    }
     960   
     961    Gatherer.println("    Zipping up: " + file_path);
     962    }
     963
     964    static protected void dirFunc (ZipOutputStream zos, String dir_name, int prefix_strip)
     965    {
     966    File dirObj = new File(dir_name);
     967
     968    if (dirObj.exists() == true) {
     969        if (dirObj.isDirectory() == true) {
     970        // Create an array of File objects, one for each file or directory in dirObj.
     971        File [] fileList = dirObj.listFiles();
     972       
     973        // Loop through File array and display.
     974        for (int i = 0; i < fileList.length; i++) {
     975            File file = fileList[i];
     976            if (file.isDirectory()) {
     977            String dir_path = file.getPath();
     978            String zip_path = dir_path.substring(prefix_strip);
     979            // use of "/" here instead of File.separation intentional
     980            ZipEntry dirEntry = new ZipEntry(zip_path+"/");
     981
     982            try {
     983                zos.putNextEntry(dirEntry);
     984            }
     985            catch (IOException e) {
     986                e.printStackTrace();
     987            }
     988
     989            dirFunc(zos,dir_path,prefix_strip);
     990            } else if (file.isFile()) {
     991            // Call the zipFunc function
     992            String file_path = fileList[i].getPath();
     993            zipFunc(zos,file_path,prefix_strip);
     994            }
     995        }
     996        }
     997        else {
     998        System.err.println (dir_name+" is not a directory.");
     999        }
     1000    }
     1001    else {
     1002        System.err.println ("Directory "+dir_name+" does not exist.");
     1003    }
     1004    }
     1005   
     1006
     1007
     1008    static public void zipup(String col_name, String dir_or_file)
     1009    {
     1010    String col_dir = Utility.getCollectDir(Gatherer.config.gsdl_path);
     1011    int prefix_strip = col_dir.length();
     1012
     1013    String zip_fname = col_dir + col_name + ".zip";
     1014    String zip_dir_or_file = col_dir + col_name + File.separator + dir_or_file;
     1015    File zip_dof = new File(zip_dir_or_file);
     1016
     1017    try {
     1018        FileOutputStream fos = new FileOutputStream(zip_fname);
     1019        ZipOutputStream zos = new ZipOutputStream(fos);
     1020       
     1021        if (zip_dof.exists()) {
     1022        if (zip_dof.isDirectory()) {
     1023            String zip_dir = zip_dir_or_file;
     1024            dirFunc(zos,zip_dir,prefix_strip);
     1025        }
     1026        else {
     1027            String zip_full_file = zip_dir_or_file;
     1028
     1029            String zip_path = zip_full_file.substring(prefix_strip);
     1030
     1031            for (int i=1; i<zip_path.length(); i++) {
     1032            String ch = String.valueOf(zip_path.charAt(i));
     1033
     1034            if (ch.equals(File.separator)) {
     1035                String dir_path = zip_path.substring(0,i);
     1036                // use of "/" here instead of File.separation intentional
     1037                ZipEntry dirEntry = new ZipEntry(dir_path+"/");
     1038                zos.putNextEntry(dirEntry);
     1039            }
     1040            }
     1041            zipFunc(zos,zip_full_file,prefix_strip);
     1042        }
     1043        }
     1044        else {
     1045        System.err.println("Warning: " + zip_dir_or_file + " does not exist!");
     1046        }
     1047       
     1048        // Close the file output streams for both the file and the zip.
     1049        zos.flush();
     1050        zos.close();
     1051        fos.close();
     1052    }
     1053    catch (IOException e) {
     1054        e.printStackTrace();
     1055    }
     1056    }
     1057   
     1058
     1059    static public void unzip(String col_name)
     1060    {
     1061    String col_dir = Utility.getCollectDir(Gatherer.config.gsdl_path);
     1062    String zip_fname = col_dir + col_name + ".zip";
     1063    int zip_mode = ZipFile.OPEN_READ | ZipFile.OPEN_DELETE;
     1064
     1065    try {
     1066        ZipFile zipfile = new ZipFile(new File(zip_fname), zip_mode);
     1067       
     1068        Enumeration e = zipfile.entries();
     1069        while (e.hasMoreElements()) {
     1070        ZipEntry zipentry = (ZipEntry) e.nextElement();
     1071        String zentryname = col_dir + zipentry.getName();
     1072        Gatherer.println("    Unzipping: " + zentryname);
     1073
     1074        if (zipentry.isDirectory()) {
     1075            // Create named directory
     1076            boolean success = (new File(zentryname)).mkdir();
     1077            if (!success) {
     1078            System.err.println("Error: unable to create directory '"+zentryname+"'");
     1079            }
     1080        }
     1081        else {
     1082            // Write out file to disk
     1083
     1084            // set up input stream
     1085            InputStream zis = zipfile.getInputStream(zipentry);
     1086            BufferedInputStream bzis = new BufferedInputStream(zis);
     1087            DataInputStream dbzis = new DataInputStream(bzis);
     1088           
     1089            // set up output stream
     1090            FileOutputStream fzos = new FileOutputStream(zentryname);
     1091            BufferedOutputStream bfzos = new BufferedOutputStream(fzos);
     1092           
     1093            byte[] buf = new byte[1024];
     1094            int len;
     1095            while ((len = dbzis.read(buf)) >= 0) {
     1096            bfzos.write(buf,0,len);
     1097            }
     1098           
     1099            dbzis.close();
     1100            bfzos.close();
     1101        }
     1102        }
     1103    }
     1104    catch (ZipException error) {
     1105        System.err.println("Error: Unable to open '"+zip_fname+"'");
     1106        Gatherer.printStackTrace(error);
     1107    }
     1108
     1109    catch (Exception error) {
     1110        error.printStackTrace();
     1111    }
     1112    }
     1113
     1114
     1115
     1116
     1117
     1118    /* static private File getRecycleDirectory() {
     1119    return new File(RECYCLE);
     1120    } */
    6491121
    6501122
     
    7971269    if(use_classloader) {
    7981270        try {
    799         URL url = ClassLoader.getSystemResource(filename);
    800         file = new File(URLDecoder.decode(url.getFile(), ENCODING));
    801         url = null;
     1271        // ****
     1272        // URL url = ClassLoader.getSystemResource(filename);
     1273        // URL url = base.getResource("/"+filename);
     1274        System.err.println("*** looking for resource as stream: " + filename);
     1275        InputStream is = base.getResourceAsStream("/"+filename);
     1276
     1277        // file = new File(URLDecoder.decode(url.getFile(), ENCODING));
     1278        // url = null;
     1279
     1280        //FileInputStream fis   = new FileInputStream(file);       
     1281        return parse(is,true);
    8021282        }
    8031283        catch (Exception error) {
    8041284        // Most likely file name.
     1285        /* String prefix = "";
     1286        if (!filename.startsWith("/")) {
     1287            prefix = "/research/code/gsdl/gli/";
     1288            }*/
    8051289        file = new File("classes" + File.separator + filename);
    8061290        //Gatherer.printStackTrace(error);
     
    8121296    return parse(file, true);
    8131297    }
     1298
    8141299    /** Parse in a xml document from a given file. */
    8151300    static public Document parse(File file) {
    8161301    return parse(file, true);
    8171302    }
     1303
    8181304    /** Parse in a xml document from a given file. */
    819     static public Document parse(File file, boolean noisey) {
     1305    static public Document parse(File file, boolean noisey)
     1306    {
    8201307    Document document = null;
    8211308    try {
     1309        System.err.println("file = " + file);
    8221310        FileInputStream fis   = new FileInputStream(file);
    823         InputStreamReader isr = new InputStreamReader(fis, ENCODING);
     1311        document = parse(fis,noisey);
     1312        file = null;
     1313    }
     1314    catch (Exception error) {
     1315        if(noisey) {
     1316        error.printStackTrace();
     1317        Gatherer.println("Exception in Utility.parse() - Unexpected");
     1318        }
     1319        else {
     1320        Gatherer.println("Exception in Utility.parse() - Expected");
     1321        Gatherer.printStackTrace(error);
     1322        }
     1323    }
     1324
     1325    return document;
     1326    }
     1327
     1328    /** Parse in a xml document from a given URL. */
     1329    static public Document parse(URL url, boolean noisey)
     1330    {
     1331    Document document = null;
     1332    try {
     1333       
     1334        URLConnection connection = url.openConnection();
     1335        InputStream is = connection.getInputStream();
     1336        document = parse(is,noisey);
     1337    }
     1338    catch (Exception error) {
     1339        if(noisey) {
     1340        error.printStackTrace();
     1341        Gatherer.println("Exception in Utility.parse() - Unexpected");
     1342        }
     1343        else {
     1344        Gatherer.println("Exception in Utility.parse() - Expected");
     1345        Gatherer.printStackTrace(error);
     1346        }
     1347    }
     1348
     1349    return document;
     1350    }
     1351
     1352    /** Parse in a xml document from a given file. */
     1353    static public Document parse(InputStream is, boolean noisey) {
     1354    Document document = null;
     1355    try {
     1356        InputStreamReader isr = new InputStreamReader(is, ENCODING);
    8241357        Reader r              = new BufferedReader(isr);
    8251358        InputSource isc       = new InputSource(r);
     
    8331366        document = parser.getDocument();
    8341367        isr.close();
    835         fis.close();
     1368        is.close();
    8361369        parser = null;
    8371370        isc = null;
    8381371        r = null;
    8391372        isr = null;
    840         fis = null;
    841         file = null;
     1373        is = null;
    8421374    }
    8431375    catch (Exception error) {
Note: See TracChangeset for help on using the changeset viewer.