update dev300-m58
[ooovba.git] / xmlsecurity / tools / uno / TestTool.java
blob8bc1bbe5ea809a9251ae38339f550c94a6167b88
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: TestTool.java,v $
10 * $Revision: 1.4 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 package com.sun.star.xml.security.uno;
33 import javax.xml.parsers.DocumentBuilder;
34 import javax.xml.parsers.DocumentBuilderFactory;
35 import javax.xml.parsers.ParserConfigurationException;
37 import java.io.File;
38 import java.io.IOException;
39 import java.io.FileOutputStream;
40 import java.io.FileInputStream;
41 import java.io.InputStream;
42 import java.io.ByteArrayInputStream;
43 import java.io.UnsupportedEncodingException;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Node;
47 import org.w3c.dom.NodeList;
49 /* Basic GUI components */
50 import javax.swing.JFrame;
51 import javax.swing.JPanel;
52 import javax.swing.JScrollPane;
53 import javax.swing.JTree;
54 import javax.swing.JButton;
55 import javax.swing.JCheckBox;
56 import javax.swing.JTextArea;
57 import javax.swing.JTextField;
58 import javax.swing.JFileChooser;
59 import javax.swing.ToolTipManager;
60 import javax.swing.JTable;
61 import javax.swing.JLabel;
62 import javax.swing.BorderFactory;
64 /* GUI components for right-hand side */
65 import javax.swing.JSplitPane;
66 import javax.swing.JOptionPane;
67 import javax.swing.JTabbedPane;
70 /* GUI support classes */
71 import java.awt.BorderLayout;
72 import java.awt.Dimension;
73 import java.awt.Container;
74 import java.awt.Toolkit;
75 import java.awt.event.WindowEvent;
76 import java.awt.event.WindowAdapter;
77 import java.awt.event.ActionEvent;
78 import java.awt.event.ActionListener;
80 /* For creating borders */
81 import javax.swing.border.EmptyBorder;
82 import javax.swing.border.BevelBorder;
83 import javax.swing.border.CompoundBorder;
85 /* For creating a TreeModel */
86 import javax.swing.tree.TreePath;
87 import java.util.Vector;
89 /* UNO classes */
90 import com.sun.star.uno.UnoRuntime;
91 import com.sun.star.bridge.XUnoUrlResolver;
92 import com.sun.star.lang.XMultiComponentFactory;
93 import com.sun.star.beans.XPropertySet;
94 import com.sun.star.uno.XComponentContext;
95 import com.sun.star.xml.sax.XDocumentHandler;
97 import com.sun.star.xml.crypto.*;
98 import com.sun.star.xml.crypto.sax.*;
100 public class TestTool extends JFrame implements ActionListener
103 * xml security framewrok component names
105 public static String SIGNATURECREATOR_COMPONENT = "com.sun.star.xml.crypto.sax.SignatureCreator";
106 public static String SIGNATUREVERIFIER_COMPONENT = "com.sun.star.xml.crypto.sax.SignatureVerifier";
107 public static String ENCRYPTOR_COMPONENT = "com.sun.star.xml.crypto.sax.Encryptor";
108 public static String DECRYPTOR_COMPONENT = "com.sun.star.xml.crypto.sax.Decryptor";
109 public static String SAXEVENTKEEPER_COMPONENT = "com.sun.star.xml.crypto.sax.SAXEventKeeper";
112 * Java-based component names
114 public static String SEINITIALIZER_COMPONENT_JAVA = "com.sun.star.xml.security.bridge.jxsec.SEInitializer_JxsecImpl";
115 public static String XMLSIGNATURE_COMPONENT_JAVA = "com.sun.star.xml.security.bridge.jxsec.XMLSignature_JxsecImpl";
116 public static String XMLENCRYPTION_COMPONENT_JAVA = "com.sun.star.xml.security.bridge.jxsec.XMLEncryption_JxsecImpl";
117 public static String XMLDOCUMENTWRAPPER_COMPONENT_JAVA = "com.sun.star.xml.security.bridge.jxsec.XMLDocumentWrapper_JxsecImpl";
120 * C-based component names
122 public static String SEINITIALIZER_COMPONENT_C = "com.sun.star.xml.crypto.SEInitializer";
123 public static String XMLSIGNATURE_COMPONENT_C = "com.sun.star.xml.crypto.XMLSignature";
124 public static String XMLENCRYPTION_COMPONENT_C = "com.sun.star.xml.crypto.XMLEncryption";
125 public static String XMLDOCUMENTWRAPPER_COMPONENT_C = "com.sun.star.xml.wrapper.XMLDocumentWrapper";
127 /* url resolver name */
128 public static String UNOURLRESOLVER = "com.sun.star.bridge.UnoUrlResolver";
131 * connection URL
133 private String m_unoURL = "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager";
135 /* key file */
136 private String m_javaTokenFile = null;
137 private String m_nssTokenPath = null;
139 /* User Interfaces */
140 private JButton m_goButton;
141 private JButton m_stepButton;
142 private JButton m_startButton;
143 private JButton m_openButton;
144 private JCheckBox m_isExportingButton;
145 private JCheckBox m_isJavaComponentButton;
146 private JButton m_saveButton;
147 private JButton m_batchButton;
148 private JTree m_leftTree;
149 private JTextArea m_leftTextArea;
150 private JTree m_middleTree;
151 private JTree m_rightTree;
152 private JTabbedPane m_leftTabPane;
153 private JTextArea m_bufferNodeTextArea;
154 private JLabel m_saxChainLabel;
155 private JTextField m_saxEventText;
156 private JTable m_unsolvedReferenceTable;
159 * whether a batch file is running,
160 * if so, no message box is popped up
162 private boolean m_bIsBatchRunning = false;
165 * whether the UI needs to be updated.
166 * when user click the "go" button, the UI needs
167 * not to be updated step by step for performance
168 * reason
170 private boolean m_bIsUIUpdateSuppressed = false;
173 * three DOM tree adapter
175 private DomToTreeModelAdapter m_leftTreeModelAdapter;
176 private DomToTreeModelAdapter m_middleTreeModelAdapter;
177 private DomToTreeModelAdapter m_rightTreeModelAdapter;
180 * the current directory, which reserves the default
181 * location when user open/save a file.
183 private File m_currentDirectory = null;
186 * the log file
188 private FileOutputStream m_logFileOutputStream = null;
191 * the thread which is parsing the current XML
192 * file
194 private ParsingThread m_parsingThread;
197 * whether is exporting or importing
199 private boolean m_bIsExporting;
202 * whether java based component or c based component
203 * is used now
205 private boolean m_bIsJavaBased;
208 * XML security component interface
210 private XComponentContext m_xRemoteContext = null;
211 private XMultiComponentFactory m_xRemoteServiceManager = null;
212 private XXMLSecurityContext m_xXMLSecurityContext = null;
213 private XXMLSignature m_xXMLSignature = null;
214 private XXMLEncryption m_xXMLEncryption = null;
215 private XSEInitializer m_xSEInitializer = null;
218 * SAX event collector for the middle tree and the right tree
220 private SAXEventCollector m_rightTreeEventCollector = null;
221 private SAXEventCollector m_middleTreeEventCollector = null;
224 * security framework controller
226 private XMLSecurityFrameworkController m_xmlSecurityFrameworkController = null;
228 /* org.w3c.dom.Document */
229 private Document m_document;
231 /* represents whether "Go" or "Step" */
232 private boolean stepMode = true;
234 /**************************************************************************************
235 * private methods
236 **************************************************************************************/
239 /******************************************************************************
240 * UI related methods
241 ******************************************************************************/
244 * initalizes the UI.
246 private void initUI()
248 m_leftTreeModelAdapter = new DomToTreeModelAdapter(m_document);
249 m_middleTreeModelAdapter = new DomToTreeModelAdapter(m_document);
250 m_rightTreeModelAdapter = new DomToTreeModelAdapter(m_document);
252 m_parsingThread = null;
254 m_leftTree.setModel(m_leftTreeModelAdapter);
255 m_middleTree.setModel(m_middleTreeModelAdapter);
256 m_rightTree.setModel(m_rightTreeModelAdapter);
260 * constructs the user interface.
262 private Container buildUI(int width, int height)
264 JPanel mainPanel = new JPanel();
266 int frameHeight = height-40;
267 int leftWindowWidth = (width-40)/3;
268 int middleWindowWidth = leftWindowWidth;
269 int rightWindowWidth = leftWindowWidth;
270 int leftPaneWidth = leftWindowWidth+middleWindowWidth;
271 int frameWidth = leftPaneWidth + rightWindowWidth;
273 /* Make a nice border */
274 EmptyBorder emptyBorder = new EmptyBorder(5,5,5,5);
275 BevelBorder bevelBorder = new BevelBorder(BevelBorder.LOWERED);
276 CompoundBorder compoundBorder = new CompoundBorder(emptyBorder,bevelBorder);
277 mainPanel.setBorder(new CompoundBorder(compoundBorder,emptyBorder));
279 /* Set up the tree */
280 m_leftTreeModelAdapter = new DomToTreeModelAdapter(m_document);
281 m_middleTreeModelAdapter = new DomToTreeModelAdapter(m_document);
282 m_rightTreeModelAdapter = new DomToTreeModelAdapter(m_document);
284 m_leftTree = new JTree(m_leftTreeModelAdapter);
285 m_leftTextArea = new JTextArea();
286 m_middleTree = new JTree(m_middleTreeModelAdapter);
287 m_rightTree = new JTree(m_rightTreeModelAdapter);
289 ToolTipManager.sharedInstance().registerComponent(m_leftTree);
290 ToolTipManager.sharedInstance().registerComponent(m_middleTree);
291 ToolTipManager.sharedInstance().registerComponent(m_rightTree);
293 /* Builds left tab pane */
294 JScrollPane leftTreePane = new JScrollPane(m_leftTree);
295 JScrollPane leftTextPane = new JScrollPane(m_leftTextArea);
296 m_leftTabPane= new JTabbedPane();
297 m_leftTabPane.add("Tree View",leftTreePane);
298 m_leftTabPane.add("Text View",leftTextPane);
300 /* Builds middle tree pane */
301 JScrollPane middleTreePane = new JScrollPane(m_middleTree);
303 /* Builds right tree pane */
304 JScrollPane rightTreePane = new JScrollPane(m_rightTree);
305 rightTreePane.setBorder(BorderFactory.createCompoundBorder(
306 BorderFactory.createTitledBorder("Result"),
307 BorderFactory.createEmptyBorder(8,8,8,8)));
309 m_leftTabPane.setPreferredSize(
310 new Dimension( leftWindowWidth, frameHeight ));
311 middleTreePane.setPreferredSize(
312 new Dimension( middleWindowWidth, frameHeight ));
313 rightTreePane.setPreferredSize(
314 new Dimension( rightWindowWidth, frameHeight ));
316 /* Builds the SAX event text box */
317 m_saxEventText = new JTextField();
319 /* Builds the unsolved reference table */
320 m_unsolvedReferenceTable = new JTable(
321 new UnsolvedReferenceTableModel(this));
323 /* Builds the BufferNode information text area */
324 m_bufferNodeTextArea = new JTextArea();
326 /* Builds the SAX chain information label */
327 m_saxChainLabel = new JLabel();
329 /* Builds the left pane */
330 JPanel tabPaneWithSaxEventPane = new JPanel();
331 tabPaneWithSaxEventPane.setLayout(new BorderLayout());
332 tabPaneWithSaxEventPane.add("Center",m_leftTabPane);
333 tabPaneWithSaxEventPane.add("South",new JScrollPane(m_saxEventText));
335 JSplitPane leftPane =
336 new JSplitPane( JSplitPane.VERTICAL_SPLIT,
337 tabPaneWithSaxEventPane,
338 new JScrollPane(m_unsolvedReferenceTable));
339 leftPane.setBorder(BorderFactory.createCompoundBorder(
340 BorderFactory.createTitledBorder("Original"),
341 BorderFactory.createEmptyBorder(8,8,8,8)));
343 leftPane.setContinuousLayout( true );
344 leftPane.setDividerLocation( frameHeight*2/3 );
345 leftPane.setPreferredSize(
346 new Dimension( leftWindowWidth, frameHeight ));
348 /* Builds the middle pane */
349 JPanel bufferNodeWithSaxChainPane = new JPanel();
350 bufferNodeWithSaxChainPane.setLayout(new BorderLayout());
351 bufferNodeWithSaxChainPane.add("Center",m_bufferNodeTextArea);
352 bufferNodeWithSaxChainPane.add("South",new JScrollPane(m_saxChainLabel));
354 JSplitPane middlePane =
355 new JSplitPane( JSplitPane.VERTICAL_SPLIT,
356 middleTreePane,
357 new JScrollPane(bufferNodeWithSaxChainPane));
359 middlePane.setBorder(BorderFactory.createCompoundBorder(
360 BorderFactory.createTitledBorder("Insight SAXEventKeeper"),
361 BorderFactory.createEmptyBorder(8,8,8,8)));
363 middlePane.setContinuousLayout( true );
364 middlePane.setDividerLocation( frameHeight/2+5 );
365 middlePane.setPreferredSize(
366 new Dimension( middleWindowWidth, frameHeight ));
368 /* Builds the whole frame pane */
369 JSplitPane leftWithMiddlePane =
370 new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
371 leftPane,
372 middlePane );
373 leftWithMiddlePane.setContinuousLayout( true );
374 leftWithMiddlePane.setDividerLocation( leftWindowWidth );
375 leftWithMiddlePane.setPreferredSize(
376 new Dimension( leftPaneWidth + 10, frameHeight+10 ));
378 JSplitPane framePane =
379 new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
380 leftWithMiddlePane,
381 rightTreePane );
384 framePane.setContinuousLayout( true );
385 framePane.setDividerLocation(leftPaneWidth+10 );
386 framePane.setPreferredSize(
387 new Dimension( frameWidth + 20, frameHeight+10 ));
389 /* Adds all GUI components to the main panel */
390 mainPanel.setLayout(new BorderLayout());
391 mainPanel.add("Center", framePane );
393 m_openButton = new JButton("Open...");
394 m_openButton.addActionListener(this);
396 m_goButton = new JButton("Go!");
397 m_goButton.addActionListener(this);
399 m_stepButton = new JButton("Step");
400 m_stepButton.addActionListener(this);
402 m_startButton = new JButton("Start");
403 m_startButton.addActionListener(this);
404 m_startButton.setEnabled(false);
406 m_isExportingButton = new JCheckBox("export, not import", true);
407 m_isJavaComponentButton = new JCheckBox("use java component", false);
409 m_saveButton = new JButton("Save...");
410 m_saveButton.addActionListener(this);
412 m_batchButton = new JButton("Batch...");
413 m_batchButton.addActionListener(this);
415 JPanel buttonPanel = new JPanel();
416 buttonPanel.add(m_batchButton);
417 buttonPanel.add(m_openButton);
418 buttonPanel.add(m_startButton);
419 buttonPanel.add(m_goButton);
420 buttonPanel.add(m_stepButton);
421 buttonPanel.add(m_isExportingButton);
422 buttonPanel.add(m_isJavaComponentButton);
423 buttonPanel.add(m_saveButton);
425 mainPanel.add("South", buttonPanel);
427 enableGoButton(false);
429 return mainPanel;
433 * enables/disables the Go(and Step) button.
435 private void enableGoButton(boolean enabled)
437 m_goButton.setEnabled(enabled);
438 m_stepButton.setEnabled(enabled);
442 * updates the unsolved reference information.
444 private void updatesUnsolvedReferencesInformation()
446 m_unsolvedReferenceTable.setModel(new UnsolvedReferenceTableModel(this));
450 * adjusts the view of the tree in order to make the
451 * particular Node into the focus tree leaf.
453 private void updatesTree(Node node, JTree tree)
455 int i=0;
456 int currentLine = 0;
458 while (i<tree.getRowCount())
460 TreePath treePath = tree.getPathForRow(i);
461 tree.expandPath(treePath);
463 AdapterNode adapterNode = (AdapterNode)treePath.getLastPathComponent();
465 if (node == adapterNode.getNode())
467 tree.addSelectionPath(treePath);
468 currentLine = i;
471 ++i;
474 tree.setCellRenderer(new XMLTreeCellRanderer(node));
475 tree.scrollRowToVisible(currentLine);
478 /******************************************************************************
479 * action listener related methods.
480 ******************************************************************************/
483 * reads in a document, either the document is a file or
484 * is a text paragraph.
486 private void openDocument()
488 if (m_leftTabPane.getSelectedIndex() == 0)
490 File f = openFile();
491 if (f != null)
493 parseFile(f);
496 else
498 String text = m_leftTextArea.getText();
502 parseStream(new ByteArrayInputStream(text.getBytes("UTF-8")));
504 catch(UnsupportedEncodingException e)
506 e.printStackTrace();
509 m_leftTabPane.setSelectedIndex(0);
514 * save the result tree to a file.
516 private void saveResult()
518 saveFile();
522 * selects a batch file to excute.
524 private void openBatch()
526 File f = openFile();
527 if (f != null)
529 runBatch(f);
534 * makes the current operation to an end.
536 private void endMission()
538 enableGoButton(false);
539 m_parsingThread = null;
541 if (m_xmlSecurityFrameworkController != null)
543 m_xmlSecurityFrameworkController.endMission();
546 updatesUIs();
548 m_xmlSecurityFrameworkController = null;
549 freeComponents();
551 System.gc();
555 /******************************************************************************
556 * UNO component related methods
557 ******************************************************************************/
560 * connects the SO server.
562 private void connectSO(String unoUrlString)
564 if (unoUrlString != null)
566 m_unoURL = new String(unoUrlString);
571 m_xRemoteServiceManager = getRemoteServiceManager(m_unoURL);
573 catch(Exception e)
575 e.printStackTrace();
580 * creates UNO components.
582 private boolean createComponents()
586 String SEInitializer_comp;
587 String XMLSignature_comp;
588 String XMLEncryption_comp;
589 String tokenPath;
591 if (m_bIsJavaBased)
593 SEInitializer_comp = SEINITIALIZER_COMPONENT_JAVA;
594 XMLSignature_comp = XMLSIGNATURE_COMPONENT_JAVA;
595 XMLEncryption_comp = XMLENCRYPTION_COMPONENT_JAVA;
596 tokenPath = m_javaTokenFile;
598 else
600 SEInitializer_comp = SEINITIALIZER_COMPONENT_C;
601 XMLSignature_comp = XMLSIGNATURE_COMPONENT_C;
602 XMLEncryption_comp = XMLENCRYPTION_COMPONENT_C;
603 tokenPath = m_nssTokenPath;
606 Object seInitializerObj = m_xRemoteServiceManager.createInstanceWithContext(
607 SEInitializer_comp, m_xRemoteContext);
609 if (seInitializerObj == null)
611 freeComponents();
612 return false;
615 m_xSEInitializer = (XSEInitializer)UnoRuntime.queryInterface(
616 XSEInitializer.class, seInitializerObj);
618 m_xXMLSecurityContext = m_xSEInitializer.createSecurityContext(tokenPath);
620 Object xmlSignatureObj = m_xRemoteServiceManager.createInstanceWithContext(
621 XMLSignature_comp, m_xRemoteContext);
623 if (xmlSignatureObj == null)
625 freeComponents();
626 return false;
629 m_xXMLSignature = (XXMLSignature)UnoRuntime.queryInterface(
630 XXMLSignature.class, xmlSignatureObj);
632 Object xmlEncryptionObj = m_xRemoteServiceManager.createInstanceWithContext(
633 XMLEncryption_comp, m_xRemoteContext);
635 if (xmlEncryptionObj == null)
637 freeComponents();
638 return false;
641 m_xXMLEncryption = (XXMLEncryption)UnoRuntime.queryInterface(
642 XXMLEncryption.class, xmlEncryptionObj);
644 return true;
646 catch(Exception e)
648 freeComponents();
649 e.printStackTrace();
650 return false;
655 * frees UNO components.
657 private void freeComponents()
661 if (m_xXMLSecurityContext != null)
663 m_xSEInitializer.freeSecurityContext(m_xXMLSecurityContext);
664 m_xXMLSecurityContext = null;
667 m_xXMLSignature = null;
668 m_xXMLEncryption = null;
669 m_xSEInitializer = null;
671 catch(Exception e)
673 e.printStackTrace();
678 * getRemoteServiceManager
680 private XMultiComponentFactory getRemoteServiceManager(String unoUrl) throws java.lang.Exception
682 if (m_xRemoteContext == null)
685 * First step: create local component context, get local servicemanager and
686 * ask it to create a UnoUrlResolver object with an XUnoUrlResolver interface
688 XComponentContext xLocalContext =
689 com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
690 XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();
691 Object urlResolver = xLocalServiceManager.createInstanceWithContext(
692 UNOURLRESOLVER, xLocalContext );
694 * query XUnoUrlResolver interface from urlResolver object
696 XUnoUrlResolver xUnoUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(
697 XUnoUrlResolver.class, urlResolver );
700 * Second step: use xUrlResolver interface to import the remote StarOffice.ServiceManager,
701 * retrieve its property DefaultContext and get the remote servicemanager
703 Object initialObject = xUnoUrlResolver.resolve( unoUrl );
704 XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(
705 XPropertySet.class, initialObject);
706 Object context = xPropertySet.getPropertyValue("DefaultContext");
707 m_xRemoteContext = (XComponentContext)UnoRuntime.queryInterface(
708 XComponentContext.class, context);
710 return m_xRemoteContext.getServiceManager();
714 /******************************************************************************
715 * XML related methods
716 ******************************************************************************/
719 * removes all empty text node inside the particular element
721 private void removeEmptyText(Node node)
723 int type = node.getNodeType();
724 NodeList children;
725 int i;
727 switch (type)
729 case Node.DOCUMENT_NODE:
730 case Node.ELEMENT_NODE:
731 Node child = node.getFirstChild();
732 while (child!= null)
734 Node nextSibling = child.getNextSibling();
735 int childType = child.getNodeType();
737 if (childType==Node.TEXT_NODE)
739 String message = child.getNodeValue().trim();
740 if (message == null || message.length()<=0)
742 node.removeChild(child);
745 else if (childType == Node.ELEMENT_NODE)
747 removeEmptyText(child);
750 child = nextSibling;
752 break;
757 * reads a stream, and parses it into the original tree.
759 private void parseStream(InputStream is)
763 DocumentBuilderFactory factory =
764 DocumentBuilderFactory.newInstance();
765 m_document = null;
766 m_startButton.setEnabled(false);
767 initUI();
769 /* factory.setValidating(true); */
770 /* factory.setNamespaceAware(true); */
772 try
774 DocumentBuilder builder = factory.newDocumentBuilder();
775 m_document = builder.parse(is);
776 m_startButton.setEnabled(true);
777 initUI();
779 catch (ParserConfigurationException pce)
781 pce.printStackTrace();
783 catch (IOException ioe)
785 ioe.printStackTrace();
788 catch(Exception exce)
790 System.out.println("input stream Exception");
795 /******************************************************************************
796 * file operation related methods
797 ******************************************************************************/
800 * opens a file, and parses it into the original tree.
802 private void parseFile(File name)
806 FileInputStream fis = new FileInputStream(name);
807 parseStream(fis);
808 fis.close();
810 catch(Exception exce)
812 System.out.println("open file Exception");
818 * selects a file to open
820 private File openFile()
822 File rc = null;
824 JFileChooser fileChooser= new JFileChooser();
826 fileChooser.setDialogTitle("Select File To Open");
827 fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
829 fileChooser.setApproveButtonText("Ok");
831 if (m_currentDirectory == null)
833 fileChooser.rescanCurrentDirectory();
835 else
837 fileChooser.setCurrentDirectory(m_currentDirectory);
840 fileChooser.setFileFilter(new XMLFileFilter());
842 int result = fileChooser.showDialog(this,null);
843 if (result==fileChooser.APPROVE_OPTION)
845 m_currentDirectory = fileChooser.getCurrentDirectory();
846 rc = fileChooser.getSelectedFile();
849 return rc;
852 private void saveFile()
854 JFileChooser fileChooser= new JFileChooser();
856 fileChooser.setDialogTitle("Select File To Save");
857 fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
859 fileChooser.setApproveButtonText("Ok");
861 if (m_currentDirectory == null)
863 fileChooser.rescanCurrentDirectory();
865 else
867 fileChooser.setCurrentDirectory(m_currentDirectory);
870 fileChooser.setFileFilter(new XMLFileFilter());
872 int result = fileChooser.showDialog(this,null);
873 if (result==fileChooser.APPROVE_OPTION)
877 m_currentDirectory = fileChooser.getCurrentDirectory();
878 saveFile(fileChooser.getSelectedFile());
880 catch(Exception exce)
882 System.out.println("save file Exception");
883 exce.printStackTrace();
889 * excutes a batch file.
891 private void runBatch(File f)
893 FileInputStream fis = null;
897 fis = new FileInputStream(f);
898 StringBuffer commandBuffer = new StringBuffer();
900 m_logFileOutputStream = new FileOutputStream("TestTool-log.txt");
901 m_bIsBatchRunning = true;
902 int ch = 0;
904 while (ch != -1)
906 ch = fis.read();
908 if (ch != 0x0a && ch != -1)
910 if (ch != 0x0d)
912 commandBuffer.append((char)ch);
915 else
917 String command = new String(commandBuffer);
918 if (command.startsWith("Open "))
920 m_logFileOutputStream.write(("start \""+command+"\" ...\n").getBytes());
921 String fileName = command.substring(5);
922 parseFile(new File(fileName));
923 m_logFileOutputStream.write("command end \n\n".getBytes());
925 else if (command.startsWith("Use Java Component"))
927 m_logFileOutputStream.write(("start \""+command+"\" ...\n").getBytes());
928 m_isJavaComponentButton.setSelected(true);
929 m_logFileOutputStream.write("command end \n\n".getBytes());
931 else if (command.startsWith("Use C++ Component"))
933 m_logFileOutputStream.write(("start \""+command+"\" ...\n").getBytes());
934 m_isJavaComponentButton.setSelected(false);
935 m_logFileOutputStream.write("command end \n\n".getBytes());
937 else if (command.startsWith("Go "))
939 m_logFileOutputStream.write(("start \""+command+"\" ...\n").getBytes());
940 String opera = command.substring(3);
941 if (opera.equals("Sign") || opera.equals("Encrypt"))
943 m_isExportingButton.setSelected(true);
945 else
947 m_isExportingButton.setSelected(false);
950 startsUp();
951 if (m_parsingThread != null)
953 m_bIsUIUpdateSuppressed = true;
954 try{
955 while (m_parsingThread.nextStep());
956 endMission();
958 catch(Exception e)
960 System.out.println("exception happen during batch:"+e);
961 e.printStackTrace();
964 m_bIsUIUpdateSuppressed = false;
965 updatesUIs();
967 m_logFileOutputStream.write("command end \n\n".getBytes());
969 else if (command.startsWith("Save "))
971 m_logFileOutputStream.write(("start \""+command+"\" ...\n").getBytes());
972 String fileName = command.substring(5);
973 saveFile(new File(fileName));
974 m_logFileOutputStream.write("command end \n\n".getBytes());
977 commandBuffer = new StringBuffer();
981 m_bIsBatchRunning = false;
982 m_logFileOutputStream.close();
983 m_logFileOutputStream = null;
985 fis.close();
986 fis = null;
988 catch(java.io.IOException e)
990 e.printStackTrace();
995 * save the current result tree to a particular file.
997 private void saveFile(File f)
999 try{
1000 FileOutputStream fos = new FileOutputStream(f);
1001 SAXEventPrinter.display((Document)m_rightTreeEventCollector.getDocument(),
1002 0,fos,false);
1003 fos.close();
1004 }catch(Exception e)
1006 e.printStackTrace();
1010 /******************************************************************************
1011 * others
1012 ******************************************************************************/
1015 * starts up the operation.
1017 private void startsUp()
1019 if (m_parsingThread != null)
1021 m_parsingThread = null;
1024 m_bIsExporting = m_isExportingButton.isSelected();
1025 m_bIsJavaBased = m_isJavaComponentButton.isSelected();
1027 if (createComponents())
1029 m_rightTreeEventCollector = new SAXEventCollector(this);
1031 m_parsingThread = new ParsingThread(
1032 m_document,
1033 null,
1034 this);
1036 m_xmlSecurityFrameworkController =
1037 new XMLSecurityFrameworkController(
1038 this,
1039 m_bIsExporting,
1040 m_bIsJavaBased,
1041 m_rightTreeEventCollector,
1042 m_parsingThread,
1043 m_xXMLSecurityContext,
1044 m_xXMLSignature,
1045 m_xXMLEncryption,
1046 m_xRemoteServiceManager,
1047 m_xRemoteContext);
1049 enableGoButton(true);
1051 else
1053 showMessage("Error in creating XML Security Components!");
1057 /**************************************************************************************
1058 * protected methods
1059 **************************************************************************************/
1061 /******************************************************************************
1062 * UI related methods
1063 ******************************************************************************/
1066 * updates the sax chain information.
1068 protected void updatesSAXChainInformation(String chainStr)
1070 m_saxChainLabel.setText(chainStr);
1074 * update the current SAX event information.
1076 protected void updatesCurrentSAXEventInformation(String event)
1078 m_saxEventText.setText(event);
1082 * updates all information in the UI.
1084 protected void updatesUIs()
1086 if (!m_bIsUIUpdateSuppressed)
1088 m_leftTree.clearSelection();
1089 updatesTree(null, m_leftTree);
1091 if (m_xmlSecurityFrameworkController != null)
1093 String bufferNodeTreeText = m_xmlSecurityFrameworkController.getBufferNodeTreeInformation();
1094 if (bufferNodeTreeText == null)
1096 m_middleTree.setVisible(false);
1097 m_bufferNodeTextArea.setText("No XML Security Related");
1099 else
1101 m_middleTreeEventCollector = new SAXEventCollector(null);
1102 m_xmlSecurityFrameworkController.getDocument(m_middleTreeEventCollector);
1104 m_middleTreeModelAdapter = new DomToTreeModelAdapter(m_middleTreeEventCollector.getDocument());
1105 m_middleTree.setModel(m_middleTreeModelAdapter);
1106 updatesTree(null, m_middleTree);
1107 m_middleTree.setVisible(true);
1108 m_bufferNodeTextArea.setText(bufferNodeTreeText);
1111 else
1113 m_middleTree.setVisible(false);
1114 m_bufferNodeTextArea.setText("No XMLImporter/XMLExporter");
1117 if (m_rightTreeEventCollector != null)
1119 m_rightTreeModelAdapter = new DomToTreeModelAdapter((Document)m_rightTreeEventCollector.getDocument());
1120 m_rightTree.setModel(m_rightTreeModelAdapter);
1121 updatesTree((Node)m_rightTreeEventCollector.getCurrentElement(), m_rightTree);
1124 updatesUnsolvedReferencesInformation();
1129 * shows a message.
1131 protected void showMessage(String msg)
1133 if (m_bIsBatchRunning)
1137 if (!msg.startsWith("Message from : SAXEventKeeper"))
1139 byte [] b = msg.getBytes();
1140 m_logFileOutputStream.write(" ".getBytes());
1142 for (int i=0; i<b.length; ++i)
1144 m_logFileOutputStream.write(b[i]);
1145 if (b[i] == '\n')
1147 m_logFileOutputStream.write(" ".getBytes());
1150 m_logFileOutputStream.write("\n ==============================\n".getBytes());
1153 catch(IOException e)
1155 e.printStackTrace();
1158 else
1160 if (stepMode)
1162 JOptionPane optionPane = new JOptionPane();
1163 optionPane.showMessageDialog(this, msg, "TestTool Notification", JOptionPane.INFORMATION_MESSAGE);
1165 else
1167 Object[] options = { "OK", "Go back to step mode" };
1168 if (1 == JOptionPane.showOptionDialog(this, msg, "TestTool Notification",
1169 JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
1170 null, options, options[0]))
1172 stepMode = true;
1179 /******************************************************************************
1180 * information retrieving
1181 ******************************************************************************/
1184 * gets all unsolved reference ids.
1185 * a reference id is the value of the id attribute of an
1186 * referenced element.
1188 protected Vector getUnsolvedReferenceIds()
1190 Vector rc;
1192 if (m_xmlSecurityFrameworkController == null)
1194 rc = new Vector();
1196 else
1198 rc = ((XMLSecurityFrameworkController)m_xmlSecurityFrameworkController).
1199 getUnsolvedReferenceIds();
1202 return rc;
1206 * gets all unsolved reference keeper ids.
1207 * a reference keeper id is the id which the SAXEventKeeper uses
1208 * to identify the corresponding BufferNode.
1210 protected Vector getUnsolvedReferenceKeeperIds()
1212 Vector rc;
1214 if (m_xmlSecurityFrameworkController == null)
1216 rc = new Vector();
1218 else
1220 rc = ((XMLSecurityFrameworkController)m_xmlSecurityFrameworkController).
1221 getUnsolvedReferenceKeeperIds();
1224 return rc;
1228 * gets all unsolved references' remaining numbers.
1229 * a remaining number is that how many claims have not been found for
1230 * a unsolved reference.
1232 protected Vector getUnsolvedReferenceRefNum()
1234 Vector rc;
1236 if (m_xmlSecurityFrameworkController == null)
1238 rc = new Vector();
1240 else
1242 rc = ((XMLSecurityFrameworkController)m_xmlSecurityFrameworkController).
1243 getUnsolvedReferenceRefNum();
1246 return rc;
1250 /**************************************************************************************
1251 * public methods
1252 **************************************************************************************/
1254 /******************************************************************************
1255 * action listener related methods.
1256 ******************************************************************************/
1259 * action listening method.
1261 public void actionPerformed(ActionEvent e)
1263 if (e.getSource().equals(m_startButton))
1265 endMission();
1266 startsUp();
1268 if (e.getSource().equals(m_goButton))
1270 if (m_parsingThread != null)
1272 stepMode = false;
1273 boolean notOver;
1274 while ( notOver = m_parsingThread.nextStep())
1276 if (stepMode) break;
1279 if (!notOver) endMission();
1282 if (e.getSource().equals(m_stepButton))
1284 if (m_parsingThread != null)
1286 if (!m_parsingThread.nextStep())
1288 endMission();
1292 if (e.getSource().equals(m_openButton))
1294 openDocument();
1296 if (e.getSource().equals(m_saveButton))
1298 saveResult();
1300 if (e.getSource().equals(m_batchButton))
1302 openBatch();
1307 * void-consturctor method
1309 public TestTool()
1311 getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
1315 m_currentDirectory = new File(System.getProperty("user.dir"));
1317 catch(Exception e)
1319 System.out.println("getProperty error :"+e);
1324 * consturctor method with a specific connection URL
1326 public TestTool(String connecturl)
1328 this();
1329 m_unoURL = new String(connecturl);
1332 public static void main(String argv[])
1334 Dimension screenSize =
1335 Toolkit.getDefaultToolkit().getScreenSize();
1337 TestTool tt;
1339 if (argv.length < 1)
1341 System.out.println("Usage: java TestTool [javaTokenFile] [nssTokenPath] [xml file]?");
1342 return;
1345 boolean hasFile = false;
1346 boolean hasBatch = false;
1347 String fileName = null;
1349 if (argv.length >= 3)
1351 if (argv[2].startsWith("-b"))
1353 fileName = argv[2].substring(2);
1354 hasBatch = true;
1356 else
1358 fileName = argv[2];
1359 hasFile = true;
1363 tt = new TestTool();
1364 tt.m_javaTokenFile = new String(argv[0]);
1365 tt.m_nssTokenPath = new String(argv[1]);
1366 tt.connectSO(null);
1368 /* Set up a GUI framework */
1369 JFrame myFrame = new JFrame("XML Security Components Tester");
1370 myFrame.addWindowListener(
1371 new WindowAdapter() {
1372 public void windowClosing(WindowEvent e) {System.exit(0);}
1376 myFrame.setContentPane(tt.buildUI(screenSize.width, screenSize.height));
1377 myFrame.pack();
1378 int w = screenSize.width-30;
1379 int h = screenSize.height-30;
1380 myFrame.setLocation(screenSize.width/2 - w/2,
1381 screenSize.height/2 - h/2);
1382 myFrame.setSize(w, h);
1383 myFrame.setVisible(true);
1385 if (hasFile)
1387 tt.parseFile(new File(fileName));
1389 else if (hasBatch)
1391 tt.runBatch(new File(fileName));