source: gli/trunk/src/org/greenstone/gatherer/gui/ReplaceSrcDocWithHtmlPrompt.java@ 18412

Last change on this file since 18412 was 18412, checked in by kjdon, 15 years ago

more modifications for RTL GLI, thanks to Amin Hedjazi

File size: 16.9 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * Author: Anupama Krishnan, Greenstone Digital Library, University of Waikato
9 * Code based entirely on Katherine Don's ExplodeMetadataDatabasePrompt.java
10 * (part of the Greenstone Digital Library)
11 *
12 * Copyright (C) 2008 Greenstone Digital Library Project
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 *########################################################################
28 */
29package org.greenstone.gatherer.gui;
30
31import java.awt.*;
32import java.awt.event.*;
33import javax.swing.*;
34import javax.swing.event.*;
35import javax.swing.text.*;
36import java.io.*;
37import java.util.ArrayList;
38
39import org.w3c.dom.Document;
40
41import org.greenstone.gatherer.Dictionary;
42import org.greenstone.gatherer.Configuration;
43import org.greenstone.gatherer.Gatherer;
44import org.greenstone.gatherer.cdm.Argument;
45import org.greenstone.gatherer.cdm.ArgumentControl;
46import org.greenstone.gatherer.cdm.CollectionDesignManager;
47import org.greenstone.gatherer.cdm.Plugin;
48import org.greenstone.gatherer.collection.CollectionManager;
49import org.greenstone.gatherer.collection.ScriptOptions;
50import org.greenstone.gatherer.collection.Collection;
51import org.greenstone.gatherer.greenstone.LocalGreenstone;
52import org.greenstone.gatherer.gui.tree.DragTree;
53import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
54import org.greenstone.gatherer.shell.GShell;
55import org.greenstone.gatherer.shell.GShellEvent;
56import org.greenstone.gatherer.shell.GShellListener;
57import org.greenstone.gatherer.util.Utility;
58import org.greenstone.gatherer.util.XMLTools;
59
60public class ReplaceSrcDocWithHtmlPrompt
61 extends ModalDialog
62 implements GShellListener
63{
64 /** The size of this new collection dialog box. */
65 static private Dimension SIZE = new Dimension(675, 250);
66 private JDialog self;
67
68 /** the source document files we wil be replacing with their GS3-generated html equivalent */
69 private File[] srcdoc_files = null;
70 /** the names of the srcdoc_files that could not be replaced with their GS3-generated html equivalent */
71 private java.util.Vector failedFiles = null;
72
73 /** the list of potential plugins to be used */
74 private Argument plugin_arg = null;
75 /** holds all the available options for the src-replacing script */
76 private ScriptOptions options = null;
77 /** the pane containing the options */
78 private JPanel options_pane = null;
79 /** the error message if any */
80 private StringBuffer error_message = null;
81 /** whether we were successful or not */
82 private boolean successful;
83 /** The command output of a successful execution of the replace script
84 * containing the generated tailname of the replacement file */
85 private String successfulOutput;
86
87 public ReplaceSrcDocWithHtmlPrompt(File[] source_files) {
88 super(Gatherer.g_man, true);
89 this.self = this;
90 this.srcdoc_files = source_files;
91 failedFiles = new java.util.Vector(source_files.length); // number of failures will never be more than num source docs
92
93 // check that we actually have a src doc file which can be replaced with its GS3-generated html
94 // since all the files here have the same extension, the first file can be used to work out
95 // the necessary plugin
96 ArrayList replacer_plugins = CollectionDesignManager.plugin_manager.getSrcReplacerPlugins(source_files[0]);
97 if (replacer_plugins.size() == 0) {
98 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("ReplaceSrcWithHTMLPrompt.NotSrcReplaceable"), Dictionary.get("ReplaceSrcWithHTMLPrompt.Title"), JOptionPane.ERROR_MESSAGE);
99 return;
100 }
101 plugin_arg = createPluginArgument(replacer_plugins);
102 setJMenuBar(new SimpleMenuBar("replacingSourceDoc"));
103 setSize(SIZE);
104 setTitle(Dictionary.get("ReplaceSrcWithHTMLPrompt.Title"));
105
106 // set up the script options
107 // we have empty initial values
108 String dom_string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Options/>";
109 Document doc = XMLTools.parseXML(new StringReader(dom_string));
110 options = new ScriptOptions(doc.getDocumentElement(), "replace_srcdoc_with_html.pl");
111
112 // Creation
113 JPanel content_pane = (JPanel) getContentPane();
114 content_pane.setOpaque(true);
115 content_pane.setComponentOrientation(Dictionary.getOrientation());
116 options_pane = new JPanel();
117
118 addScriptOptions(options_pane);
119 JScrollPane middle_pane = new JScrollPane(options_pane);
120 middle_pane.setComponentOrientation(Dictionary.getOrientation());
121
122 JTextArea instructions_area = new JTextArea(Dictionary.get("ReplaceSrcWithHTMLPrompt.Instructions"));
123 instructions_area.setComponentOrientation(Dictionary.getOrientation());
124 instructions_area.setEditable(false);
125 instructions_area.setLineWrap(true);
126 instructions_area.setRows(5);
127 instructions_area.setWrapStyleWord(true);
128
129 JPanel button_pane = new JPanel();
130 button_pane.setComponentOrientation(Dictionary.getOrientation());
131 JButton srcreplace_button = new GLIButton(Dictionary.get("ReplaceSrcWithHTMLPrompt.ReplaceSrc"), Dictionary.get("ReplaceSrcWithHTMLPrompt.ReplaceSrc_Tooltip"));
132 JButton cancel_button = new GLIButton(Dictionary.get("General.Cancel"), Dictionary.get("General.Cancel_Tooltip"));
133
134 // Connection
135 cancel_button.addActionListener(new CancelListener());
136 srcreplace_button.addActionListener(new SrcReplaceListener());
137
138 // Layout
139
140 button_pane.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
141 button_pane.setLayout(new GridLayout(1,2));
142 button_pane.add(srcreplace_button);
143 button_pane.add(cancel_button);
144
145 content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
146 content_pane.setLayout(new BorderLayout());
147 content_pane.add(instructions_area, BorderLayout.NORTH);
148 content_pane.add(middle_pane, BorderLayout.CENTER);
149 content_pane.add(button_pane, BorderLayout.SOUTH);
150
151 // Final dialog setup & positioning.
152 Dimension screen_size = Configuration.screen_size;
153 setLocation((screen_size.width - SIZE.width) / 2, (screen_size.height - SIZE.height) / 2);
154 setVisible(true);
155 }
156
157 public void destroy()
158 {
159
160 }
161
162 /** All implementation of GShellListener must include this method so the listener can be informed of messages from the GShell.
163 * @param event A <strong>GShellEvent</strong> that contains, amoung other things, the message.
164 */
165 public synchronized void message(GShellEvent event) {
166 String message = event.getMessage();
167 if (message.startsWith("replace_srcdoc_with_html.pl>")) {
168 message = message.substring(28); // length of "replace_srcdoc_with_html.pl>"?
169 error_message.append(message);
170 error_message.append("\n");
171 }
172 }
173
174 /** All implementation of GShellListener must include this method so the listener can be informed when a GShell begins its task. Implementation side-effect, not actually used.
175 * @param event A <strong>GShellEvent</strong> that contains details of the initial state of the <strong>GShell</strong> before task comencement.
176 */
177 public synchronized void processBegun(GShellEvent event) {
178 // We don't care.
179 }
180
181 /** All implementation of GShellListener must include this method so the listener can be informed when a GShell completes its task.
182 * @param event A <strong>GShellEvent</strong> that contains details of the final state of the <strong>GShell</strong> after task completion.
183 */
184 public synchronized void processComplete(GShellEvent event) {
185 successful = false;
186 if(event.getStatus() == GShell.OK) {
187 successful = true;
188 GShell process = (GShell)event.getSource();
189 successfulOutput = process.getCommandOutput();
190 process.resetCommandOutput();
191 }
192 }
193
194 private Argument createPluginArgument(ArrayList plugin_list) {
195 Argument arg = new Argument();
196 arg.setName("plugin");
197 arg.setDescription(Dictionary.get("ReplaceSrcWithHTMLPrompt.Plugin"));
198 arg.setRequired(true);
199 arg.setType(Argument.ENUM);
200 for (int i=0; i<plugin_list.size(); i++) {
201 Plugin p = (Plugin)plugin_list.get(i);
202 arg.addOption(p.getName(), p.getName());
203 }
204 return arg;
205 }
206 private void addScriptOptions(JPanel options_pane) {
207
208 options_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
209 options_pane.setBackground(Configuration.getColor("coloring.collection_heading_background", false));
210 options_pane.setLayout(new BoxLayout(options_pane, BoxLayout.Y_AXIS));
211
212 int current_mode = Configuration.getMode();
213 int total_argument_count = options.getArgumentCount();
214
215 // first we add the plugin arg
216 ArgumentControl argument_control = new ArgumentControl(plugin_arg, true, null);
217 argument_control.setBackground(Configuration.getColor("coloring.collection_heading_background", false));
218 options_pane.add((JComponent)argument_control);
219 for(int i = 0; i < total_argument_count; i++) {
220 // Retrieve the argument so we know how to format the control.
221 Argument argument = options.getArgument(i);
222 if(!argument.isHiddenGLI() && argument.getModeLevel() <= current_mode) {
223 // by default, all args are disabled, and no value
224 argument_control = new ArgumentControl(argument, false, null);
225
226 // make sure they are coloured the way we want - this is not the standard arg control coloring
227 argument_control.setBackground(Configuration.getColor("coloring.collection_heading_background", false));
228 options_pane.add((JComponent)argument_control);
229 }
230 }
231 }
232
233 private void updateScriptOptions() {
234 for(int i = 0; i < options_pane.getComponentCount(); i++) {
235 Component component = options_pane.getComponent(i);
236 if(component instanceof ArgumentControl) {
237 ArgumentControl ac = (ArgumentControl)component;
238 String name = ac.getArgumentName();
239 String value = ac.getValue();
240 boolean enabled = ac.isEnabled();
241 if (!enabled && value==null) {
242 // flag type, remove from options altogether
243 options.removeValue(name);
244 } else {
245 if (value.equals("")) {
246 // if the value is empty, we don't want it to be passed to the script
247 options.setValue(name, false, value);
248 } else {
249 options.setValue(name, enabled, value);
250 }
251 }
252
253 }
254 }
255 }
256
257 private int replaceSrcDoc(int fileNum)
258 {
259 // Generate the replace_srcdoc_with_html.pl command
260 ArrayList command_parts_list = new ArrayList();
261 if (Utility.isWindows() && (!Gatherer.isGsdlRemote)) {
262 command_parts_list.add(Configuration.perl_path);
263 command_parts_list.add("-S");
264 }
265 command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "replace_srcdoc_with_html.pl");
266
267 // Add in all the options from the user
268 String[] src_replace_options = options.getValues();
269 for (int i = 0; i < src_replace_options.length; i++) {
270 command_parts_list.add(src_replace_options[i]);
271 }
272
273 // Local case
274 if (!Gatherer.isGsdlRemote) {
275 // Add in the filename
276 command_parts_list.add(this.srcdoc_files[fileNum].getPath());
277 }
278 // Remote case
279 else {
280 // Add in the filename, relative to the collection directory
281 String collection_name = CollectionManager.getLoadedCollectionName();
282 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
283 String srcdoc_file_relative_path = Gatherer.remoteGreenstoneServer.getPathRelativeToDirectory(
284 this.srcdoc_files[fileNum], collection_directory_path); // preserves spaces in filename
285 command_parts_list.add("-file");
286 command_parts_list.add(srcdoc_file_relative_path);
287
288 // When running remotely we also need the collection name as the last argument
289 command_parts_list.add(collection_name);
290 }
291
292 // Run the replace_srcdoc_with_html.pl command
293 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
294 this.error_message = new StringBuffer();
295
296 GShell process = new GShell(command_parts, GShell.SRCREPLACE, 3, this, null, GShell.GSHELL_SRCREPLACE);
297 //process.start();
298 process.run();
299
300 if (successful) {
301 return 0;
302 }
303 return 1;
304 }
305
306 private void resultPrompt(boolean success, String message)
307 {
308 if (success) {
309 // !!! TO DO: Get replace_srcdoc_with_html.pl strings translated and use SimpleResultDialog below
310 JOptionPane.showMessageDialog(null, Dictionary.get("ReplaceSrcWithHTMLPrompt.Successful_ReplaceSrc"), Dictionary.get("ReplaceSrcWithHTMLPrompt.Successful_Title"), JOptionPane.INFORMATION_MESSAGE);
311 }
312 else {
313 String title = Dictionary.get("ReplaceSrcWithHTMLPrompt.Failed_Title");
314
315 // comma separated list of all the names of the files that could not be replaced
316 String failedFilenames = failedFiles.size() > 0 ? failedFiles.get(0).toString() : "";
317 for(int i = 1; i < failedFiles.size(); i++) {
318 failedFilenames = failedFilenames + ", " + failedFiles.get(i);
319 }
320
321 String label = Dictionary.get("ReplaceSrcWithHTMLPrompt.Failed_ReplaceSrc", failedFilenames);//srcdoc_file.getName());
322 SimpleResultDialog result_dialog = new SimpleResultDialog(title, label, message);
323 result_dialog.setVisible(true); // Blocks
324 result_dialog.dispose();
325 result_dialog = null;
326 }
327 }
328
329 private class CancelListener
330 implements ActionListener {
331 public void actionPerformed(ActionEvent event) {
332 self.dispose();
333 }
334 }
335
336 private class SrcReplaceListener
337 implements ActionListener {
338
339 public void actionPerformed(ActionEvent event) {
340 Gatherer.g_man.wait(true);
341 // update the options
342 updateScriptOptions();
343 self.dispose();
344 (new ReplaceSrcDocWithHtmlTask()).start();
345 }
346 }
347
348
349 private class ReplaceSrcDocWithHtmlTask
350 extends Thread
351 {
352 public ReplaceSrcDocWithHtmlTask()
353 {
354 }
355
356 public void run()
357 {
358 int exit_value = 0;
359 String errMsg = "";
360
361 // We're going to try replacing all selected documents and then
362 // display errormessages
363 // first run the replace process for all src files, and accumulate error exit values (0 means it's fine)
364 for(int i = 0; i < srcdoc_files.length; i++) {
365 int exit_value_this_time = replaceSrcDoc(i);
366 exit_value += exit_value_this_time; // if all files successfully replaced, exit_value will stay at 0
367
368 // accumulate all error and success msgs to display after processing all the files
369 // that are to be replaced
370 errMsg += error_message.toString();
371 error_message = null;
372
373 if(exit_value_this_time != 0) {
374 failedFiles.add(srcdoc_files[i].getName()); // add this file to list of failures
375 } else {
376 if (Gatherer.isGsdlRemote) {
377 //System.err.println("*****ReplaceSrcDocWithHtmlPrompt.java - run() - gsdl remote case");
378
379 // Conversion may have renamed the file by URL- or base64-encoding it.
380 // The new replacement file's tailname is the last line of the script output.
381 String[] lines = successfulOutput.split("\n");
382 String suffixlessFilename = lines[lines.length-1];
383 String htmlFile = suffixlessFilename+".html";
384
385 // Delete the local copy of the old source document file on the client side
386 // (it's already been replaced on the server side), and download the updated
387 // (html) file and any directory containing associated files
388 Utility.delete(srcdoc_files[i]); // remove the local copy of src doc
389
390 // download the generated html file from the server side to put it
391 // into the import directory on the client side
392 Gatherer.remoteGreenstoneServer.downloadCollectionFile(
393 CollectionManager.getLoadedCollectionName(),
394 new File(srcdoc_files[i].getParentFile(), htmlFile));
395
396 // download any assoc folder which is srcfilename+"_files"
397 File assoc_folder = new File(srcdoc_files[i].getParentFile(), suffixlessFilename+"_files");
398 // If an associated_folder by such a name exists, download it
399 if(Gatherer.remoteGreenstoneServer.exists(CollectionManager.getLoadedCollectionName(), assoc_folder)) {
400 Gatherer.remoteGreenstoneServer.downloadCollectionFile(
401 CollectionManager.getLoadedCollectionName(), assoc_folder);
402 }
403 }
404 // Whether remote or local case, need to refressh the GLI filemanager system to show
405 // what files are in the current collection space
406 Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED); // refreshes coll's content view
407 Gatherer.g_man.wait(false);
408 }
409 } // end for loop
410
411 // Display error messages now that we finished processing the multiple files
412 if(exit_value != 0) {
413 resultPrompt(false, errMsg);
414 } else {
415 resultPrompt(true, errMsg);
416 }
417 } // end run method
418
419 } //end Task class
420}
Note: See TracBrowser for help on using the repository browser.