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();
}
}
}
}