//import graph.*; import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; import javax.swing.border.*; import java.io.*; import java.net.*; import java.util.*; //import javax.jnlp.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import java.sql.*; import com.sun.image.codec.jpeg.*; import org.jdom.*; import org.jdom.output.*; // Changed base class to JFrame since JApplet disabled keyboard shortcuts public class Araucaria extends JFrame implements Runnable { static int MAX_MESSAGELABEL_SIZE = 100; static String encoding = "UTF-8"; FileActionHandler fileHandler; File lastDirectory; File araucariaHome; File currentOpenXMLFile = null; JFileChooser fileChoice, xmlChoice, schemeChoice; Preferences preferencesDialog; PropertiesDialog propertiesDialog; JMenuItem openFileMenu, closeFileMenu, saveAsXMLFileMenu, saveXMLFileMenu, readXMLFileMenu, saveToDBMenu, viewSourceComments, searchMenu, selectAllMenu, saveJpegFileMenu, showPreferencesMenu, exitFileMenu, ownersMenu, showOwnersMenu, labelsMenu, showLabelsMenu, fullTextTreeMenu, undoMenu, redoMenu, setSourceComments, newGraphMenu, linkGraphMenu, unlinkGraphMenu, refutationGraphMenu, deleteGraphMenu, invertGraphMenu, missingPremiseMenu, selectSchemeMenu, argTypeSchemeMenu, saveSchemeMenu, openSchemeMenu, propertiesMenu, showHelpMenu, aboutHelpMenu, loginLoginMenu, registerLoginMenu; JMenu fileMenu, graphMenu, labelsOwnersMenu, argumentMenu, loginMenu, helpMenu, encodingFileMenu; JRadioButtonMenuItem encodingUTF8Menu, encodingBIG5Menu; JMenuBar menuBar; Action showOwnersAction, showLabelsAction; // ToolBar & buttons JToolBar m_toolBar; JButton m_openTextToolBar, m_openArgToolBar, m_saveArgToolBar, saveJpegToolBar, m_deleteToolBar, m_invertDiagramToolBar, m_missingPremiseToolBar, m_linkStatementsToolBar, m_unlinkStatementsToolBar, m_refutationToolBar, m_selectSchemeToolBar, m_addEditSchemeToolBar, m_ownersToolBar, m_showOwnersToolBar, m_labelsToolBar, m_showLabelsToolBar, m_undoToolBar, m_redoToolBar, m_saveToDBToolBar, m_searchDBToolBar, m_clearDiagramToolBar, m_flipDiagramToolBar, m_deleteSelectedToolBar, m_helpToolBar; boolean m_argumentSaved = true; JPanel m_panel = new JPanel(); JPanel m_messagePanel = new JPanel(new BorderLayout()); JLabel m_messageLabel = new JLabel("Messages will be displayed here."); public static Color STATUSBAR_BACKGROUND = new Color(1.0f, 1.0f, 0.7f); JPanel m_canvasPanel = new JPanel(new BorderLayout()); TreeCanvas m_canvas; Tree m_tree; Vector m_treeTraversal = null; Vector m_freeVertexList = new Vector(); String m_shortLabel = "A"; // Statistics int m_wordCount = 0; int m_width, m_height; int m_freeVertexX, m_freeVertexY; int[] layerSize; SelectText m_selectText; boolean m_invertedTree; JScrollPane selectScrollPane; HelpHTMLDialog helpDialog; ArgInfoFrame argInfoFrame; JComboBox searchResultCombo; boolean doComboEvents = false; // Database objects Connection m_dbConnection; Statement m_statement; static final int ARGID = 0; SearchFrame searchFrame = new SearchFrame(this, false); RegistrationDialog registrationDialog = new RegistrationDialog(this); LoginDialog loginDialog = new LoginDialog(this); String loggedInUser = null; String m_argumentDate = "", m_argumentAuthor = ""; public Set ownerList, supportLabelList; public static String ipAddress, databaseName, username, password; String source, comments, author, date; public static int databaseType; public static final int MYSQL = 0, SQLSERVER = 1; /** * To add a new database type to Araucaria, need to: * 1. add a new radio button to the Preferences dialog, * 2. add code to initializeDatabase() to load the driver * 3. change sql statements in all the database methods if required * (e.g. SQL Server requires [user] instead of user...) */ public static String textDirectory, amlDirectory, schemeDirectory; // Undo/redo stack public UndoStack undoStack = new UndoStack(); public void run() { Thread currThread = Thread.currentThread(); try { if (currThread.getName().equals("Main")) { new SplashScreen(); } else if (currThread.getName().equals("OpenDatabase")) { openDatabase(); } else if (currThread.getName().equals("Messages")) { m_messageLabel.setText("Connecting to database..."); } } catch (Exception ex) { System.out.println ("run: " + currThread.getName() + ": " + ex.toString()); } } public Araucaria() { Thread splashThread = new Thread(this, "Main"); splashThread.start(); setTitle("Araucaria"); createIcon(this); m_canvas = new TreeCanvas(this); // m_canvas.setPreferredSize(new Dimension(640, 500)); m_tree = new Tree(this); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().setBackground(Color.red); m_toolBar = new JToolBar(); getContentPane().add(BorderLayout.NORTH, m_toolBar); m_canvasPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); m_canvasPanel.add(m_canvas, BorderLayout.CENTER); m_canvasPanel.setBackground(TreeCanvas.DIAGRAM_BACKGROUND); getContentPane().add(m_canvasPanel, BorderLayout.CENTER ); m_messageLabel.setText("Messages will be displayed here."); m_messageLabel.setBackground(STATUSBAR_BACKGROUND); m_messagePanel.setBackground(STATUSBAR_BACKGROUND); m_messagePanel.add(m_messageLabel); m_messagePanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); getContentPane().add(BorderLayout.SOUTH, m_messagePanel); m_selectText = new SelectText(230, 800); selectScrollPane = new JScrollPane(m_selectText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); selectScrollPane.getViewport().setBackground(SelectText.TEXT_BACKGROUND); JPanel scrollPanel = new JPanel(new BorderLayout()); scrollPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); scrollPanel.add(selectScrollPane, BorderLayout.CENTER); getContentPane().add(BorderLayout.WEST, scrollPanel); argInfoFrame = new ArgInfoFrame(this); // initArgInfoVector(); ownerList = new HashSet(); supportLabelList = new HashSet(); } public void printCanvasSize(int ref) { System.out.println ("Canvas size " + ref + ": " + m_canvas.getWidth() + " x " + m_canvas.getHeight()); } public void initSize() { Dimension size = m_canvas.getSize(); m_width = size.width; m_height = size.height; m_freeVertexX = TreeCanvas.NODE_DIAM / 4; m_freeVertexY = m_height - TreeCanvas.NODE_DIAM; } /** * Only used in testing - loads a sample scheme into the scheme dialog */ /* private void initArgInfoVector() { String argInfoXML = "Argument from Position to Know" + "
a is in a position to know whether A is true" + "a asserts that A is trueA is true" + "
Is a in a position to know whether A is true?" + " Is a an honest (trustworthy, reliable) source?" + " Did a actually assert that A is true?
"; try { AraucariaXML xmlCC = new AraucariaXML(new StringReader(argInfoXML)); xmlCC.setGlobals(this, getSelectText(), getTree(), getTreeCanvas()); xmlCC.Statement(); } catch (Exception e) { System.out.println("Parser exception: " + e.toString()); } catch (Error e) { System.out.println("Parser error: " + e.toString()); } argInfoFrame.loadArgTypeCombo(); searchFrame.updateSchemesetSearchCombo(); } */ public static void createIcon(Frame frame) { try { ClassLoader loader = frame.getClass().getClassLoader(); if (loader == null) return; ImageIcon icon = new ImageIcon(loader.getResource("AraucariaIcon.jpg")); frame.setIconImage(icon.getImage()); } catch(Exception ex){ System.out.println("ImageIcon Problem: " + ex); } } public void init() { JFrame frame = new JFrame(); Araucaria.createIcon(frame); m_canvas.setSubtreeFrame(new SubtreeFrame(true, frame, this)); } public void appInit() { JFrame frame = new JFrame(); Araucaria.createIcon(frame); m_canvas.setSubtreeFrame(new SubtreeFrame(false, frame, this)); } private void addToolBarMenus() { m_toolBar.setFloatable(false); m_toolBar.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED)); m_toolBar.setAlignmentX(LEFT_ALIGNMENT); // File toolbar Action openTextAction = new FileActionHandler("Open text file", new ImageIcon("images/OpenDoc.gif")); openTextAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_T, ActionEvent.CTRL_MASK)); openTextAction.putValue(Action.SHORT_DESCRIPTION, "Open text file"); Action openArgAction = new FileActionHandler("Open argument", new ImageIcon("images/OpenArrow.gif")); openArgAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_O, ActionEvent.CTRL_MASK)); openArgAction.putValue(Action.SHORT_DESCRIPTION, "Open argument"); Action saveArgAction = new FileActionHandler("Save argument", new ImageIcon("images/FolderIn.gif")); saveArgAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_S, ActionEvent.CTRL_MASK)); saveArgAction.putValue(Action.SHORT_DESCRIPTION, "Save argument"); Action saveAsArgAction = new FileActionHandler("Save as..."); saveAsArgAction.putValue(Action.SHORT_DESCRIPTION, "Save argument as new file"); Action saveJpegAction = new FileActionHandler("Save diagram", new ImageIcon("images/DocumentIn.gif")); saveJpegAction.putValue(Action.SHORT_DESCRIPTION, "Save diagram"); saveJpegAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_D, ActionEvent.CTRL_MASK)); Action closeAllAction = new FileActionHandler("Close all"); closeAllAction.putValue(Action.SHORT_DESCRIPTION, "Close all"); closeAllAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_N, ActionEvent.CTRL_MASK)); // File menu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); // openFileMenu = new JMenuItem(openTextAction); openFileMenu.setMnemonic(KeyEvent.VK_T); closeFileMenu = new JMenuItem(closeAllAction); closeFileMenu.setMnemonic(KeyEvent.VK_C); saveXMLFileMenu = new JMenuItem(saveArgAction); saveXMLFileMenu.setMnemonic(KeyEvent.VK_S); saveAsXMLFileMenu = new JMenuItem(saveAsArgAction); saveAsXMLFileMenu.setMnemonic(KeyEvent.VK_A); readXMLFileMenu = new JMenuItem(openArgAction); readXMLFileMenu.setMnemonic(KeyEvent.VK_O); saveJpegFileMenu = new JMenuItem(saveJpegAction); saveJpegFileMenu.setMnemonic(KeyEvent.VK_D); fullTextTreeMenu = new JMenuItem("Full text"); fullTextTreeMenu.setMnemonic(KeyEvent.VK_F); fullTextTreeMenu.addActionListener(fileHandler); fileMenu.add(openFileMenu); propertiesMenu = new JMenuItem("Properties"); propertiesMenu.setMnemonic(KeyEvent.VK_R); propertiesMenu.addActionListener(fileHandler); encodingFileMenu = new JMenu("Set encoding"); encodingFileMenu.setMnemonic(KeyEvent.VK_E); // fileMenu.add(encodingFileMenu); ButtonGroup encodingGroup = new ButtonGroup(); encodingUTF8Menu = new JRadioButtonMenuItem("UTF-8"); encodingGroup.add(encodingUTF8Menu); encodingFileMenu.add(encodingUTF8Menu); encodingUTF8Menu.addActionListener(fileHandler); encodingUTF8Menu.setSelected(true); encodingBIG5Menu = new JRadioButtonMenuItem("BIG5"); encodingGroup.add(encodingBIG5Menu); encodingFileMenu.add(encodingBIG5Menu); encodingBIG5Menu.addActionListener(fileHandler); fileMenu.addSeparator(); fileMenu.add(readXMLFileMenu); fileMenu.add(saveXMLFileMenu); fileMenu.add(saveAsXMLFileMenu); fileMenu.addSeparator(); fileMenu.add(saveJpegFileMenu); fileMenu.add(fullTextTreeMenu); fileMenu.add(propertiesMenu); fileMenu.addSeparator(); fileMenu.add(closeFileMenu); showPreferencesMenu = new JMenuItem("Preferences"); showPreferencesMenu.setMnemonic(KeyEvent.VK_P); showPreferencesMenu.addActionListener(fileHandler); fileMenu.add(showPreferencesMenu); fileMenu.addSeparator(); exitFileMenu = new JMenuItem("Exit"); exitFileMenu.setMnemonic(KeyEvent.VK_X); exitFileMenu.addActionListener(fileHandler); fileMenu.add(exitFileMenu); // Edit toolbar Action clearDiagramAction = new FileActionHandler("Clear diagram", new ImageIcon("images/Document.gif")); clearDiagramAction.putValue(Action.SHORT_DESCRIPTION, "Clear diagram"); clearDiagramAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_C, ActionEvent.CTRL_MASK)); Action invertDiagramAction = new FileActionHandler("Flip diagram", new ImageIcon("images/DocumentDiagram.gif")); invertDiagramAction.putValue(Action.SHORT_DESCRIPTION, "Flip diagram"); invertDiagramAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_F, ActionEvent.CTRL_MASK)); Action missingPremiseAction = new FileActionHandler("Missing premise", new ImageIcon("images/RotCCRight.gif")); missingPremiseAction.putValue(Action.SHORT_DESCRIPTION, "Missing premise"); missingPremiseAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_M, ActionEvent.CTRL_MASK)); Action refutationAction = new FileActionHandler("Refutation", new ImageIcon("images/Widen.gif")); refutationAction.putValue(Action.SHORT_DESCRIPTION, "Refutation"); refutationAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_R, ActionEvent.CTRL_MASK)); Action linkStatementsAction = new FileActionHandler("Link statements", new ImageIcon("images/Pin.gif")); linkStatementsAction.putValue(Action.SHORT_DESCRIPTION, "Link statements"); linkStatementsAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_L, ActionEvent.CTRL_MASK)); Action unlinkStatementsAction = new FileActionHandler("Unlink statements", new ImageIcon("images/PinLeft.gif")); unlinkStatementsAction.putValue(Action.SHORT_DESCRIPTION, "Unlink statements"); unlinkStatementsAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_U, ActionEvent.CTRL_MASK)); Action selectAllAction = new FileActionHandler("Select all nodes"); selectAllAction.putValue(Action.SHORT_DESCRIPTION, "Select all nodes"); selectAllAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_A, ActionEvent.CTRL_MASK)); // Action ownersAction = new FileActionHandler("Modify ownership", new ImageIcon("images/Forward.gif")); Action ownersAction = new FileActionHandler("Modify ownership", null); ownersAction.putValue(Action.SHORT_DESCRIPTION, "Modify ownership"); ownersAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_W, ActionEvent.CTRL_MASK)); // showOwnersAction = new FileActionHandler("Hide owners", new ImageIcon("images/DeleteUser.gif")); showOwnersAction = new FileActionHandler("Hide owners", null); showOwnersAction.putValue(Action.SHORT_DESCRIPTION, "Hide owners"); showOwnersAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_H, ActionEvent.CTRL_MASK)); // Action labelsAction = new FileActionHandler("Modify evaluation", new ImageIcon("images/Forward.gif")); Action labelsAction = new FileActionHandler("Modify evaluation", null); labelsAction.putValue(Action.SHORT_DESCRIPTION, "Modify evaluation"); labelsAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_K, ActionEvent.CTRL_MASK)); // showLabelsAction = new FileActionHandler("Hide labels", new ImageIcon("images/LabelOff.gif")); showLabelsAction = new FileActionHandler("Hide evaluations", null); showLabelsAction.putValue(Action.SHORT_DESCRIPTION, "Hide evaluations"); showLabelsAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_G, ActionEvent.CTRL_MASK)); Action deleteAction = new FileActionHandler("Delete selected", new ImageIcon("images/Error.gif")); deleteAction.putValue(Action.SHORT_DESCRIPTION, "Delete selected"); deleteAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0)); Action undoAction = new FileActionHandler("Undo", new ImageIcon("images/Undo20.gif")); undoAction.putValue(Action.SHORT_DESCRIPTION, "Undo"); undoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); Action redoAction = new FileActionHandler("Redo", new ImageIcon("images/Redo20.gif")); redoAction.putValue(Action.SHORT_DESCRIPTION, "Redo"); redoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK)); // Edit menu graphMenu = new JMenu("Edit"); graphMenu.setMnemonic(KeyEvent.VK_E); newGraphMenu = new JMenuItem(clearDiagramAction); newGraphMenu.setMnemonic(KeyEvent.VK_C); newGraphMenu.setSelectedIcon(new ImageIcon("images/DocumentDiagram.gif")); invertGraphMenu = new JMenuItem(invertDiagramAction); invertGraphMenu.setMnemonic(KeyEvent.VK_F); missingPremiseMenu = new JMenuItem(missingPremiseAction); missingPremiseMenu.setMnemonic(KeyEvent.VK_M); linkGraphMenu = new JMenuItem(linkStatementsAction); linkGraphMenu.setMnemonic(KeyEvent.VK_L); unlinkGraphMenu = new JMenuItem(unlinkStatementsAction); unlinkGraphMenu.setMnemonic(KeyEvent.VK_U); refutationGraphMenu = new JMenuItem(refutationAction); refutationGraphMenu.setMnemonic(KeyEvent.VK_R); selectAllMenu = new JMenuItem(selectAllAction); selectAllMenu.setMnemonic(KeyEvent.VK_A); deleteGraphMenu = new JMenuItem(deleteAction); deleteGraphMenu.setMnemonic(KeyEvent.VK_D); undoMenu = new JMenuItem(undoAction); undoMenu.setMnemonic(KeyEvent.VK_N); redoMenu = new JMenuItem(redoAction); redoMenu.setMnemonic(KeyEvent.VK_O); viewSourceComments = new JMenuItem("View source & comments"); viewSourceComments.setMnemonic(KeyEvent.VK_V); viewSourceComments.addActionListener(fileHandler); setSourceComments = new JMenuItem("Set source & comments"); setSourceComments.setMnemonic(KeyEvent.VK_S); setSourceComments.addActionListener(fileHandler); graphMenu.add(undoMenu); graphMenu.add(redoMenu); graphMenu.addSeparator(); graphMenu.add(newGraphMenu); graphMenu.add(invertGraphMenu); graphMenu.addSeparator(); graphMenu.add(missingPremiseMenu); graphMenu.add(refutationGraphMenu); graphMenu.add(deleteGraphMenu); graphMenu.add(linkGraphMenu); graphMenu.add(unlinkGraphMenu); graphMenu.add(selectAllMenu); // LabelsOwnersMenu labelsOwnersMenu = new JMenu("Labels"); labelsOwnersMenu.setMnemonic(KeyEvent.VK_L); ownersMenu = new JMenuItem(ownersAction); ownersMenu.setMnemonic(KeyEvent.VK_W); showOwnersMenu = new JMenuItem(showOwnersAction); showOwnersMenu.setSelected(true); showOwnersMenu.setMnemonic(KeyEvent.VK_H); labelsMenu = new JMenuItem(labelsAction); labelsMenu.setMnemonic(KeyEvent.VK_O); showLabelsMenu = new JMenuItem(showLabelsAction); showLabelsMenu.setMnemonic(KeyEvent.VK_I); showLabelsMenu.setSelected(true); labelsOwnersMenu.add(ownersMenu); labelsOwnersMenu.add(showOwnersMenu); labelsOwnersMenu.addSeparator(); labelsOwnersMenu.add(labelsMenu); labelsOwnersMenu.add(showLabelsMenu); // Scheme menu m_toolBar.addSeparator(); Action selectSchemeAction = new FileActionHandler("Select scheme", new ImageIcon("images/FlowGraph.gif")); selectSchemeAction.putValue(Action.SHORT_DESCRIPTION, "Select scheme"); selectSchemeAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_E, ActionEvent.CTRL_MASK)); Action addEditSchemeAction = new FileActionHandler("Add/edit scheme");//, new ImageIcon("images/EditBook.gif")); addEditSchemeAction.putValue(Action.SHORT_DESCRIPTION, "Add/edit scheme"); addEditSchemeAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_I, ActionEvent.CTRL_MASK)); // m_addEditSchemeToolBar = m_toolBar.add(addEditSchemeAction); Action saveSchemeAction = new FileActionHandler("Save schemeset");//, new ImageIcon("images/FlowGraph.gif")); saveSchemeAction.putValue(Action.SHORT_DESCRIPTION, "Save schemeset"); saveSchemeAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_V, ActionEvent.CTRL_MASK)); // m_saveSchemeToolBar = m_toolBar.add(saveSchemeAction); Action openSchemeAction = new FileActionHandler("Open schemeset");//, new ImageIcon("images/Book.gif")); openSchemeAction.putValue(Action.SHORT_DESCRIPTION, "Open schemeset"); openSchemeAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_P, ActionEvent.CTRL_MASK)); // m_openSchemeToolBar = m_toolBar.add(openSchemeAction); argumentMenu = new JMenu("Schemes"); argumentMenu.setMnemonic(KeyEvent.VK_S); selectSchemeMenu = new JMenuItem(selectSchemeAction); selectSchemeMenu.setMnemonic(KeyEvent.VK_E); argTypeSchemeMenu = new JMenuItem(addEditSchemeAction); argTypeSchemeMenu.setMnemonic(KeyEvent.VK_I); saveSchemeMenu = new JMenuItem(saveSchemeAction); saveSchemeMenu.setMnemonic(KeyEvent.VK_V); openSchemeMenu = new JMenuItem(openSchemeAction); openSchemeMenu.setMnemonic(KeyEvent.VK_P); argumentMenu.add(selectSchemeMenu); argumentMenu.add(argTypeSchemeMenu); argumentMenu.addSeparator(); argumentMenu.add(saveSchemeMenu); argumentMenu.add(openSchemeMenu); // AraucariaDB menu Action loginAction = new FileActionHandler("Login"); loginAction.putValue(Action.SHORT_DESCRIPTION, "Login to database"); Action registerAction = new FileActionHandler("Register"); registerAction.putValue(Action.SHORT_DESCRIPTION, "Register to use database"); Action saveDBAction = new FileActionHandler("Save to database", new ImageIcon("images/DataStore.gif")); saveDBAction.putValue(Action.SHORT_DESCRIPTION, "Save to database"); saveDBAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_B, ActionEvent.CTRL_MASK)); Action searchDBAction = new FileActionHandler("Search database", new ImageIcon("images/DataQuery2.gif")); searchDBAction.putValue(Action.SHORT_DESCRIPTION, "Search database"); searchDBAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); loginMenu = new JMenu("AraucariaDB"); loginMenu.setMnemonic(KeyEvent.VK_D); loginLoginMenu = new JMenuItem(loginAction); loginLoginMenu.setMnemonic(KeyEvent.VK_L); registerLoginMenu = new JMenuItem(registerAction); registerLoginMenu.setMnemonic(KeyEvent.VK_R); saveToDBMenu = new JMenuItem(saveDBAction); saveToDBMenu.setMnemonic(KeyEvent.VK_S); searchMenu = new JMenuItem(searchDBAction); searchMenu.setMnemonic(KeyEvent.VK_E); loginMenu.add(loginLoginMenu); loginMenu.add(registerLoginMenu); loginMenu.addSeparator(); loginMenu.add(saveToDBMenu); loginMenu.add(searchMenu); // ComboBox for displaying search results searchResultCombo = new JComboBox(); searchResultCombo.setFont(new Font("SansSerif", Font.PLAIN, 12)); searchResultCombo.addActionListener(new FileActionHandler()); String comboSizeString = "2. If any journalists learn about the invasion,"; searchResultCombo.setPrototypeDisplayValue(comboSizeString); // Help menu Action helpAction = new FileActionHandler("Help", new ImageIcon("images/Help.gif")); helpAction.putValue(Action.SHORT_DESCRIPTION, "Help"); helpAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_F1, 0)); helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); showHelpMenu = new JMenuItem(helpAction); aboutHelpMenu = new JMenuItem("About", KeyEvent.VK_A); aboutHelpMenu.addActionListener(fileHandler); helpMenu.add(showHelpMenu); helpMenu.add(aboutHelpMenu); // Build toolbar m_openTextToolBar = m_toolBar.add(openTextAction); m_openArgToolBar = m_toolBar.add(openArgAction); m_saveArgToolBar = m_toolBar.add(saveArgAction); m_toolBar.addSeparator(); m_undoToolBar = m_toolBar.add(undoAction); m_redoToolBar = m_toolBar.add(redoAction); m_clearDiagramToolBar = m_toolBar.add(clearDiagramAction); m_invertDiagramToolBar = m_toolBar.add(invertDiagramAction); saveJpegToolBar = m_toolBar.add(saveJpegAction); m_toolBar.addSeparator(); m_missingPremiseToolBar = m_toolBar.add(missingPremiseAction); m_refutationToolBar = m_toolBar.add(refutationAction); m_deleteToolBar = m_toolBar.add(deleteAction); m_linkStatementsToolBar = m_toolBar.add(linkStatementsAction); m_unlinkStatementsToolBar = m_toolBar.add(unlinkStatementsAction); m_toolBar.addSeparator(); m_selectSchemeToolBar = m_toolBar.add(selectSchemeAction); // m_ownersToolBar = m_toolBar.add(ownersAction); // m_showOwnersToolBar = m_toolBar.add(showOwnersAction); // m_showOwnersToolBar.setSelected(true); // m_toolBar.addSeparator(); // m_labelsToolBar = m_toolBar.add(labelsAction); // m_showLabelsToolBar = m_toolBar.add(showLabelsAction); // m_showLabelsToolBar.setSelected(true); m_toolBar.addSeparator(); m_saveToDBToolBar = m_toolBar.add(saveDBAction); m_searchDBToolBar = m_toolBar.add(searchDBAction); m_toolBar.add(searchResultCombo); m_helpToolBar = m_toolBar.add(helpAction); } public String trimPathName(String path) { int homeDot = path.indexOf(File.separator + "."); if(homeDot > 0) { path = path.substring(0, homeDot); } return path; } /** * Used only in the stand-alone application. * Adds menus and handlers to the JFrame */ public void setupFrame(JFrame testFrame) { testFrame.addWindowListener(new WindowHandler()); fileHandler = new FileActionHandler(); testFrame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { m_width = m_canvas.getWidth(); m_height = m_canvas.getHeight(); m_canvas.redrawTree(); m_canvas.calcSubtreeShapes(); m_canvas.repaint(); } }); try { File currentDir = new File("."); lastDirectory = new File(currentDir.getAbsolutePath()); araucariaHome = new File(currentDir.getAbsolutePath()); String homePath = trimPathName(araucariaHome.getAbsolutePath()); textDirectory = homePath + File.separator + "TextFiles"; amlDirectory = homePath + File.separator + "AMLFiles"; schemeDirectory = homePath + File.separator + "SchemeFiles"; // Add extension filters for the file dialog ExtensionFileFilter extFilter = new ExtensionFileFilter(); extFilter.addExtension("txt"); fileChoice = new JFileChooser(); fileChoice.setFileFilter(extFilter); // Set up the XML dialog ExtensionFileFilter xmlFilter = new ExtensionFileFilter(); xmlFilter.addExtension("aml"); xmlChoice = new JFileChooser(); xmlChoice.setFileFilter(xmlFilter); // Set up the scheme dialog ExtensionFileFilter schemeFilter = new ExtensionFileFilter(); schemeFilter.addExtension("scm"); schemeChoice = new JFileChooser(); schemeChoice.setFileFilter(schemeFilter); // Set up database parameters - default DB is MySQL on Chris's machine ipAddress = "134.36.34.192"; databaseName = "araucaria_v1_0"; username = "araucaria_client"; password = ""; databaseType = MYSQL; initializeDatabase(); // Set up the preferences dialog preferencesDialog = new Preferences(this, true); } catch (Exception e) { System.out.println ("Error in Araucaria.setupFrame: " + e.toString()); } addToolBarMenus(); // Build menu menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(graphMenu); menuBar.add(labelsOwnersMenu); menuBar.add(argumentMenu); menuBar.add(loginMenu); menuBar.add(helpMenu); testFrame.setJMenuBar(menuBar); } public void initializeDatabase() { this.dbAddress = null; if (databaseType == MYSQL) { try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch(Exception ex) { ex.printStackTrace(); } } else if (databaseType == SQLSERVER) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); } catch (Exception ex) { ex.printStackTrace(); } } } public void resetDefaultParams() { STATUSBAR_BACKGROUND = new Color(1.0f, 1.0f, 0.7f); TreeCanvas.DIAGRAM_BACKGROUND = Color.white; SelectText.TEXT_BACKGROUND = new Color(0.75f, 1.0f, 1.0f); String homePath = araucariaHome.getAbsolutePath(); int homeDot = homePath.indexOf(File.separator + "."); if(homeDot > 0) { homePath = homePath.substring(0, homeDot); } textDirectory = homePath + File.separator + "TextFiles"; amlDirectory = homePath + File.separator + "AMLFiles"; schemeDirectory = homePath + File.separator + "SchemeFiles"; ipAddress = "134.36.34.192"; databaseName = "araucaria_v1_0"; username = "araucaria_client"; password = ""; databaseType = MYSQL; initializeDatabase(); } public static void main(String[] argv) { String version = System.getProperty("java.version"); int[] versionComp = new int[3]; StringTokenizer versionTok = new StringTokenizer(version, "."); int i = 0; while (versionTok.hasMoreTokens()) { versionComp[i++] = Integer.parseInt(versionTok.nextToken().substring(0,1)); } int yesNo = 0; if (!(versionComp[0] >= 1 && versionComp[1] >= 4 && versionComp[2] >= 1)) { yesNo = JOptionPane.showConfirmDialog(null, "Araucaria requires Java Runtime Environment\n" + "version 1.4.1 or later to run. Your computer is using version " + version + ".\n" + "Araucaria may not work properly with this version.\nDo you want to continue?", "Old JRE version", JOptionPane.YES_NO_OPTION); } if (yesNo != 0) { System.exit(1); } Araucaria araucaria = new Araucaria(); araucaria.setSize(900, 630); araucaria.appInit(); araucaria.emptyTree(true); araucaria.setupFrame(araucaria); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); araucaria.setLocation(d.width/2 - araucaria.getSize().width/2, d.height/2 - araucaria.getSize().height/2); /** * Testing full screen mode */ /* GraphicsEnvironment graphEnv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice graphDevice = graphEnv.getDefaultScreenDevice(); if(graphDevice.isFullScreenSupported()) { System.out.println ("Full screen"); araucaria.setUndecorated(true); graphDevice.setFullScreenWindow(araucaria); } */ araucaria.show(); araucaria.initSize(); } public void emptyFreeVertexList() { m_freeVertexList = new Vector(); m_freeVertexX = TreeCanvas.NODE_DIAM / 2; m_freeVertexY = m_height - TreeCanvas.NODE_DIAM; m_shortLabel = "A"; m_selectText.clearAllSelectedText(); m_selectText.repaint(); } public void emptyTree(boolean clearFreeVertexList) { m_tree = new Tree(this); m_canvas.clearLists(); m_canvas.setSubtreeNumber(0); if (clearFreeVertexList) emptyFreeVertexList(); m_treeTraversal = null; ownerList = new HashSet(); supportLabelList = new HashSet(); source = ""; comments = ""; date = null; author = null; m_canvas.repaint(); } /** * Calculates the traversal of the tree (needed for other stuff) * the number of vertices in each layer, and the position at * which each node is to be drawn */ public void calcTreeShape(TreeVertex root) { if (root == null) { m_treeTraversal = null; return; } m_treeTraversal = m_tree.breadthFirstTraversal(root); m_tree.calcNodeCoords(m_width, m_height, TreeCanvas.NODE_DIAM, m_invertedTree); m_canvas.setTraversal(m_treeTraversal); } /** * Finds the maximum short label currently in use in either the * free vertex list or the tree. */ public String getMaxShortLabel() { String maxLabel = "A"; for (int i = 0; i maxLabel.length()) { maxLabel = label; } else if (label.length() == maxLabel.length()) { if (label.compareTo(maxLabel) > 0) { maxLabel = label; } } } if (m_treeTraversal == null) { return maxLabel; } for (int i = 0; i maxLabel.length()) { maxLabel = label; } else if (label.length() == maxLabel.length()) { if (label.compareTo(maxLabel) > 0) { maxLabel = label; } } } return maxLabel; } /** * Calculates the location to draw the next free vertex */ public void calcFreeVertexPosition() { char[] label = m_shortLabel.toCharArray(); int labelLength = m_shortLabel.length(); if (labelLength == 1) { m_freeVertexX = label[0] >= 'a' ? TreeCanvas.NODE_DIAM / 4 + (label[0] - 'a') * TreeCanvas.NODE_DIAM : TreeCanvas.NODE_DIAM / 4 + (label[0] - 'A') * TreeCanvas.NODE_DIAM; m_freeVertexY = label[0] >= 'a' ? m_height - TreeCanvas.NODE_DIAM : m_height - 2* TreeCanvas.NODE_DIAM; } else if (labelLength == 2) { m_freeVertexX = label[1] >= 'a' ? TreeCanvas.NODE_DIAM / 4 + (label[1] - 'a') * TreeCanvas.NODE_DIAM : TreeCanvas.NODE_DIAM / 4 + (label[1] - 'A') * TreeCanvas.NODE_DIAM; m_freeVertexY = label[1] >= 'a' ? m_height - TreeCanvas.NODE_DIAM : m_height - 2* TreeCanvas.NODE_DIAM; } } /** * Increments the short label used to label nodes * If the label is a single letter, it increments by following * the sequence A B C ... Z a b c ... z * When z is reached, the labels start double letters, so we have * AA AB AC ... AZ Aa Ab Ac ... Az BA BB BC ... etc * No check is made as to what happens after zz * This allows 2756 distinct labels - should be enough. * * Returns m_shortLabel before the increment */ public String incrementShortLabel() { String oldLabel = new String(m_shortLabel); int labelLength = m_shortLabel.length(); char[] label = m_shortLabel.toCharArray(); if (labelLength == 1) { if (label[0] == 'Z') { m_shortLabel = "a"; m_freeVertexX = TreeCanvas.NODE_DIAM / 4; m_freeVertexY += m_width / 26; } else if (label[0] == 'z') { m_shortLabel = "AA"; } else { label[0]++; m_shortLabel = new String(label); } } else if (labelLength == 2) { if (label[1] == 'Z') { label[1] = 'a'; m_shortLabel = new String(label); m_freeVertexX = TreeCanvas.NODE_DIAM / 4; m_freeVertexY += m_width / 26; } else if (label[1] == 'z') { if (label[0] == 'Z') { label[0] = 'a'; } else { // Don't bother checking if the first letter is 'z' label[0]++; } label[1] = 'A'; m_shortLabel = new String(label); m_freeVertexX = TreeCanvas.NODE_DIAM / 4; m_freeVertexY = m_height - TreeCanvas.NODE_DIAM; } else { label[1]++; m_shortLabel = new String(label); } } calcFreeVertexPosition(); return oldLabel; } /** * Adds a new free vertex at the bottom of the canvas. * The free vertex has a label obtained from the selected text, * a short label generated as a consecutive char within this class, * and a shape reference so that the greyed out text can be un-greyed * if the vertex is deleted. */ public void addFreeVertex(String label, GeneralPath shape, int offset) { m_shortLabel = getTree().firstAvailableVertexID(); TreeVertex free = new TreeVertex(label, m_shortLabel); free.setAuxObject(shape); free.setOffset(offset); if (offset < 0) free.setMissing(true); String oldLabel = incrementShortLabel(); free.setDrawPoint(m_freeVertexX, m_freeVertexY); m_freeVertexList.add(free); } public String writeSchemeset() { try { Element root = new Element("ARG"); Document doc = new Document(root); DocType argDTD = new DocType("ARG", "argument.dtd"); doc.setDocType(argDTD); // Schemeset root.addContent(jdomSchemeset()); // Extract the JDOM tree as XML text ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); // Output text using 2 blanks as indent, and with line breaks XMLOutputter outputter = new XMLOutputter(" ", true); outputter.output(doc, byteOutput); String stringOutput = new String(byteOutput.toByteArray()); return stringOutput; } catch (Exception e) { System.out.println(e.toString()); } return null; } public void readXML() { File saveDirectory = null; String fileName = ""; File chosenFile = null; try { xmlChoice.setDialogTitle("Open argument"); // Sets directory to amlDirectory specified in preferences xmlChoice.setCurrentDirectory(new File(amlDirectory)); if (xmlChoice.showOpenDialog(Araucaria.this) != JFileChooser.APPROVE_OPTION) { return; } lastDirectory = xmlChoice.getCurrentDirectory(); chosenFile = xmlChoice.getSelectedFile(); // See if user has typed in the .aml suffix. If not, add it. if (chosenFile.getPath().indexOf(".aml") == -1) { String newPath = chosenFile.getPath() + ".aml"; chosenFile = new File(newPath); } if (!chosenFile.exists()) { m_messageLabel.setText("File does not exist."); return; } fileName = chosenFile.getAbsolutePath(); } catch (Exception e) { } try { emptyTree(true); // Try using SAX to parse the XML file FileInputStream fileStream = new FileInputStream(fileName); char inBuffer[] = new char[(int)chosenFile.length()]; // BIG5 is for Chinese // BufferedReader r = new BufferedReader(new InputStreamReader(chosenInput, )); InputStreamReader isReader = new InputStreamReader(fileStream, Araucaria.encoding); BufferedReader r = new BufferedReader(isReader); int charsRead = r.read(inBuffer, 0, inBuffer.length); String text = new String(inBuffer); text = text.substring(0, charsRead); inBuffer = text.toCharArray(); CharArrayReader charReader = new CharArrayReader(inBuffer); /* byte[] bytes = new byte[1024]; StringBuffer byteString = new StringBuffer(); do { int count = fileStream.read(bytes); if (count == -1) break; for (int i = 0; i < count; i++) { byte[] b = new byte[1]; if (bytes[i] == 13 || bytes[i] == 10) bytes[i] = 32; b[0] = bytes[i]; byteString.append(new String(b)); } } while (true); */ fileStream.close(); // ByteArrayInputStream byteStream = new ByteArrayInputStream(byteString.toString().getBytes()); // ByteArrayInputStream byteStream = new ByteArrayInputStream(text.getBytes()); // SAX's InputSource can determine the encoding from the tag in the XML file // so no need to specify it explicitly here. // InputSource saxInput = new InputSource(byteStream); InputSource saxInput = new InputSource(charReader); parseXMLwithSAX(saxInput, m_tree, m_canvas, m_selectText); m_messageLabel.setText("File " + fileName + " read successfully."); this.currentOpenXMLFile = chosenFile; m_wordCount = SelectText.wordCount(m_selectText.text); clearUndoStack(); } catch (IOException e) { m_messageLabel.setText("Error reading URI: " + e.getMessage()); } catch (SAXException e) { m_messageLabel.setText("Error in parsing " + fileName + ": " + e.getMessage()); } catch (Exception e) { m_messageLabel.setText("Error: " + fileName); } catch (Error e) { m_messageLabel.setText("Error: " + fileName); } } /** *

