0001 /*
0002 * Copyright (c) 1995-2010, The University of Sheffield. See the file
0003 * COPYRIGHT.txt in the software or at http://gate.ac.uk/gate/COPYRIGHT.txt
0004 *
0005 * This file is part of GATE (see http://gate.ac.uk/), and is free
0006 * software, licenced under the GNU Library General Public License,
0007 * Version 2, June 1991 (in the distribution as file licence.html,
0008 * and also available at http://gate.ac.uk/gate/licence.html).
0009 *
0010 * Angel Kirilov 26/03/2002
0011 *
0012 * $Id: ShellSlacFrame.java 12919 2010-08-03 10:31:37Z valyt $
0013 *
0014 */
0015
0016 package gate.gui;
0017
0018 import java.awt.*;
0019 import java.awt.event.ActionEvent;
0020 import java.awt.event.ActionListener;
0021 import java.io.*;
0022 import java.net.MalformedURLException;
0023 import java.net.URL;
0024 import java.text.NumberFormat;
0025 import java.util.*;
0026 import java.util.List;
0027
0028 import javax.swing.*;
0029 import javax.swing.tree.DefaultMutableTreeNode;
0030
0031 import gate.*;
0032 import gate.creole.ResourceData;
0033 import gate.creole.ResourceInstantiationException;
0034 import gate.event.CreoleEvent;
0035 import gate.persist.PersistenceException;
0036 import gate.swing.XJMenuItem;
0037 import gate.util.*;
0038 //import guk.im.*;
0039
0040
0041 /**
0042 * The main Shell SLAC Gate GUI frame.
0043 */
0044 public class ShellSlacFrame extends MainFrame {
0045
0046 /** Debug flag */
0047 private static final boolean DEBUG = false;
0048
0049 /** Shell GUI application */
0050 private CorpusController application = null;
0051
0052 /** Shell GUI corpus */
0053 private Corpus corpus = null;
0054 private Corpus oneDocCorpus = null;
0055
0056 /** Shell GUI documents DataStore */
0057 private DataStore dataStore = null;
0058
0059 /** Keep this action for enable/disable the menu item */
0060 private Action saveAction = null;
0061 /** Keep this action for enable/disable the menu item */
0062 private Action runOneAction = null;
0063 private Action runAction = null;
0064
0065 /** Default corpus resource name */
0066 public static final String DEFAULT_SLUG_CORPUS_NAME = "SLUG Corpus";
0067 public static final String ONE_DOC_SLUG_CORPUS_NAME = "SLUG One Doc Corpus";
0068
0069 /** New frame */
0070 public ShellSlacFrame() {
0071 super(true, null);
0072 // guiRoots.clear();
0073 // guiRoots.add(this);
0074
0075 initShellSlacLocalData();
0076 initShellSlacGuiComponents();
0077 } // ShellSlacFrame
0078
0079 protected void initShellSlacLocalData(){
0080 createCorpus();
0081 // createDefaultApplication();
0082 String applicationURL =
0083 System.getProperty(GateConstants.APPLICATION_JAVA_PROPERTY_NAME);
0084 if(applicationURL != null) {
0085 createDefaultApplication(applicationURL);
0086 }
0087 else {
0088 // create default ANNIE
0089 createDefaultApplication();
0090 } // if
0091
0092 dataStore = null;
0093 } // initLocalData
0094
0095 protected void initShellSlacGuiComponents() {
0096 super.setJMenuBar(createMenuBar());
0097 } // initShellSlacGuiComponents()
0098
0099 /** Create the new Shell SLAC menu */
0100 private JMenuBar createMenuBar() {
0101 //MENUS
0102 JMenuBar retMenuBar = new JMenuBar();
0103
0104 JMenu fileMenu = new JMenu("File");
0105 Action action;
0106
0107 ResourceData rDataDocument = getDocumentResourceData();
0108 if(rDataDocument != null) {
0109 action = new NewResourceAction(rDataDocument);
0110 action.putValue(Action.NAME, "New Document");
0111 action.putValue(Action.SHORT_DESCRIPTION,"Create a new document");
0112
0113 fileMenu.add(new XJMenuItem(action, this));
0114
0115 } // if
0116
0117 // Open All... action - open multiple files from directory
0118 corpusFiller = new CorpusFillerComponent();
0119 action = new PopulateCorpusAction();
0120 action.putValue(Action.NAME, "New Documents...");
0121 action.putValue(Action.SHORT_DESCRIPTION,"Create multiple documents");
0122 fileMenu.add(new XJMenuItem(action, this));
0123
0124 fileMenu.add(new XJMenuItem(new CloseSelectedDocumentAction(), this));
0125 fileMenu.add(new XJMenuItem(new CloseAllDocumentAction(), this));
0126
0127 fileMenu.addSeparator();
0128
0129 action = new ImportDocumentAction();
0130 fileMenu.add(new XJMenuItem(action, this));
0131
0132 JMenu exportMenu = new JMenu("Export");
0133 action = new ExportDocumentAction();
0134 exportMenu.add(new XJMenuItem(action, this));
0135 action = new ExportDocumentInlineAction();
0136 exportMenu.add(new XJMenuItem(action, this));
0137 fileMenu.add(exportMenu);
0138
0139 JMenu exportAllMenu = new JMenu("Export All");
0140 action = new ExportAllDocumentAction();
0141 exportAllMenu.add(new XJMenuItem(action, this));
0142 action = new ExportAllDocumentInlineAction();
0143 exportAllMenu.add(new XJMenuItem(action, this));
0144 fileMenu.add(exportAllMenu);
0145
0146 /*
0147 action = new StoreAllDocumentAction();
0148 action.setEnabled(false);
0149 saveAction = action;
0150 fileMenu.add(new XJMenuItem(action, this));
0151 action = new StoreAllDocumentAsAction();
0152 fileMenu.add(new XJMenuItem(action, this));
0153 action = new LoadAllDocumentAction();
0154 fileMenu.add(new XJMenuItem(action, this));
0155
0156 action = new LoadResourceFromFileAction();
0157 action.putValue(action.NAME, "Load application");
0158 fileMenu.add(new XJMenuItem(action, this));
0159
0160 action = new RestoreDefaultApplicationAction();
0161 fileMenu.add(new XJMenuItem(action, this));
0162
0163 action = new TestStoreAction();
0164 fileMenu.add(new XJMenuItem(action, this));
0165 */
0166
0167 fileMenu.addSeparator();
0168
0169 // action = new ExitGateAction();
0170 // define exit action without save of session
0171 action = new AbstractAction () {
0172 public void actionPerformed(ActionEvent e) {
0173 setVisible(false);
0174 dispose();
0175 System.exit(0);
0176 }
0177 };
0178 action.putValue(Action.NAME, "Exit");
0179 fileMenu.add(new XJMenuItem(action, this));
0180 retMenuBar.add(fileMenu);
0181
0182 JMenu analyseMenu = new JMenu("Analyse");
0183
0184 action = new RunApplicationOneDocumentAction();
0185 if(application == null) {
0186 action.setEnabled(false);
0187 } // if
0188 runOneAction = action;
0189 analyseMenu.add(new XJMenuItem(action, this));
0190 retMenuBar.add(analyseMenu);
0191
0192 action = new RunApplicationAction();
0193 if(application == null) {
0194 action.setEnabled(false);
0195 } // if
0196 runAction = action;
0197 analyseMenu.add(new XJMenuItem(action, this));
0198 retMenuBar.add(analyseMenu);
0199
0200 JMenu toolsMenu = new JMenu("Tools");
0201 createToolsMenuItems(toolsMenu);
0202 retMenuBar.add(toolsMenu);
0203
0204 JMenu helpMenu = new JMenu("Help");
0205 helpMenu.add(new HelpAboutSlugAction());
0206 retMenuBar.add(helpMenu);
0207
0208 return retMenuBar;
0209 } // createMenuBar()
0210
0211 /** Should check for registered Creole components and populate menu.
0212 * <BR> In first version is hardcoded. */
0213 private void createToolsMenuItems(JMenu toolsMenu) {
0214 toolsMenu.add(new NewAnnotDiffAction());
0215 toolsMenu.add(
0216 new AbstractAction("Unicode editor", getIcon("unicode")){
0217 public void actionPerformed(ActionEvent evt){
0218 new guk.Editor();
0219 }
0220 });
0221
0222 if (System.getProperty("gate.slug.gazetteer") != null)
0223 toolsMenu.add(new NewGazetteerEditorAction());
0224
0225 } // createToolsMenuItems()
0226
0227 /** Find ResourceData for "Create Document" menu item. */
0228 private ResourceData getDocumentResourceData() {
0229 ResourceData result = null;
0230
0231 CreoleRegister reg = Gate.getCreoleRegister();
0232 List lrTypes = reg.getPublicLrTypes();
0233
0234 if(lrTypes != null && !lrTypes.isEmpty()){
0235 Iterator lrIter = lrTypes.iterator();
0236 while(lrIter.hasNext()){
0237 ResourceData rData = (ResourceData)reg.get(lrIter.next());
0238 if("gate.corpora.DocumentImpl".equalsIgnoreCase(rData.getClassName())) {
0239 result = rData;
0240 break;
0241 } // if
0242 } // while
0243 } // if
0244
0245 return result;
0246 } // getDocumentResourceData()
0247
0248 /** Here default ANNIE is created. Could be changed. */
0249 private void createDefaultApplication() {
0250 // Loads ANNIE with defaults
0251 Runnable loadAction = new ANNIERunnable(ShellSlacFrame.this);
0252
0253 Thread thread = new Thread(loadAction, "");
0254 thread.setPriority(Thread.MIN_PRIORITY);
0255 thread.start();
0256 } // createDefaultApplication
0257
0258 /** Load serialized application from file. */
0259 private void createDefaultApplication(String url) {
0260 ApplicationLoadRun run = new ApplicationLoadRun(url, this);
0261 Thread thread = new Thread(run, "");
0262 thread.setPriority(Thread.MIN_PRIORITY);
0263 thread.start();
0264 } // createDefaultApplication
0265
0266 /** Create corpus for application */
0267 private void createCorpus() {
0268 try {
0269 Factory.newCorpus(DEFAULT_SLUG_CORPUS_NAME);
0270 Factory.newCorpus(ONE_DOC_SLUG_CORPUS_NAME);
0271 } catch (ResourceInstantiationException ex) {
0272 ex.printStackTrace();
0273 throw new GateRuntimeException("Error in creating build in corpus.");
0274 } // catch
0275 } // createCorpus()
0276
0277 /** Override base class method */
0278 public void resourceLoaded(CreoleEvent e) {
0279 super.resourceLoaded(e);
0280
0281 Resource res = e.getResource();
0282
0283 if(res instanceof CorpusController) {
0284 if(application != null) {
0285 // remove old application
0286 Factory.deleteResource(application);
0287 } // if
0288 application = (CorpusController) res;
0289
0290 runOneAction.setEnabled(true);
0291 runAction.setEnabled(true);
0292 if(corpus != null)
0293 application.setCorpus(corpus);
0294 } // if
0295
0296 if(res instanceof Corpus) {
0297 Corpus resCorpus = (Corpus) res;
0298
0299 if(DEFAULT_SLUG_CORPUS_NAME.equals(resCorpus.getName())) {
0300 corpus = resCorpus;
0301 if(application != null)
0302 application.setCorpus(corpus);
0303 } // if
0304
0305 if(ONE_DOC_SLUG_CORPUS_NAME.equals(resCorpus.getName())) {
0306 oneDocCorpus = resCorpus;
0307 } // if
0308 } // if
0309
0310 if(res instanceof Document) {
0311 final Document doc = (Document) res;
0312 corpus.add(doc);
0313 if(DEBUG) Out.println("Document loaded, showing...");
0314 SwingUtilities.invokeLater(new Runnable() {
0315 public void run() {
0316 showDocument(doc);
0317 }
0318 });
0319 } // if
0320 }// resourceLoaded();
0321
0322 /** Find in resource tree and show the document */
0323 protected void showDocument(Document doc) {
0324 // should find NameBearerHandle for document and call
0325 Handle handle = null;
0326 Enumeration nodesEnum = resourcesTreeRoot.preorderEnumeration();
0327 boolean done = false;
0328 DefaultMutableTreeNode node = resourcesTreeRoot;
0329 Object obj;
0330
0331 while(!done && nodesEnum.hasMoreElements()){
0332 node = (DefaultMutableTreeNode)nodesEnum.nextElement();
0333 obj = node.getUserObject();
0334 if(obj instanceof Handle) {
0335 handle = (Handle)obj;
0336 obj = handle.getTarget();
0337 done = obj instanceof Document
0338 && doc == (Document)obj;
0339 } // if
0340 } // while
0341
0342 if(done){
0343 select(handle);
0344 } // if
0345 else {
0346 if(DEBUG) Out.println("Failed to find handle for document");
0347 }
0348 } // showDocument(Document doc)
0349
0350 /** Called when a {@link gate.DataStore} has been opened.
0351 * Save corpus on datastore open. */
0352 public void datastoreOpened(CreoleEvent e){
0353 super.datastoreOpened(e);
0354 if(corpus == null) return;
0355
0356 DataStore ds = e.getDatastore();
0357 try {
0358 if(dataStore != null) {
0359 // close old datastore if any
0360 dataStore.close();
0361 } // if
0362 // put documents in datastore
0363 saveAction.setEnabled(false);
0364
0365 LanguageResource persCorpus = ds.adopt(corpus, null);
0366 ds.sync(persCorpus);
0367 // change corpus with the new persistent corpus
0368 Factory.deleteResource((LanguageResource)corpus);
0369 corpus = (Corpus) persCorpus;
0370 if(application != null) application.setCorpus(corpus);
0371
0372 dataStore = ds;
0373 saveAction.setEnabled(true);
0374 } catch (PersistenceException pex) {
0375 pex.printStackTrace();
0376 } catch (gate.security.SecurityException sex) {
0377 sex.printStackTrace();
0378 } // catch
0379 } // datastoreOpened(CreoleEvent e)
0380
0381 /** Return handle to selected tab resource */
0382 private Handle getSelectedResource() {
0383 JComponent largeView = (JComponent)
0384 mainTabbedPane.getSelectedComponent();
0385
0386 Handle result = null;
0387 Enumeration nodesEnum = resourcesTreeRoot.preorderEnumeration();
0388 boolean done = false;
0389 DefaultMutableTreeNode node = resourcesTreeRoot;
0390 while(!done && nodesEnum.hasMoreElements()){
0391 node = (DefaultMutableTreeNode)nodesEnum.nextElement();
0392 done = node.getUserObject() instanceof Handle &&
0393 ((Handle)node.getUserObject()).getLargeView()
0394 == largeView;
0395 }
0396 if(done)
0397 result = (Handle)node.getUserObject();
0398
0399 return result;
0400 } // getSelectedResource()
0401
0402 /** Export All store of documents from SLUG corpus */
0403 private void saveDocuments(File targetDir) {
0404 if(corpus == null || corpus.size() == 0) return;
0405
0406 Document doc;
0407 String target = targetDir.getPath();
0408 URL fileURL;
0409 String fileName = null;
0410 int index;
0411
0412 MainFrame.lockGUI("Export all documents...");
0413
0414 target = target+File.separatorChar;
0415 for(int i=0; i<corpus.size(); ++i) {
0416 doc = (Document) corpus.get(i);
0417 fileURL = doc.getSourceUrl();
0418 if(fileURL != null)
0419 fileName = fileURL.toString();
0420 index = fileName.lastIndexOf('/');
0421 if(index != -1) {
0422 fileName = fileName.substring(index+1, fileName.length());
0423 }
0424 else
0425 fileName = "content_txt";
0426
0427 // create full file name
0428 fileName = target + fileName+".xml";
0429 try{
0430
0431 // Prepare to write into the xmlFile using UTF-8 encoding
0432 OutputStreamWriter writer = new OutputStreamWriter(
0433 new FileOutputStream(new File(fileName)),"UTF-8");
0434
0435 // Write (test the toXml() method)
0436 // This Action is added only when a gate.Document is created.
0437 // So, is for sure that the resource is a gate.Document
0438 writer.write(doc.toXml());
0439 writer.flush();
0440 writer.close();
0441 } catch (Exception ex){
0442 ex.printStackTrace(Out.getPrintWriter());
0443 } finally{
0444 MainFrame.unlockGUI();
0445 } // finally
0446 } // for
0447
0448 MainFrame.unlockGUI();
0449 } // saveDocuments(File targetDir)
0450
0451 //------------------------------------------------------------------------------
0452 // Inner classes section
0453
0454 /** Run the current application SLAC */
0455 class RunApplicationAction extends AbstractAction {
0456 public RunApplicationAction() {
0457 super("Analyse All", getIcon("menu_controller"));
0458 putValue(SHORT_DESCRIPTION, "Run the application to process documents");
0459 } // RunApplicationAction()
0460
0461 public void actionPerformed(ActionEvent e) {
0462 if (application != null && corpus != null && corpus.size() > 0) {
0463 application.setCorpus(corpus);
0464 SerialControllerEditor editor = new SerialControllerEditor();
0465 editor.setTarget(application);
0466 editor.runAction.actionPerformed(null);
0467 } // if
0468 } // actionPerformed(ActionEvent e)
0469 } // class RunApplicationAction extends AbstractAction
0470
0471 /** Run the current application SLAC on current document */
0472 class RunApplicationOneDocumentAction extends AbstractAction {
0473 public RunApplicationOneDocumentAction() {
0474 super("Analyse", getIcon("menu_controller"));
0475 putValue(SHORT_DESCRIPTION,
0476 "Run the application to process current document");
0477 } // RunApplicationOneDocumentAction()
0478
0479 public void actionPerformed(ActionEvent e) {
0480 if (application != null) {
0481 Handle handle = getSelectedResource();
0482 if(handle == null) return;
0483 Object target = handle.getTarget();
0484 if(target == null) return;
0485
0486 if(target instanceof Document) {
0487 Document doc = (Document) target;
0488 oneDocCorpus.clear();
0489 oneDocCorpus.add(doc);
0490
0491 application.setCorpus(oneDocCorpus);
0492
0493 SerialControllerEditor editor = new SerialControllerEditor();
0494 editor.setTarget(application);
0495 editor.runAction.actionPerformed(null);
0496 } // if - Document
0497 } // if
0498 } // actionPerformed(ActionEvent e)
0499 } // class RunApplicationOneDocumentAction extends AbstractAction
0500
0501 class RestoreDefaultApplicationAction extends AbstractAction {
0502 public RestoreDefaultApplicationAction() {
0503 super("Create ANNIE application");
0504 putValue(SHORT_DESCRIPTION, "Create default ANNIE application");
0505 } // RestoreDefaultApplicationAction()
0506
0507 public void actionPerformed(ActionEvent e) {
0508 createDefaultApplication();
0509 } // actionPerformed(ActionEvent e)
0510 } // class RestoreDefaultApplicationAction extends AbstractAction
0511
0512 class CloseSelectedDocumentAction extends AbstractAction {
0513 public CloseSelectedDocumentAction() {
0514 super("Close Document");
0515 putValue(SHORT_DESCRIPTION, "Closes the selected document");
0516 } // CloseSelectedDocumentAction()
0517
0518 public void actionPerformed(ActionEvent e) {
0519 JComponent resource = (JComponent)
0520 mainTabbedPane.getSelectedComponent();
0521 if (resource != null){
0522 Action act = resource.getActionMap().get("Close resource");
0523 if (act != null)
0524 act.actionPerformed(null);
0525 }// End if
0526 } // actionPerformed(ActionEvent e)
0527 } // class CloseSelectedDocumentAction extends AbstractAction
0528
0529 class CloseAllDocumentAction extends AbstractAction {
0530 public CloseAllDocumentAction() {
0531 super("Close All");
0532 putValue(SHORT_DESCRIPTION, "Closes all documents");
0533 } // CloseAllDocumentAction()
0534
0535 public void actionPerformed(ActionEvent e) {
0536 JComponent resource;
0537 for(int i=mainTabbedPane.getTabCount()-1; i>0; --i) {
0538
0539 resource = (JComponent) mainTabbedPane.getComponentAt(i);
0540 if (resource != null){
0541 Action act = resource.getActionMap().get("Close resource");
0542 if (act != null)
0543 act.actionPerformed(null);
0544 }// End if
0545 } // for
0546 } // actionPerformed(ActionEvent e)
0547 } // class CloseAllDocumentAction extends AbstractAction
0548
0549 class StoreAllDocumentAsAction extends AbstractAction {
0550 public StoreAllDocumentAsAction() {
0551 super("Store all Documents As...");
0552 putValue(SHORT_DESCRIPTION,
0553 "Store all opened in the application documents in new directory");
0554 } // StoreAllDocumentAsAction()
0555
0556 public void actionPerformed(ActionEvent e) {
0557 createSerialDataStore();
0558 } // actionPerformed(ActionEvent e)
0559 } // class StoreAllDocumentAction extends AbstractAction
0560
0561 class StoreAllDocumentAction extends AbstractAction {
0562 public StoreAllDocumentAction() {
0563 super("Store all Documents");
0564 putValue(SHORT_DESCRIPTION,"Store all opened in the application documents");
0565 } // StoreAllDocumentAction()
0566
0567 public void actionPerformed(ActionEvent e) {
0568 if(dataStore != null) {
0569 try {
0570 dataStore.sync(corpus);
0571 } catch (PersistenceException pex) {
0572 pex.printStackTrace();
0573 } catch (gate.security.SecurityException sex) {
0574 sex.printStackTrace();
0575 } // catch
0576 } // if
0577 } // actionPerformed(ActionEvent e)
0578 } // class StoreAllDocumentAction extends AbstractAction
0579
0580 class LoadAllDocumentAction extends AbstractAction {
0581 public LoadAllDocumentAction() {
0582 super("Load all Documents");
0583 putValue(SHORT_DESCRIPTION,"Load documents from storage");
0584 } // StoreAllDocumentAction()
0585
0586 public void actionPerformed(ActionEvent e) {
0587 if(dataStore != null) {
0588 // on close all resources will be closed too
0589 try {
0590 dataStore.close();
0591 } catch (PersistenceException pex) {
0592 pex.printStackTrace();
0593 } // catch
0594 dataStore = null;
0595 } // if
0596
0597 // should open a datastore
0598 dataStore = openSerialDataStore();
0599
0600 if(dataStore != null) {
0601 // load from datastore
0602 List corporaIDList = null;
0603 List docIDList = null;
0604 String docID = "";
0605 FeatureMap features;
0606 Document doc;
0607
0608 try {
0609 corporaIDList = dataStore.getLrIds("gate.corpora.CorpusImpl");
0610 docIDList = dataStore.getLrIds("gate.corpora.DocumentImpl");
0611 } catch (PersistenceException pex) {
0612 pex.printStackTrace();
0613 } // catch
0614
0615 features = Factory.newFeatureMap();
0616 features.put(DataStore.LR_ID_FEATURE_NAME, docID);
0617 features.put(DataStore.DATASTORE_FEATURE_NAME, dataStore);
0618
0619 for(int i=0; i < docIDList.size(); ++i) {
0620 docID = (String) docIDList.get(i);
0621 // read the document back
0622 features.put(DataStore.LR_ID_FEATURE_NAME, docID);
0623 doc = null;
0624 try {
0625 doc = (Document)
0626 Factory.createResource("gate.corpora.DocumentImpl", features);
0627 } catch (gate.creole.ResourceInstantiationException rex) {
0628 rex.printStackTrace();
0629 } // catch
0630
0631 if(doc != null) corpus.add(doc);
0632 } // for
0633 } // if
0634
0635 } // actionPerformed(ActionEvent e)
0636 } // class LoadAllDocumentAction extends AbstractAction
0637
0638 class TestStoreAction extends AbstractAction {
0639 public TestStoreAction() {
0640 super("Test Store application");
0641 putValue(SHORT_DESCRIPTION,"Store the application");
0642 } // TestStoreAction()
0643
0644 public void actionPerformed(ActionEvent e) {
0645 if(application != null) {
0646 // load/store test
0647 try {
0648 File file = new File("D:/temp/tempapplication.tmp");
0649 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
0650 long startTime = System.currentTimeMillis();
0651 oos.writeObject(application);
0652 long endTime = System.currentTimeMillis();
0653
0654 System.out.println("Storing completed in " +
0655 NumberFormat.getInstance().format(
0656 (double)(endTime - startTime) / 1000) + " seconds");
0657
0658 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
0659 Object object;
0660 startTime = System.currentTimeMillis();
0661 object = ois.readObject();
0662 endTime = System.currentTimeMillis();
0663 application = (CorpusController) object;
0664
0665 System.out.println("Loading completed in " +
0666 NumberFormat.getInstance().format(
0667 (double)(endTime - startTime) / 1000) + " seconds");
0668
0669 } catch (Exception ex) {
0670 ex.printStackTrace();
0671 } // catch
0672 } // if
0673 } // actionPerformed(ActionEvent e)
0674 } // class TestStoreAction extends AbstractAction
0675
0676 /** Import document action */
0677 class ImportDocumentAction extends AbstractAction {
0678 public ImportDocumentAction() {
0679 super("Import");
0680 putValue(SHORT_DESCRIPTION, "Open a document in XML format");
0681 } // ImportDocumentAction()
0682
0683 public void actionPerformed(ActionEvent e) {
0684 fileChooser.setDialogTitle("Select file to Import from");
0685 fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
0686
0687 int res = fileChooser.showOpenDialog(ShellSlacFrame.this);
0688 if(res == JFileChooser.APPROVE_OPTION) {
0689 File file = fileChooser.getSelectedFile();
0690
0691 String str = "";
0692 char chArr[] = new char[1024];
0693
0694 try {
0695 FileReader reader = new FileReader(file);
0696 int readedChars = reader.read(chArr);
0697 reader.close();
0698 str = new String(chArr, 0, readedChars);
0699 } catch (Exception ex) {
0700 // do nothing - some error, so we shouldn't read file anyway
0701 } // catch
0702
0703 boolean isGateXmlDocument = false;
0704 // Detect whether or not is a GateXmlDocument
0705 if(str.indexOf("<GateDocument") != -1 ||
0706 str.indexOf(" GateDocument") != -1)
0707 isGateXmlDocument = true;
0708
0709 if(isGateXmlDocument) {
0710 Runnable run = new ImportRunnable(file);
0711 Thread thread = new Thread(run, "");
0712 thread.setPriority(Thread.MIN_PRIORITY);
0713 thread.start();
0714 }
0715 else {
0716 JOptionPane.showMessageDialog(ShellSlacFrame.this,
0717 "The import file '"+file.getAbsolutePath()+"'\n"
0718 +"is not a SLUG document.",
0719 "Import error",
0720 JOptionPane.WARNING_MESSAGE);
0721 } // if
0722 } // if
0723 } // actionPerformed(ActionEvent e)
0724 } // class ImportDocumentAction extends AbstractAction
0725
0726 /** Object to run ExportAll in a new Thread */
0727 private class ImportRunnable implements Runnable {
0728 File file;
0729 ImportRunnable(File targetFile) {
0730 file = targetFile;
0731 } // ImportRunnable(File targetDirectory)
0732
0733 public void run() {
0734 if(file != null) {
0735 MainFrame.lockGUI("Import file...");
0736 try {
0737 Factory.newDocument(file.toURI().toURL());
0738 } catch (MalformedURLException mex) {
0739 mex.printStackTrace();
0740 } catch (ResourceInstantiationException rex) {
0741 rex.printStackTrace();
0742 } finally {
0743 MainFrame.unlockGUI();
0744 } // finally
0745 } // if
0746 } // run()
0747 } // ImportRunnable
0748
0749 /** Export current document action */
0750 class ExportDocumentInlineAction extends AbstractAction {
0751 public ExportDocumentInlineAction() {
0752 super("with inline markup");
0753 putValue(SHORT_DESCRIPTION, "Save the selected document in XML format"
0754 +" with inline markup");
0755 } // ExportDocumentInlineAction()
0756
0757 public void actionPerformed(ActionEvent e) {
0758 JComponent resource = (JComponent)
0759 mainTabbedPane.getSelectedComponent();
0760 if (resource == null) return;
0761 Component c;
0762 Document doc = null;
0763
0764 for(int i=0; i<resource.getComponentCount(); ++i) {
0765 c = resource.getComponent(i);
0766 if(c instanceof DocumentEditor) {
0767 doc = ((DocumentEditor) c).getDocument();
0768 } // if
0769 } // for
0770
0771 if(doc != null) {
0772 JFileChooser fileChooser = MainFrame.getFileChooser();
0773 File selectedFile = null;
0774
0775 fileChooser.setMultiSelectionEnabled(false);
0776 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
0777 fileChooser.setDialogTitle("Select document to save ...");
0778 fileChooser.setSelectedFiles(null);
0779
0780 int res = fileChooser.showDialog(ShellSlacFrame.this, "Save");
0781 if(res == JFileChooser.APPROVE_OPTION){
0782 selectedFile = fileChooser.getSelectedFile();
0783 fileChooser.setCurrentDirectory(fileChooser.getCurrentDirectory());
0784
0785 // store document with annotations Document.toXML()
0786 Runnable run = new ExportInline(doc, selectedFile);
0787 Thread thread = new Thread(run, "");
0788 thread.setPriority(Thread.MIN_PRIORITY);
0789 thread.start();
0790 } // if
0791 }// End if
0792 } // actionPerformed(ActionEvent e)
0793 } // class ExportDocumentInlineAction extends AbstractAction
0794
0795 /** New thread object for export inline */
0796 private class ExportInline implements Runnable {
0797 File targetFile;
0798 Document document;
0799
0800 ExportInline(Document doc, File target) {
0801 targetFile = target;
0802 document = doc;
0803 } // ExportAllRunnable(File targetDirectory)
0804
0805 protected Set getTypes(String types) {
0806 Set set = new HashSet();
0807 StringTokenizer tokenizer = new StringTokenizer(types, ";");
0808
0809 while(tokenizer.hasMoreTokens()) {
0810 set.add(tokenizer.nextToken());
0811 } // while
0812
0813 return set;
0814 }
0815
0816 public void run() {
0817 if(document == null || targetFile == null) return;
0818 MainFrame.lockGUI("Store document with inline markup...");
0819 try{
0820 AnnotationSet annotationsToDump = null;
0821 annotationsToDump = document.getAnnotations();
0822 // check for restriction from Java property
0823 String enumaratedAnnTypes =
0824 System.getProperty(GateConstants.ANNOT_TYPE_TO_EXPORT);
0825
0826 if(enumaratedAnnTypes != null) {
0827 Set typesSet = getTypes(enumaratedAnnTypes);
0828 annotationsToDump = annotationsToDump.get(typesSet);
0829 } // if
0830
0831 // Prepare to write into the xmlFile using the original encoding
0832 String encoding = ((gate.TextualDocument)document).getEncoding();
0833 if(encoding == null || encoding.length() == 0)
0834 encoding = System.getProperty("file.encoding");
0835 if(encoding == null || encoding.length() == 0) encoding = "UTF-8";
0836
0837 OutputStreamWriter writer = new OutputStreamWriter(
0838 new FileOutputStream(targetFile),
0839 encoding);
0840
0841 //determine if the features need to be saved first
0842 Boolean featuresSaved =
0843 Gate.getUserConfig().getBoolean(
0844 GateConstants.SAVE_FEATURES_WHEN_PRESERVING_FORMAT);
0845 boolean saveFeatures = true;
0846 if (featuresSaved != null)
0847 saveFeatures = featuresSaved.booleanValue();
0848
0849 // Write with the toXml() method
0850 String toXml = document.toXml(annotationsToDump, saveFeatures);
0851
0852 // check for plain text feature and add root XML tag <GATE>
0853 String mimeType = (String) document.getFeatures().get("MimeType");
0854 if("text/plain".equalsIgnoreCase(mimeType)) {
0855 toXml = "<GATE>\n"+ toXml + "\n</GATE>";
0856 } // if
0857
0858 writer.write(toXml);
0859 writer.flush();
0860 writer.close();
0861 } catch (Exception ex){
0862 ex.printStackTrace(Out.getPrintWriter());
0863 }// End try
0864
0865 MainFrame.unlockGUI();
0866 } // run()
0867 } // ExportInline
0868
0869 /** Export current document action */
0870 class ExportDocumentAction extends AbstractAction {
0871 public ExportDocumentAction() {
0872 super("in GATE format");
0873 putValue(SHORT_DESCRIPTION, "Save the selected document in XML format");
0874 } // ExportDocumentAction()
0875
0876 public void actionPerformed(ActionEvent e) {
0877 JComponent resource = (JComponent)
0878 mainTabbedPane.getSelectedComponent();
0879 if (resource != null){
0880 Action act = resource.getActionMap().get("Save As XML");
0881 if (act != null)
0882 act.actionPerformed(null);
0883 }// End if
0884 } // actionPerformed(ActionEvent e)
0885 } // class ExportDocumentAction extends AbstractAction
0886
0887 /** Export All menu action */
0888 class ExportAllDocumentAction extends AbstractAction {
0889 public ExportAllDocumentAction() {
0890 super("in GATE format");
0891 putValue(SHORT_DESCRIPTION, "Save all documents in XML format");
0892 } // ExportAllDocumentAction()
0893
0894 public void actionPerformed(ActionEvent e) {
0895 fileChooser.setDialogTitle("Select Export directory");
0896 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
0897
0898 int res = fileChooser.showOpenDialog(ShellSlacFrame.this);
0899 if(res == JFileChooser.APPROVE_OPTION) {
0900 File directory = fileChooser.getSelectedFile();
0901 if(directory != null && directory.isDirectory()) {
0902 Runnable run = new ExportAllRunnable(directory);
0903 Thread thread = new Thread(run, "");
0904 thread.setPriority(Thread.MIN_PRIORITY);
0905 thread.start();
0906 } // if
0907 } // if
0908 } // actionPerformed(ActionEvent e)
0909 } // class ExportAllDocumentAction extends AbstractAction
0910
0911 /** Export All Inline menu action */
0912 class ExportAllDocumentInlineAction extends AbstractAction {
0913 public ExportAllDocumentInlineAction() {
0914 super("with inline markup");
0915 putValue(SHORT_DESCRIPTION, "Save all documents in XML format"
0916 +" with inline markup");
0917 } // ExportAllDocumentInlineAction()
0918
0919 public void actionPerformed(ActionEvent e) {
0920 fileChooser.setDialogTitle("Select Export directory");
0921 fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
0922
0923 int res = fileChooser.showOpenDialog(ShellSlacFrame.this);
0924 if(res == JFileChooser.APPROVE_OPTION) {
0925 File directory = fileChooser.getSelectedFile();
0926 if(directory != null && directory.isDirectory()) {
0927 Document currentDoc;
0928 String fileName;
0929 URL fileURL;
0930 Runnable run;
0931 Thread thread;
0932
0933 for(int i=0; i<corpus.size(); ++i) {
0934 currentDoc = (Document) corpus.get(i);
0935
0936 fileURL = currentDoc.getSourceUrl();
0937 fileName = null;
0938 if(fileURL != null){
0939 fileName = fileURL.getFile();
0940 fileName = Files.getLastPathComponent(fileName);
0941 } // if
0942 if(fileName == null || fileName.length() == 0){
0943 fileName = currentDoc.getName();
0944 } // if
0945 if(fileName.length() == 0) {
0946 fileName = "gate_result"+i;
0947 } // if
0948 // create full file name
0949 fileName = fileName+".gate";
0950
0951 // run export
0952 run = new ExportInline(currentDoc, new File(directory, fileName));
0953 thread = new Thread(run, "");
0954 thread.setPriority(Thread.MIN_PRIORITY);
0955 thread.start();
0956 } // for
0957 } // if
0958 } // if
0959 } // actionPerformed(ActionEvent e)
0960 } // class ExportAllDocumentInlineAction extends AbstractAction
0961
0962 /** Object to run ExportAll in a new Thread */
0963 private class ExportAllRunnable implements Runnable {
0964 File directory;
0965 ExportAllRunnable(File targetDirectory) {
0966 directory = targetDirectory;
0967 } // ExportAllRunnable(File targetDirectory)
0968
0969 public void run() {
0970 saveDocuments(directory);
0971 } // run()
0972 } // ExportAllRunnable
0973
0974 /** Load application from file */
0975 private class ApplicationLoadRun implements Runnable {
0976 private String appURL;
0977 private MainFrame appFrame;
0978 public ApplicationLoadRun(String url, MainFrame frame) {
0979 appURL = url;
0980 appFrame = frame;
0981 }
0982
0983 public void run(){
0984 File file = new File(appURL);
0985 boolean appLoaded = false;
0986
0987 MainFrame.lockGUI("Application from '"+appURL+"' is being loaded...");
0988 if( file.exists() ) {
0989 try {
0990 gate.util.persistence.PersistenceManager.loadObjectFromFile(file);
0991 appLoaded = true;
0992 } catch (PersistenceException pex) {
0993 pex.printStackTrace();
0994 } catch (ResourceInstantiationException riex) {
0995 riex.printStackTrace();
0996 } catch (IOException ioex) {
0997 ioex.printStackTrace();
0998 } // catch
0999 } // if
1000 MainFrame.unlockGUI();
1001
1002 if(!appLoaded) {
1003 // file do not exist. Show a message
1004 JOptionPane.showMessageDialog(ShellSlacFrame.this,
1005 "The application file '"+appURL+"'\n"
1006 +"from parameter -Dgate.slug.app\n"
1007 +"is missing or corrupted."
1008 +"Create default application.",
1009 "Load application error",
1010 JOptionPane.WARNING_MESSAGE);
1011
1012 createDefaultApplication();
1013 } // if
1014 } // run
1015 } // class ApplicationLoadRun implements Runnable
1016
1017 /** Create default ANNIE */
1018 public class ANNIERunnable implements Runnable {
1019 MainFrame parentFrame;
1020 ANNIERunnable(MainFrame parent) {
1021 parentFrame = parent;
1022 }
1023
1024 public void run(){
1025 AbstractAction action = new LoadANNIEWithDefaultsAction();
1026 action.actionPerformed(new ActionEvent(parentFrame, 1, "Load ANNIE"));
1027 }
1028 } // ANNIERunnable
1029
1030 class AboutPaneDialog extends JDialog {
1031 public AboutPaneDialog(Frame frame, String title, boolean modal) {
1032 super(frame, title, modal);
1033 } // AboutPaneDialog
1034
1035 public boolean setURL(URL url) {
1036 boolean success = false;
1037 // try to show in JEditorPane
1038 try {
1039 Container pane = getContentPane();
1040
1041 JScrollPane scroll = new JScrollPane();
1042 JEditorPane editor = new JEditorPane(url);
1043 editor.setEditable(false);
1044 scroll.getViewport().add(editor);
1045 pane.add(scroll, BorderLayout.CENTER);
1046
1047 JButton ok = new JButton("Close");
1048 ok.addActionListener( new ActionListener() {
1049 public void actionPerformed(ActionEvent e) {
1050 AboutPaneDialog.this.setVisible(false);
1051 }
1052 });
1053 pane.add(ok, BorderLayout.SOUTH);
1054 success = true;
1055 } catch (Exception ex) {
1056 if(DEBUG) {
1057 ex.printStackTrace();
1058 }
1059 } // catch
1060 return success;
1061 } // setURL
1062 } // class AboutPaneDialog
1063
1064 /** Dummy Help About dialog */
1065 class HelpAboutSlugAction extends AbstractAction {
1066 public HelpAboutSlugAction() {
1067 super("About");
1068 } // HelpAboutSlugAction()
1069
1070 public void actionPerformed(ActionEvent e) {
1071
1072 // Set about box content from Java properties
1073 String aboutText = "Slug application.";
1074 String aboutURL =
1075 System.getProperty(GateConstants.ABOUT_URL_JAVA_PROPERTY_NAME);
1076
1077 boolean canShowInPane = false;
1078
1079 if(aboutURL != null) {
1080 try {
1081 URL url = new URL(aboutURL);
1082
1083 AboutPaneDialog dlg =
1084 new AboutPaneDialog(ShellSlacFrame.this,
1085 "Slug application about", true);
1086 canShowInPane = dlg.setURL(url);
1087 if(canShowInPane) {
1088 dlg.setSize(300, 200);
1089 dlg.setLocationRelativeTo(ShellSlacFrame.this);
1090 dlg.setVisible(true);
1091 } // if
1092 else {
1093 BufferedReader reader = new BomStrippingInputStreamReader(url.openStream());
1094 String line = "";
1095 StringBuffer content = new StringBuffer();
1096 do {
1097 content.append(line);
1098 line = reader.readLine();
1099 } while (line != null);
1100
1101 if(content.length() != 0) {
1102 aboutText = content.toString();
1103 } // if
1104 } // if
1105
1106 } catch (Exception ex) {
1107 // do nothing on exception
1108 // application just stay with a dummy text in about box
1109 if(DEBUG) {
1110 ex.printStackTrace();
1111 }
1112 } // catch
1113 } // if
1114
1115
1116 if(!canShowInPane) JOptionPane.showMessageDialog(ShellSlacFrame.this,
1117 aboutText,
1118 "Slug application about",
1119 JOptionPane.INFORMATION_MESSAGE);
1120 } // actionPerformed(ActionEvent e)
1121 } // class HelpAboutSlugAction extends AbstractAction
1122
1123
1124 /**
1125 * Component used to select the options for corpus populating
1126 */
1127 CorpusFillerComponent corpusFiller;
1128
1129 class PopulateCorpusAction extends AbstractAction {
1130 PopulateCorpusAction() {
1131 super("New Documents...");
1132 } // PopulateCorpusAction()
1133
1134 public void actionPerformed(ActionEvent e) {
1135 Runnable runnable = new Runnable(){
1136 public void run(){
1137 if(corpus == null || corpusFiller == null) return;
1138 corpusFiller.setExtensions(new ArrayList());
1139 corpusFiller.setEncoding("");
1140 boolean answer = OkCancelDialog.showDialog(
1141 ShellSlacFrame.this,
1142 corpusFiller,
1143 "Select a directory and allowed extensions");
1144 if(answer){
1145 URL url = null;
1146 try{
1147 url = new URL(corpusFiller.getUrlString());
1148 java.util.List extensions = corpusFiller.getExtensions();
1149 ExtensionFileFilter filter = null;
1150 if(extensions == null || extensions.isEmpty()) filter = null;
1151 else{
1152 filter = new ExtensionFileFilter();
1153 Iterator extIter = corpusFiller.getExtensions().iterator();
1154 while(extIter.hasNext()){
1155 filter.addExtension((String)extIter.next());
1156 }
1157 }
1158 corpus.populate(url, filter,
1159 corpusFiller.getEncoding(),
1160 corpusFiller.isRecurseDirectories());
1161 }catch(MalformedURLException mue){
1162 JOptionPane.showMessageDialog(ShellSlacFrame.this,
1163 "Invalid URL!\n " +
1164 "See \"Messages\" tab for details!",
1165 "GATE", JOptionPane.ERROR_MESSAGE);
1166 mue.printStackTrace(Err.getPrintWriter());
1167 }catch(IOException ioe){
1168 JOptionPane.showMessageDialog(ShellSlacFrame.this,
1169 "I/O error!\n " +
1170 "See \"Messages\" tab for details!",
1171 "GATE", JOptionPane.ERROR_MESSAGE);
1172 ioe.printStackTrace(Err.getPrintWriter());
1173 }catch(ResourceInstantiationException rie){
1174 JOptionPane.showMessageDialog(ShellSlacFrame.this,
1175 "Could not create document!\n " +
1176 "See \"Messages\" tab for details!",
1177 "GATE", JOptionPane.ERROR_MESSAGE);
1178 rie.printStackTrace(Err.getPrintWriter());
1179 }
1180 }
1181 }
1182 };
1183 Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
1184 runnable);
1185 thread.setPriority(Thread.MIN_PRIORITY);
1186 thread.start();
1187 } // actionPerformed(ActionEvent e)
1188 } // class PopulateCorpusAction extends AbstractAction
1189
1190 } // class ShellSlacFrame
|