* This parses the file, using registered SAX handlers, and output * the events in the parsing process cycle. *

* * @param uri String URI of file to parse. */ public void parseXMLwithSAX(String uri, Tree tree) throws Exception { org.xml.sax.ContentHandler contentHandler = new XMLContentHandler(Araucaria.this, m_selectText, tree, m_canvas); org.xml.sax.ErrorHandler errorHandler = new XMLErrorHandler(); XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser"); parser.setContentHandler(contentHandler); parser.setErrorHandler(errorHandler); parser.setFeature("http://xml.org/sax/features/validation", true); parser.setFeature("http://xml.org/sax/features/namespaces", false); parser.parse(uri); } /** * This version is called by doTreeSearch() and uses a TreeSearchContentHandler * to do the parsing. This builds the tree but ignores all schemesets, text, etc. */ public void parseXMLwithSAX(InputSource source, Tree tree) throws Exception { org.xml.sax.ContentHandler contentHandler = new TreeSearchContentHandler(tree); org.xml.sax.ErrorHandler errorHandler = new XMLErrorHandler(); XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser"); parser.setContentHandler(contentHandler); parser.setErrorHandler(errorHandler); parser.setFeature("http://xml.org/sax/features/validation", true); parser.setFeature("http://xml.org/sax/features/namespaces", false); parser.parse(source); } public void parseXMLwithSAX(InputSource source, Tree tree, TreeCanvas treeCanvas, SelectText selectText) throws Exception { org.xml.sax.ContentHandler contentHandler = new XMLContentHandler(Araucaria.this, selectText, tree, treeCanvas); org.xml.sax.ErrorHandler errorHandler = new XMLErrorHandler(); XMLReader parser = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser"); parser.setContentHandler(contentHandler); parser.setErrorHandler(errorHandler); parser.setFeature("http://xml.org/sax/features/validation", true); parser.setFeature("http://xml.org/sax/features/namespaces", false); parser.parse(source); } public String writeXMLHeader() { // Main ARG tag String writeString = "\r\n\r\n\r\n"; return writeString; } public Vector getSchemesetList() { if (argInfoFrame == null) return null; return argInfoFrame.getArgTypeVector(); } /** * Adds schemeset nodes to JDOM tree. */ private Element jdomSchemeset() { Element schemesetElement = new Element("SCHEMESET"); Vector argTypeVector = argInfoFrame.getArgTypeVector(); Enumeration argTypeList = argTypeVector.elements(); while (argTypeList.hasMoreElements()) { Element schemeElement = new Element("SCHEME"); schemesetElement.addContent(schemeElement); Element nameElement = new Element("NAME"); schemeElement.addContent(nameElement); ArgType argType = (ArgType)argTypeList.nextElement(); nameElement.setText(argType.getName()); Element formElement = new Element("FORM"); schemeElement.addContent(formElement); Vector premiseVector = argType.getPremises(); for (int i = 0; i < premiseVector.size(); i++ ) { Element premiseElement = new Element("PREMISE"); formElement.addContent(premiseElement); premiseElement.setText((String)premiseVector.elementAt(i)); } Element conclusionElement = new Element("CONCLUSION"); formElement.addContent(conclusionElement); conclusionElement.setText(argType.getConclusion()); Vector critQuesVector = argType.getCriticalQuestions(); Enumeration critQuesList = critQuesVector.elements(); while (critQuesList.hasMoreElements()) { Element cqElement = new Element("CQ"); schemeElement.addContent(cqElement); cqElement.setText((String)critQuesList.nextElement()); } } return schemesetElement; } /** * Uses JDOM to build the AML file. */ public String writeXML() { try { Element root = new Element("ARG"); Document doc = new Document(root); // DocType argDTD = new DocType("ARG", araucariaHome + System.getProperty("file.separator") + "argument.dtd"); DocType argDTD = new DocType("ARG", "argument.dtd"); doc.setDocType(argDTD); root.addContent(new ProcessingInstruction("Araucaria", Araucaria.encoding)); // Schemeset root.addContent(jdomSchemeset()); // Text Element textElement = new Element ("TEXT"); root.addContent(textElement); textElement.setText(m_selectText.getText()); // Argument tree getTree().jdomTraversal(root); // Edata stuff addEdataToAML(root); // Extract the JDOM tree as XML text // ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); CharArrayWriter charWriter = new CharArrayWriter(); // Output text using 2 blanks as indent, and with line breaks XMLOutputter outputter = new XMLOutputter(" ", true, Araucaria.encoding); // outputter.output(doc, byteOutput); outputter.output(doc, charWriter); // saveToDiskFile("writeXML", byteOutput.toByteArray()); // String stringOutput = new String(byteOutput.toByteArray()); // return stringOutput; String charString = charWriter.toString(); // saveToDiskFile("writeXML", charString.getBytes()); return charString; } catch (Exception e) { System.out.println(e.toString()); } return null; } public byte[] writeXMLAsBytes() { try { Element root = new Element("ARG"); Document doc = new Document(root); // DocType argDTD = new DocType("ARG", araucariaHome + System.getProperty("file.separator") + "argument.dtd"); DocType argDTD = new DocType("ARG", "argument.dtd"); doc.setDocType(argDTD); root.addContent(new ProcessingInstruction("Araucaria", Araucaria.encoding)); // Schemeset root.addContent(jdomSchemeset()); // Text Element textElement = new Element ("TEXT"); root.addContent(textElement); textElement.setText(m_selectText.getText()); // Edata stuff addEdataToAML(root); // Argument tree getTree().jdomTraversal(root); // Extract the JDOM tree as XML text ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); // Output text using 2 blanks as indent, and with line breaks XMLOutputter outputter = new XMLOutputter(" ", true, Araucaria.encoding); outputter.output(doc, byteOutput); return byteOutput.toByteArray(); } catch (Exception e) { System.out.println(e.toString()); } return null; } public void addEdataToAML(Element root) { Element edataElement = new Element("EDATA"); Element authorElement = new Element("AUTHOR"); if (author == null) { author = "null"; } authorElement.setText(author); Element dateElement = new Element("DATE"); if (date == null) { date = easyDateFormat("yyyy-MM-dd"); } dateElement.setText(date); Element sourceElement = new Element("SOURCE"); if (source == null) { source = ""; } sourceElement.setText(source); Element commentsElement = new Element("COMMENTS"); if (comments == null) { comments = ""; } commentsElement.setText(comments); edataElement.addContent(authorElement); edataElement.addContent(dateElement); edataElement.addContent(sourceElement); edataElement.addContent(commentsElement); root.addContent(edataElement); } public String getShortLabel() { return m_shortLabel; } public void setShortLabel(String shortLabel) { m_shortLabel = shortLabel; } public void setArgumentSaved(boolean saved) { m_argumentSaved = saved; } public void setDoComboEvents(boolean value) { doComboEvents = value; } public Tree getTree() { return m_tree; } public TreeCanvas getTreeCanvas() { return m_canvas; } public JLabel getMessageLabel() { return m_messageLabel; } public File getLastDirectory() { return lastDirectory; } public void setLastDirectory(File dir) { lastDirectory = dir; } public SelectText getSelectText() { return m_selectText; } public JScrollPane getSelectScrollPane() { return selectScrollPane; } public Vector getFreeVertexList() { return m_freeVertexList; } public Vector getFreeVerticesInList() { Vector list = new Vector(); for (int i = 0; i 0) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
This will erase the current tree.
" + "Do you want to continue?
", "Delete current tree?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { m_messageLabel.setText("Action cancelled."); return; } } emptyTree(true); clearUndoStack(); m_selectText.clearText(); m_messageLabel.setText("All data cleared."); } public void openTextFile() { File chosenFile = null; FileInputStream chosenInput = null; if (m_tree.getRoots().size() > 0) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Loading new text will erase the current tree.
" + "Do you want to continue?
", "Delete current tree?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { m_messageLabel.setText("Text not loaded."); return; } } try { fileChoice.setDialogTitle("Select text file"); // Sets directory to text directory specified in preferences fileChoice.setCurrentDirectory(new File(textDirectory)); if (fileChoice.showOpenDialog(Araucaria.this) == JFileChooser.APPROVE_OPTION) { lastDirectory = fileChoice.getCurrentDirectory(); chosenFile = fileChoice.getSelectedFile(); // See if user has typed in the .txt suffix. If not, add it. if (chosenFile.getPath().indexOf(".txt") == -1) { String newPath = chosenFile.getPath() + ".txt"; chosenFile = new File(newPath); } if (!chosenFile.exists()) { m_messageLabel.setText("File does not exist."); return; } chosenInput = new FileInputStream(chosenFile); } else { return; } } catch (Exception e) { } m_wordCount = m_selectText.readText(chosenInput, (int)chosenFile.length()); m_selectText.constructTextLayout(); selectScrollPane.getViewport().setView(m_selectText); m_selectText.repaint(); emptyTree(true); clearUndoStack(); m_messageLabel.setText("Text file " + chosenFile.getName() + " opened successfully"); } public void clearUndoStack() { undoStack = new UndoStack(); EditAction action = new EditAction(this, "starting state"); undoStack.push(action); } /** * If tree is empty or incomplete, return true, else false. */ private boolean treeError() { if (getTree().getRoots().size() == 0) { m_messageLabel.setText("Tree empty - nothing to save."); return true; } else if (getTree().getRoots().size() > 1) { m_messageLabel.setText("Tree has more than one conclusion - please complete the tree."); return true; } return false; } public void cancelSearch() { try { m_statement.close(); m_statement = null; m_dbConnection.close(); m_dbConnection = null; dbAddress = null; JOptionPane.showMessageDialog(this, "Search cancelled", "Search cancelled", JOptionPane.ERROR_MESSAGE); m_messageLabel.setText("Search cancelled."); } catch (Exception ex) { } } int getMaxKey(int table) { String tableTitle = ""; switch (table) { case ARGID: tableTitle = "arguments"; break; } try { String sql = "SELECT MAX(id)\nFROM " + tableTitle; ResultSet resultSet = m_statement.executeQuery(sql); resultSet.next(); int maxKey = resultSet.getInt(1); resultSet.close(); return maxKey; } catch (Exception e) { System.out.println(e.toString()); return -1; } } String dbAddress = null; public Connection openDatabase() throws SQLException { m_dbConnection = null; // Get the dbAddress on the first attempt to connect to the DB. if (dbAddress == null) { if (databaseType == SQLSERVER) { try { m_dbConnection = DriverManager.getConnection( "jdbc:odbc:Driver={SQL Server};Server=" + ipAddress + ";Database=" + databaseName, username,password); if (m_dbConnection != null && m_statement == null) m_statement = m_dbConnection.createStatement(); } catch (Exception ex) { System.out.println ("Cannot connect to SQL Server: " + ex.toString()); } } else if (databaseType == MYSQL) { try { if (m_dbConnection == null) dbAddress = "jdbc:mysql://" + ipAddress + "/" + databaseName + "?user=" + username; m_dbConnection = DriverManager.getConnection(dbAddress); if (m_dbConnection != null && m_statement == null) m_statement = m_dbConnection.createStatement(); } catch (Exception ex2) { JOptionPane.showMessageDialog(Araucaria.this, "
Unable to connect to database.
Please try later.
", "Unable to connect", JOptionPane.ERROR_MESSAGE); m_messageLabel.setText("Unable to connect to database. Please try later."); dbAddress = null; } /* try { URL url = new URL("http://www.computing.dundee.ac.uk/staff/creed/araucaria/redirect.address"); URLConnection urlConnection = url.openConnection(); InputStream input = urlConnection.getInputStream(); byte[] bytes = new byte[100]; input.read(bytes); input.close(); dbAddress = new String(bytes); int endString = dbAddress.indexOf("\n"); dbAddress = dbAddress.substring(0, endString); DriverManager.setLoginTimeout(30); m_dbConnection = DriverManager.getConnection(dbAddress); if (m_dbConnection != null && m_statement == null) m_statement = m_dbConnection.createStatement(); } catch (Exception ex) { try { if (m_dbConnection == null) dbAddress = "jdbc:mysql://134.36.34.192/araucaria_v1_0?user=araucaria_client"; m_dbConnection = DriverManager.getConnection(dbAddress); if (m_dbConnection != null && m_statement == null) m_statement = m_dbConnection.createStatement(); } catch (Exception ex2) { JOptionPane.showMessageDialog(Araucaria.this, "
Unable to connect to database.
Please try later.
", "Unable to connect", JOptionPane.ERROR_MESSAGE); m_messageLabel.setText("Unable to connect to database. Please try later."); dbAddress = null; } } */ } // We've already determined the working address, so just go ahead and use it. } else { try { if (m_dbConnection == null) m_dbConnection = DriverManager.getConnection(dbAddress); if (m_dbConnection != null && m_statement == null) m_statement = m_dbConnection.createStatement(); } catch (Exception ex2) { m_messageLabel.setText("Unable to connect to database. Please try later."); } } return m_dbConnection; } public boolean loginUser() { try { System.out.println ("Login"); Thread messageThread = new Thread(this, "Messages"); messageThread.start(); Thread dbThread = new Thread(this, "OpenDatabase"); dbThread.start(); dbThread.join(10000); if (dbThread.isAlive()) { m_messageLabel.setText("Unable to connect to database. Please try later."); dbThread.interrupt(); dbThread = null; return false; } String userText = "user"; if (databaseType == SQLSERVER) { userText = "[user]"; } String newUser = loginDialog.usernameTextField.getText(); String sql = "SELECT * FROM araucaria_users \nWHERE " + userText + " LIKE " + "'" + BaseRecord.escapeQuotes(newUser) + "'" ; ResultSet resultSet = m_statement.executeQuery(sql); // If resultSet has any entries, username exists while(resultSet.next()) { m_messageLabel.setText("User " + newUser + " logged in."); loggedInUser = newUser; return true; } resultSet.close(); m_statement.close(); m_statement = null; m_dbConnection.close(); } catch (Exception ex) { System.out.println ("loginUser: " + ex.toString()); try { if (m_dbConnection != null) m_dbConnection.close(); } catch (Exception e) { } } return false; } public boolean registerNewUser() { Connection connection = null; try { connection = openDatabase(); if (connection == null) return false; String newUser = registrationDialog.usernameTextField.getText(); String userText = "user"; if (databaseType == SQLSERVER) { userText = "[user]"; } String sql = "SELECT * FROM araucaria_users \nWHERE " + userText + " LIKE " + "'" + BaseRecord.escapeQuotes(newUser) + "'" ; ResultSet resultSet = m_statement.executeQuery(sql); // If resultSet has any entries, username already exists while(resultSet.next()) { return false; } resultSet.close(); String fullName = registrationDialog.fullNameTextField.getText(); String address = registrationDialog.addressTextField.getText(); String email = registrationDialog.emailTextField.getText(); sql = "INSERT INTO araucaria_users (" + userText + ", fullname, address, email) VALUES(" + "'" + BaseRecord.escapeQuotes(newUser) + "'," + "'" + BaseRecord.escapeQuotes(fullName) + "'," + "'" + BaseRecord.escapeQuotes(address) + "'," + "'" + BaseRecord.escapeQuotes(email) + "')"; m_statement.executeUpdate(sql); m_statement.close(); m_statement = null; connection.close(); } catch (Exception ex) { System.out.println ("registerNewUser: " + ex.toString()); ex.printStackTrace(); try { if (connection != null) connection.close(); } catch (Exception e) { } } return true; } void doDBSearch() { Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); // Position the search dialog so that it is centred in the window // but offset slightly from the main Araucaria window searchFrame.setLocation(d.width/2 - searchFrame.getSize().width/2 + 20, d.height/2 - searchFrame.getSize().height/2 + 20); searchFrame.setVisible(true); } void doTextSearchOnDB(String text, String startTag, String endTag, TextSearchTableModel textSearchTableModel, JTable textSearchTable) { System.out.println ("Doing text search"); int matchFound = 0; // Need to turn off combo box events until the combo box items have been added. doComboEvents = false; emptyTree(true); searchResultCombo.removeAllItems(); try { Connection connection = openDatabase(); System.out.println ("Database opened"); if (connection == null || m_statement == null) return; String userText = "user"; if (databaseType == SQLSERVER) { userText = "[user]"; } String sql = "SELECT id, " + userText + ", submitted, aml FROM arguments \nWHERE aml LIKE " + "'%" +startTag + "%" + BaseRecord.escapeQuotes(text) + "%" + endTag + "%' " + "\nORDER BY id"; ResultSet resultSet = m_statement.executeQuery(sql); textSearchTableModel.updateTable(textSearchTable, resultSet); resultSet.close(); resultSet = m_statement.executeQuery(sql); while(resultSet.next()) { int key = resultSet.getInt(1); String rsString = resultSet.getString(4); matchFound++; int textStart = rsString.indexOf(""); int textEnd = rsString.indexOf(""); try { String subText = rsString.substring(textStart + "".length(), textEnd); if (subText.length() > 80) { subText = subText.substring(0, 80); } searchResultCombo.addItem(""+ key + ". " + subText); } catch (StringIndexOutOfBoundsException e) { System.out.println ("Error loading combo box: " + e.toString()); } } resultSet.close(); m_statement.close(); m_statement = null; connection.close(); } catch (SQLException e) { System.out.println(" In doTextSearchOnDB: " + e.toString()); e.printStackTrace(); } catch (Exception e) { System.out.println(" In doTextSearchOnDB: " + e.toString()); e.printStackTrace(); } doComboEvents = true; } /** * Uses the Reed algorithm to search the database for pattern * matches with patternTree. * Returns the number of matches found. */ public int doTreeSearch(Tree patternTree, TextSearchTableModel textSearchTableModel, JTable textSearchTable) { int matchFound = 0; if (patternTree == null || patternTree.getRoots().size() == 0) return 0; // Need to turn off combo box events until the combo box items have been added. doComboEvents = false; emptyTree(true); searchResultCombo.removeAllItems(); try { Connection connection = openDatabase(); if (connection == null || m_statement == null) return 0; String userText = "user"; if (databaseType == SQLSERVER) { userText = "[user]"; } String sql = "SELECT COUNT(id) FROM arguments"; ResultSet resultSet = m_statement.executeQuery(sql); resultSet.next(); int numEntries = resultSet.getInt(1); if (numEntries > 0) { int yesNo = JOptionPane.showConfirmDialog(this, "This search will require downloading " + numEntries + " \nrecords to your computer. This could take some time." + "\nDo you want to continue?", "Number of database records", JOptionPane.YES_NO_OPTION); if (yesNo == 1) { resultSet.close(); m_statement.close(); m_statement = null; connection.close(); return 0; } } sql = "SELECT id, " + userText + ", submitted, aml, amlBytes FROM arguments ORDER BY id"; resultSet = m_statement.executeQuery(sql); LinkedList matchedList = new LinkedList(); while(resultSet.next()) { int key = resultSet.getInt(1); Object keyObj = new Integer(key); Object user = resultSet.getObject(2); Object submitted = resultSet.getObject(3); String rsString = resultSet.getString(4); byte[] retrievedBytes = resultSet.getBytes(5); if(retrievedBytes == null) { continue; } ByteArrayInputStream byteStream = new ByteArrayInputStream(retrievedBytes); InputSource saxInput = new InputSource(byteStream); // Call SAX parser to parse the AML and build the tree Tree targetTree = new Tree(this); try { parseXMLwithSAX(saxInput, targetTree); if (targetTree.matchSubtree(patternTree)) { matchFound++; int textStart = rsString.indexOf(""); int textEnd = rsString.indexOf(""); String text = rsString.substring(textStart + "".length(), textEnd); try { text = text.substring(0, 80); } catch (StringIndexOutOfBoundsException e) {} searchResultCombo.addItem(""+ key + ". " + text); Vector matchedItem = new Vector(); matchedItem.add(keyObj); matchedItem.add(user); matchedItem.add(submitted); matchedItem.add(rsString); matchedList.addLast(matchedItem); } } catch (SAXException ex) { //System.out.println ("Entry " + key + " has syntax error"); } // Clean up and shut down the database connection byteStream.close(); } textSearchTableModel.updateTable(textSearchTable, matchedList); resultSet.close(); m_statement.close(); m_statement = null; connection.close(); } catch (SQLException e) { } catch (Exception e) { System.out.println("doTreeSearch: "); e.printStackTrace(); } doComboEvents = true; return matchFound; } public String easyDateFormat (String format) { java.util.Date today = new java.util.Date(); java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(format); String datenewformat = formatter.format(today); return datenewformat; } public void getSourceComments(boolean loadExisting) { DBSourceComments sourceDialog = new DBSourceComments(this, true, true); if (loadExisting) { sourceDialog.sourceText.setText(source); sourceDialog.commentsText.setText(comments); } sourceDialog.show(); if (!sourceDialog.okPressed) { return; } source = sourceDialog.sourceText.getText(); if (source.length() < 1) { source = ""; } comments = sourceDialog.commentsText.getText(); if (comments.length() < 1) { comments = ""; } } /** * Saves the currently displayed argument to a database. * So far, it will save the AML and JPEG images (both as OLE objects * or long binary values), but needs to be expanded to ask for * username, etc. */ public void saveToDB() { if (loggedInUser == null) { m_messageLabel.setText("You must login to save to the database."); return; } if (treeError()) return; Connection connection = null; try { connection = openDatabase(); if (connection == null || m_statement == null) return; author = loggedInUser; date = easyDateFormat("yyyy-MM-dd"); getSourceComments(true); byte[] xmlBytes = writeXMLAsBytes(); String xmlString = BaseRecord.escapeQuotes(writeXML()); String userText = "user"; if (databaseType == SQLSERVER) { System.out.println ("Using SQL Server"); userText = "[user]"; } // Get the key value to be used for the new record and // create the statement int maxKey = getMaxKey(ARGID); String sql = "INSERT INTO arguments (id, " + userText + ", submitted, source, comments, aml, diagram, amlBytes) VALUES(" + ++maxKey + ", '" + BaseRecord.escapeQuotes(author) + "'" + ", '" + date + "'" + ", '" + BaseRecord.escapeQuotes(source) + "'" + ", '" + BaseRecord.escapeQuotes(comments) + "'" + // ", ?, ? )"; ", '" + xmlString + "', ?, ? )"; PreparedStatement prep = connection.prepareStatement(sql); // Get the AML byte array and connect it to the PreparedStatement prep.setBytes(2, xmlBytes); // Get the JPEG image BufferedImage image = m_canvas.getJpegImage(); if (image == null) { m_messageLabel.setText("Error creating JPEG image."); return; } // Get the JPEG encoder to write its output into a byte[] array ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteOutput); encoder.encode(image); // Create an input stream from the byte array to copy the JPEG // file to the database. byte[] jpegBytesCopy = byteOutput.toByteArray(); ByteArrayInputStream jpegStream = new ByteArrayInputStream(jpegBytesCopy); prep.setBinaryStream(1, jpegStream, jpegBytesCopy.length); // Add the new record prep.executeUpdate(); // Clean up everything and shut down the connection prep.close(); // byteStream.close(); jpegStream.close(); byteOutput.close(); m_statement.close(); m_statement = null; connection.close(); m_messageLabel.setText("AML & JPEG saved to database."); } catch(Exception e) { try { if (connection != null) connection.close(); } catch (Exception ee) {} m_messageLabel.setText("Error saving to database."); e.printStackTrace(); } } private void displayTreeFromCombo() { String comboString = (String)searchResultCombo.getSelectedItem(); int firstPeriod = comboString.indexOf("."); int key = Integer.parseInt(comboString.substring(0, firstPeriod)); m_messageLabel.setText("Reading from database..."); openFromDB(key); } /** * Loads in the AML from a database. */ public void openFromDB(int amlKey) { Connection connection = null; ResultSet rs = null; ByteArrayInputStream byteStream = null; try { emptyTree(true); connection = openDatabase(); if (connection == null || m_statement == null) return; // If the amlKey is negative, select the last entry in the database if (amlKey < 0) { amlKey = getMaxKey(ARGID); } String userText = "user"; if (databaseType == SQLSERVER) { userText = "[user]"; } // We read the amlBytes column rather than aml, since the only way // to retrieve non-ASCII chars seems to be by storing it as a byte array rs = m_statement.executeQuery("SELECT amlBytes, " + userText + ", submitted, source, comments FROM arguments WHERE id = " + amlKey); rs.next(); // Read the AML as a byte string from the record set, then convert to // an input stream, and then to an InputSource, so the SAX parser can // read from it. byte[] retrievedBytes = rs.getBytes(1); // saveToDiskFile("openFromDB before string", retrievedBytes); // String rsString = rs.getString(1); // saveToDiskFile("openFromDB after string", rsString.getBytes()); String user = rs.getString(2); java.sql.Date submitted = rs.getDate(3); source = rs.getString(4); comments = rs.getString(5); // for (int i = 0; i < retrievedBytes.length; i++) // if (retrievedBytes[i] == 13 || retrievedBytes[i] == 10) retrievedBytes[i] = 32; byteStream = new ByteArrayInputStream(retrievedBytes); InputSource saxInput = new InputSource(byteStream); // Call SAX parser to parse the AML and build the tree parseXMLwithSAX(saxInput, m_tree, m_canvas, m_selectText); m_wordCount = SelectText.wordCount(m_selectText.text); // Clean up and shut down the database connection byteStream.close(); rs.close(); m_statement.close(); m_statement = null; connection.close(); java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("d MMM yyyy"); String datenewformat = formatter.format(submitted); m_messageLabel.setText("Read entry " + amlKey + " submitted by " + user + " on " + datenewformat); m_argumentDate = datenewformat; m_argumentAuthor = user; clearUndoStack(); } catch(Exception e) { try { byteStream.close(); rs.close(); m_statement.close(); m_statement = null; if (connection != null) connection.close(); } catch (Exception ee) {} m_messageLabel.setText("Error reading database entry " + amlKey + ": " + e.toString()); e.printStackTrace(); } } public String getUndoAML() { byte[] outBuffer = writeXMLAsBytes(); return new String(outBuffer); } /* public void saveToDiskFile(String dialogTitle, byte[] bytesToSave) { FileOutputStream chosenOutput = null; try { xmlChoice.setDialogTitle(dialogTitle); xmlChoice.setCurrentDirectory(new File(amlDirectory)); if (xmlChoice.showSaveDialog(Araucaria.this) == JFileChooser.APPROVE_OPTION) { lastDirectory = xmlChoice.getCurrentDirectory(); File chosenFile = xmlChoice.getSelectedFile(); // See if user has typed in the .aml suffix. If not, add it. if (chosenFile.getPath().indexOf(".aml") == -1) { String newPath = chosenFile.getPath() + ".aml"; chosenFile = new File(newPath); } if (chosenFile.exists()) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Overwrite existing file?
", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { saveXMLFile(); return; } } try { chosenOutput = new FileOutputStream(chosenFile); if (chosenOutput != null) { chosenOutput.write(bytesToSave, 0, bytesToSave.length); } chosenOutput.flush(); chosenOutput.close(); m_messageLabel.setText("File " + chosenFile.getAbsolutePath() + " saved successfully."); m_argumentSaved = true; } catch (Exception e) { System.out.println(e.toString()); m_messageLabel.setText("Error writing XML file.\n" + e.toString()); } } else { m_messageLabel.setText("Argument not saved."); } } catch (Exception e) { } } */ private boolean doSaveXMLFile() { try { FileOutputStream chosenOutput = null; chosenOutput = new FileOutputStream(currentOpenXMLFile); // String writeString = writeXML(); if (chosenOutput != null) { // byte[] outBuffer = writeString.getBytes(); byte[] outBuffer = writeXMLAsBytes(); chosenOutput.write(outBuffer, 0, outBuffer.length); } chosenOutput.flush(); chosenOutput.close(); m_messageLabel.setText("File " + currentOpenXMLFile.getAbsolutePath() + " saved successfully."); m_argumentSaved = true; return true; } catch (Exception e) { System.out.println(e.toString()); m_messageLabel.setText("Error writing XML file.\n" + e.toString()); return false; } } public void saveXMLFile(boolean doSaveAs) { if (treeError()) return; try { if (doSaveAs) { xmlChoice.setDialogTitle("Save argument"); xmlChoice.setCurrentDirectory(new File(amlDirectory)); if (xmlChoice.showSaveDialog(Araucaria.this) == JFileChooser.APPROVE_OPTION) { lastDirectory = xmlChoice.getCurrentDirectory(); File chosenFile = xmlChoice.getSelectedFile(); // See if user has typed in the .aml suffix. If not, add it. if (chosenFile.getPath().indexOf(".aml") == -1) { String newPath = chosenFile.getPath() + ".aml"; chosenFile = new File(newPath); } if (chosenFile.exists()) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Overwrite existing file?
", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { saveXMLFile(doSaveAs); return; } } currentOpenXMLFile = chosenFile; doSaveXMLFile(); } else { m_messageLabel.setText("Argument not saved."); return; } } else { doSaveXMLFile(); } } catch (Exception e) { } } public void openSchemeset() { FileInputStream inputStream = null; String fileName = ""; try { schemeChoice.setDialogTitle("Read schemeset"); schemeChoice.setCurrentDirectory(new File(schemeDirectory)); if (schemeChoice.showOpenDialog(Araucaria.this) == JFileChooser.APPROVE_OPTION) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Do you want to replace the existing schemeset?
" + "(This will erase any schemes in the current tree.)
", "Replace schemeset?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { m_messageLabel.setText("Schemeset not replaced."); return; } lastDirectory = schemeChoice.getCurrentDirectory(); File chosenFile = schemeChoice.getSelectedFile(); // See if user has typed in the .scm suffix. If not, add it. if (chosenFile.getPath().indexOf(".scm") == -1) { String newPath = chosenFile.getPath() + ".scm"; chosenFile = new File(newPath); } if (!chosenFile.exists()) { m_messageLabel.setText("File does not exist."); return; } inputStream = new FileInputStream(chosenFile); fileName = chosenFile.getAbsolutePath(); } else { m_messageLabel.setText("Schemeset not read."); return; } } catch (Exception e) { // Java Web Start bit } // Parse the schemeset XML try { FileInputStream fileStream = new FileInputStream(fileName); byte[] bytes = new byte[1024]; StringBuffer byteString = new StringBuffer(); do { int count = fileStream.read(bytes); if (count == -1) break; for (int i = 0; i < count; i++) { byte[] b = new byte[1]; if (bytes[i] == 13 || bytes[i] == 10) bytes[i] = 32; b[0] = bytes[i]; byteString.append(new String(b)); } } while (true); ByteArrayInputStream byteStream = new ByteArrayInputStream(byteString.toString().getBytes()); InputSource saxInput = new InputSource(byteStream); parseXMLwithSAX(saxInput, m_tree, m_canvas, m_selectText); /* AraucariaXML xmlCC = new AraucariaXML(inputStream); xmlCC.setGlobals(Araucaria.this, m_selectText, m_tree, m_canvas); xmlCC.Statement(); **/ m_messageLabel.setText("Schemeset " + fileName + " read successfully."); } catch (Exception e) { System.out.println(e.toString()); m_messageLabel.setText("Error reading schemeset."); } catch (Error e) { System.out.println(e.toString()); m_messageLabel.setText("Error reading schemeset."); } searchFrame.updateSchemesetSearchCombo(); } public void saveSchemeset() { if (argInfoFrame == null || argInfoFrame.getArgTypeVector().size() == 0) { m_messageLabel.setText("No schemes in schemeset - nothing to save."); return; } try { schemeChoice.setDialogTitle("Save schemeset"); schemeChoice.setCurrentDirectory(new File(schemeDirectory)); if (schemeChoice.showSaveDialog(Araucaria.this) == JFileChooser.APPROVE_OPTION) { lastDirectory = schemeChoice.getCurrentDirectory(); File chosenFile = schemeChoice.getSelectedFile(); // See if user has typed in the .scm suffix. If not, add it. if (chosenFile.getPath().indexOf(".scm") == -1) { String newPath = chosenFile.getPath() + ".scm"; chosenFile = new File(newPath); } if (chosenFile.exists()) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Overwrite existing file?
", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { saveSchemeset(); return; } } try { FileOutputStream chosenOutput = new FileOutputStream(chosenFile); String outString = writeSchemeset(); byte[] outBuffer = outString.getBytes(); chosenOutput.write(outBuffer, 0, outBuffer.length); chosenOutput.flush(); chosenOutput.close(); m_messageLabel.setText("Schemeset " + chosenFile.getAbsolutePath() + " saved successfully."); } catch (Exception e) { System.out.println(e.toString()); m_messageLabel.setText("Error writing schemeset.\n" + e.toString()); } } else { m_messageLabel.setText("Schemeset not saved."); } } catch (Exception e) { // Java web start /* try { FileSaveService fileSaveService = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService"); String outString = writeXMLHeader() + writeSchemeset() + "
"; byte[] testBuffer = outString.getBytes(); ByteArrayInputStream testStream = new ByteArrayInputStream(testBuffer); FileContents fileContents = fileSaveService.saveFileDialog(null, null, testStream, null); if (fileContents == null) { System.out.println("save file is null."); return; } System.out.println(fileContents.getName()); } catch (Exception webExcept) { System.out.println(webExcept.toString() + "\nSave schemeset: problem with web start"); } **/ } } void exitApplication() { // If the tree has been modified and isn't empty, ask if you want to save it. if (!m_argumentSaved && m_tree.getRoots().size() > 0) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
Save argument before exiting?
", "Save argument?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 0) { saveXMLFile(currentOpenXMLFile == null); return; } } this.setVisible(false); // hide the Frame System.exit(0); // close the application } public Set getOwnerList() { return ownerList; } public void setOwnerList(Vector rows) { ownerList.addAll(rows); } public Vector ownerExists(String name, int column) { Iterator ownerIter = ownerList.iterator(); while (ownerIter.hasNext()) { Vector row = (Vector)ownerIter.next(); String rowName = (String)row.elementAt(column); if (rowName.equals(name)) return row; } return null; } public String getTla(String name) { String tla = null; // If name is 2 chars or less, set TLA to name. // If this TLA already exists, give up and return null. if (name.length() < 3) { if (ownerExists(name, 1) != null) { return null; } else { tla = new String(name); return tla; } } // If we get this far, name has >= 3 characters. int nameLength = name.length(); byte[] nameBytes = name.getBytes(); byte[] tlaBytes = new byte[3]; for (int i = 0; i < nameLength - 2; i++) { tlaBytes[0] = nameBytes[i]; for (int j = i+1; j < nameLength - 1; j++) { tlaBytes[1] = nameBytes[j]; for (int k = j+1; k < nameLength; k++) { tlaBytes[2] = nameBytes[k]; tla = new String(tlaBytes); if (ownerExists(tla, 1) == null) { return tla; } } } } // If we get this far, all acronyms that can be constructed // from characters in nameBytes have been tried and rejected. // We now try to find an acronym where the first 2 letters match // the first 2 letters in nameBytes and the last letter is another // character tlaBytes[0] = nameBytes[0]; tlaBytes[1] = nameBytes[1]; for (byte b = 48; b <= 121; b++) { tlaBytes[2] = b; tla = new String(tlaBytes); if (ownerExists(tla, 1) == null) { return tla; } } return null; } public String addToOwnerList(Vector row) { String name = (String)row.elementAt(0); if (ownerExists(name, 0) != null) return null; String tla = getTla(name); if (tla == null) return null; row.setElementAt(tla, 1); ownerList.add(row); return tla; } public void printOwnerList() { Iterator owners = ownerList.iterator(); while(owners.hasNext()) { Vector row = (Vector)owners.next(); System.out.println ("Owner: " + row + ":" + row.elementAt(0) + ", " + row.elementAt(1)); } System.out.println ("********************"); } public void deleteOwners(Vector remList) { for (int i = 0; i < remList.size(); i++) { ownerList.remove(remList.elementAt(i)); } } public boolean supportLabelExists(String name) { Iterator iter = supportLabelList.iterator(); while (iter.hasNext()) { String label = (String)iter.next(); if (label.equals(name)) return true; } return false; } /** * Adds 'name' to the support label list after checking * for duplication */ public boolean addToSupportLabelList(String name) { if (name == null) return false; if (supportLabelExists(name)) return false; supportLabelList.add(name); return true; } /** * Scans all vertices in the tree and builds a set of vertex * and edge labels, without duplication */ public void buildSupportLabelList() { supportLabelList = new HashSet(); if (m_treeTraversal == null) { return; } Enumeration nodeList = m_treeTraversal.elements(); while (nodeList.hasMoreElements()) { TreeVertex vertex = (TreeVertex)nodeList.nextElement(); addToSupportLabelList(vertex.m_nodeLabel); addToSupportLabelList(vertex.m_supportLabel); } } public void setEncoding(String encod) { Araucaria.encoding = encod; if (encod.equals("UTF-8")) { encodingUTF8Menu.setSelected(true); } else if (encod.equals("BIG5")) { encodingBIG5Menu.setSelected(true); } SelectText.setFont(); } public void doRedo() { if (undoStack.undoPointer == undoStack.size() - 1) { return; } EditAction action = (EditAction)undoStack.elementAt(++undoStack.undoPointer); action.restore(false, action.description); } public void doUndo() { // If we've undone everything, return if (undoStack.undoPointer <= 0) { return; } EditAction undoingAction = (EditAction)undoStack.elementAt(undoStack.undoPointer); EditAction action = (EditAction)undoStack.elementAt(--undoStack.undoPointer); // System.out.println ("Undo: restoring to action " + undoStack.undoPointer + " \n" + action.amlString); action.restore(true, undoingAction.description); } public void showAboutDialog() { JFrame frame = new JFrame(); createIcon(frame); AboutDialog about = new AboutDialog(this); } public void showLabelsDialog() { if (this.getTreeCanvas().getSelectedEdges().size() + this.getTreeCanvas().getSelectedVertices().size() == 0) { JOptionPane.showMessageDialog(this, "
Please select some nodes or supports first." + "
", "Nothing selected", JOptionPane.ERROR_MESSAGE); return; } showLabelsMenu.setSelected(true); // showLabelsAction.putValue(Action.SMALL_ICON, new ImageIcon("images/LabelOff.gif")); showLabelsAction.putValue(Action.SHORT_DESCRIPTION, "Hide evaluations"); showLabelsMenu.setText("Hide evaluations"); buildSupportLabelList(); LabelDialog labelDialog = new LabelDialog(this); labelDialog.show(); m_canvas.showSupportLabels(true); if (m_tree.getRoots().size() > 0) m_canvas.redrawTree(); } public void showOwnerDialog() { OwnerDialog ownerDialog = new OwnerDialog(this); ownerDialog.show(); showOwnersMenu.setSelected(true); // showOwnersAction.putValue(Action.SMALL_ICON, new ImageIcon("images/DeleteUser.gif")); showOwnersAction.putValue(Action.SHORT_DESCRIPTION, "Hide owners"); showOwnersMenu.setText("Hide owners"); m_canvas.showOwners(true); // Redrawing an empty tree deletes the owners list if (m_tree.getRoots().size() > 0) m_canvas.redrawTree(); } class WindowHandler extends WindowAdapter { public void windowClosing(WindowEvent event) { exitApplication(); } } class FileActionHandler extends AbstractAction //implements ActionListener { FileActionHandler() { } FileActionHandler(String name, Icon icon) { super(name, icon); } FileActionHandler(String name) { super(name); } public void actionPerformed(ActionEvent event) { String sourceCode = ""; if (event.getSource() == openFileMenu || event.getSource() == m_openTextToolBar) { openTextFile(); } else if (event.getSource() == closeFileMenu) { closeAll(); } else if (event.getSource() == saveXMLFileMenu || event.getSource() == m_saveArgToolBar) { saveXMLFile(currentOpenXMLFile == null); } else if (event.getSource() == saveAsXMLFileMenu) { saveXMLFile(true); } else if (event.getSource() == encodingUTF8Menu) { Araucaria.encoding = "UTF8"; SelectText.setFont(); } else if (event.getSource() == encodingBIG5Menu) { Araucaria.encoding = "BIG5"; SelectText.setFont(); } else if (event.getSource() == readXMLFileMenu || event.getSource() == m_openArgToolBar) { readXML(); } else if (event.getSource() == saveToDBMenu || event.getSource() == m_saveToDBToolBar) { saveToDB(); } else if (event.getSource() == m_searchDBToolBar || event.getSource() == searchMenu) { if (m_tree.getRoots().size() > 0) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
This command will erase the current tree.
" + "Do you want to continue?
", "Search database", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { m_messageLabel.setText("Database search cancelled."); return; } } m_messageLabel.setText("Searching database..."); doDBSearch(); } else if (event.getSource() == setSourceComments) { getSourceComments(true); } else if (event.getSource() == viewSourceComments) { DBSourceComments showSource = new DBSourceComments(Araucaria.this, true, false); showSource.sourceText.setText(source); showSource.commentsText.setText(comments); showSource.show(); } else if (event.getSource() == saveJpegFileMenu || event.getSource() == saveJpegToolBar) { m_canvas.saveJpegFile(); } else if (event.getSource() == propertiesMenu) { propertiesDialog = new PropertiesDialog(Araucaria.this); propertiesDialog.show(); if(propertiesDialog.okPressed) { author = propertiesDialog.author.getText(); source = propertiesDialog.sourceText.getText(); comments = propertiesDialog.commentsText.getText(); } } else if (event.getSource() == showPreferencesMenu) { preferencesDialog.show(); } else if (event.getSource() == exitFileMenu) { exitApplication(); } else if (event.getSource() == newGraphMenu || event.getSource() == m_clearDiagramToolBar) { int action = JOptionPane.showConfirmDialog(Araucaria.this, "
This command will erase the current tree.
" + "Do you want to continue?
", "New argument tree?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null); if (action == 1) { m_messageLabel.setText("Tree not erased."); return; } emptyTree(true); clearUndoStack(); } else if (event.getSource() == linkGraphMenu || event.getSource() == m_linkStatementsToolBar) { boolean success = m_canvas.linkVertices(); if (success) { m_canvas.redrawTree(); undoStack.push(new EditAction(Araucaria.this, "linking premises")); m_argumentSaved = false; } } else if (event.getSource() == unlinkGraphMenu || event.getSource() == m_unlinkStatementsToolBar) { boolean success = m_canvas.unlinkVertices(); if (success) { m_canvas.redrawTree(); m_canvas.calcSubtreeShapes(); undoStack.push(new EditAction(Araucaria.this, "unlinking premises")); m_argumentSaved = false; } } else if (event.getSource() == refutationGraphMenu || event.getSource() == m_refutationToolBar) { boolean success = m_canvas.setRefutations(); if (success) { m_canvas.redrawTree(); m_canvas.calcSubtreeShapes(); undoStack.push(new EditAction(Araucaria.this, "toggling refutation")); } } else if (event.getSource() == selectAllMenu) { m_canvas.selectAllNodes(); m_canvas.redrawTree(); m_canvas.calcSubtreeShapes(); } else if (event.getSource() == fullTextTreeMenu) { if (getTree() == null || getTree().getRoots().size() <= 0) { m_messageLabel.setText("No argument available to show."); return; } if (getTree().getRoots().size() > 1) { m_messageLabel.setText("Full text diagram is only available for complete arguments."); return; } m_messageLabel.setText(" "); FullTextDialog fullTextDialog = new FullTextDialog(Araucaria.this); fullTextDialog.show(); fullTextDialog.dispose(); System.gc(); } else if (event.getSource() == ownersMenu || event.getSource() == m_ownersToolBar) { showOwnerDialog(); } else if (event.getSource() == labelsMenu || event.getSource() == m_labelsToolBar) { showLabelsDialog(); } else if (event.getSource() == showLabelsMenu || event.getSource() == m_showLabelsToolBar) { m_canvas.showSupportLabels(); m_canvas.redrawTree(); if (!showLabelsMenu.isSelected()) { // m_showLabelsToolBar.setSelected(true); showLabelsMenu.setSelected(true); // showLabelsAction.putValue(Action.SMALL_ICON, new ImageIcon("images/LabelOff.gif")); showLabelsAction.putValue(Action.SHORT_DESCRIPTION, "Hide evaluations"); showLabelsMenu.setText("Hide evaluations"); } else { // m_showLabelsToolBar.setSelected(false); showLabelsMenu.setSelected(false); // showLabelsAction.putValue(Action.SMALL_ICON, new ImageIcon("images/LabelOn.gif")); showLabelsAction.putValue(Action.SHORT_DESCRIPTION, "Show evaluations"); showLabelsMenu.setText("Show evaluations"); } } else if (event.getSource() == showOwnersMenu || event.getSource() == m_showOwnersToolBar) { m_canvas.showOwners(); m_canvas.redrawTree(); if (!showOwnersMenu.isSelected()) { // m_showOwnersToolBar.setSelected(true); showOwnersMenu.setSelected(true); // showOwnersAction.putValue(Action.SMALL_ICON, new ImageIcon("images/DeleteUser.gif")); showOwnersAction.putValue(Action.SHORT_DESCRIPTION, "Hide owners"); showOwnersMenu.setText("Hide owners"); } else { // m_showOwnersToolBar.setSelected(false); showOwnersMenu.setSelected(false); // showOwnersAction.putValue(Action.SMALL_ICON, new ImageIcon("images/Users.gif")); showOwnersAction.putValue(Action.SHORT_DESCRIPTION, "Show owners"); showOwnersMenu.setText("Show owners"); } } else if (event.getSource() == selectSchemeMenu || event.getSource() == m_selectSchemeToolBar) { m_canvas.addSubtree(null); m_canvas.redrawTree(); m_argumentSaved = false; } else if (event.getSource() == invertGraphMenu || event.getSource() == m_invertDiagramToolBar) { setInvertedTree(!getInvertedTree()); m_canvas.redrawTree(); m_canvas.calcSubtreeShapes(); } else if (event.getSource() == deleteGraphMenu || event.getSource() == m_deleteToolBar) { if (m_canvas.deleteSelectedItems()) { setArgumentSaved(false); } else { m_messageLabel.setText("Nothing selected for deletion."); } m_canvas.redrawTree(); } else if (event.getSource() == redoMenu || event.getSource() == m_redoToolBar) { m_messageLabel.setText(" "); doRedo(); } else if (event.getSource() == undoMenu || event.getSource() == m_undoToolBar) { m_messageLabel.setText(" "); doUndo(); } else if (event.getSource() == missingPremiseMenu || event.getSource() == m_missingPremiseToolBar) { String missingPremise = JOptionPane.showInputDialog(Araucaria.this, "Enter text for missing premise. ", "Missing premise", JOptionPane.QUESTION_MESSAGE); if (missingPremise != null) { // missingPremise = SelectText.stripWhiteSpace(missingPremise); // missingPremise = SelectText.stripWeirdChars(missingPremise); addFreeVertex(missingPremise, null, -1); m_canvas.redrawTree(); undoStack.push(new EditAction(Araucaria.this, "adding missing premise")); } } else if (event.getSource() == argTypeSchemeMenu || event.getSource() == m_addEditSchemeToolBar) { argInfoFrame.show(); } else if (event.getSource() == saveSchemeMenu) { saveSchemeset(); } else if (event.getSource() == openSchemeMenu) { openSchemeset(); } else if (event.getSource() == loginLoginMenu) { loginDialog.show(); } else if (event.getSource() == registerLoginMenu) { registrationDialog.show(); } else if (event.getSource() == aboutHelpMenu) { showAboutDialog(); } else if (event.getSource() == showHelpMenu || event.getSource() == m_helpToolBar) { helpDialog = new HelpHTMLDialog(Araucaria.this); helpDialog.show(); } else if (event.getSource() == searchResultCombo && doComboEvents) { displayTreeFromCombo(); } } } }