Example usage for org.dom4j.io OutputFormat setLineSeparator

List of usage examples for org.dom4j.io OutputFormat setLineSeparator

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat setLineSeparator.

Prototype

public void setLineSeparator(String separator) 

Source Link

Document

This will set the new-line separator.

Usage

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Starts a saving procedure calling the method's own saveResults function.
 * Run-specific data will be added to the end of the file.
 * /* w w  w.jav a2s .  c  o m*/
 * @param fileName
 *            Name of the saved file without the extension. (E.g.
 *            solution_generation_13)
 * @param method
 *            The corresponding method instance to be called for saving.
 */
public static File saveResult(String fileName, final Element representationRootElement, long startSeed,
        long currentActiveSeed) {
    // create new document for output
    Document doc = DocumentHelper.createDocument();
    doc.addDocType("frevo", null, System.getProperty("user.dir") + "//Components//ISave.dtd");
    Element dfrevo = doc.addElement("frevo");

    String fileLocation = "Undefined";

    // export sessionconfig
    Element sessionconfig = dfrevo.addElement("sessionconfig");

    // custom name
    Element configentry = sessionconfig.addElement("configentry");
    configentry.addAttribute("key", "CustomName");
    configentry.addAttribute("type", "STRING");
    configentry.addAttribute("value", customName);

    // number of runs
    Element runentry = sessionconfig.addElement("configentry");
    runentry.addAttribute("key", "NumberofRuns");
    runentry.addAttribute("type", "INT");
    runentry.addAttribute("value", Integer.toString(getNumberOfSimulationRuns()));

    // starting seed
    Element seedentry = sessionconfig.addElement("configentry");
    seedentry.addAttribute("key", "StartingSeed");
    seedentry.addAttribute("type", "LONG");
    // seedentry.addAttribute("value", Long.toString(getSeed()));
    seedentry.addAttribute("value", Long.toString(startSeed));

    // active seed
    Element aseedentry = sessionconfig.addElement("configentry");
    aseedentry.addAttribute("key", "CurrentSeed");
    aseedentry.addAttribute("type", "LONG");
    aseedentry.addAttribute("value", Long.toString(currentActiveSeed));

    try {
        // export problem
        Element problemsettings = dfrevo.addElement("problem");
        ComponentXMLData problem = FrevoMain.SELECTED_PROBLEM;
        problemsettings.addAttribute("class", problem.getClassName());
        Vector<String> keys = new Vector<String>(problem.getProperties().keySet());
        for (String k : keys) {
            Element entry = problemsettings.addElement("problementry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", problem.getTypeOfProperty(k).toString());
            entry.addAttribute("value", problem.getValueOfProperty(k));
        }

        // export method
        Element methodsettings = dfrevo.addElement("method");
        ComponentXMLData method = FrevoMain.SELECTED_METHOD;
        methodsettings.addAttribute("class", method.getClassName());
        keys = new Vector<String>(method.getProperties().keySet());
        for (String k : keys) {
            Element entry = methodsettings.addElement("methodentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", method.getTypeOfProperty(k).toString());
            entry.addAttribute("value", method.getValueOfProperty(k));
        }

        // export ranking
        Element rankingsettings = dfrevo.addElement("ranking");
        ComponentXMLData ranking = FrevoMain.SELECTED_RANKING;
        rankingsettings.addAttribute("class", ranking.getClassName());
        keys = new Vector<String>(ranking.getProperties().keySet());
        for (String k : keys) {
            Element entry = rankingsettings.addElement("rankingentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", ranking.getTypeOfProperty(k).toString());
            entry.addAttribute("value", ranking.getValueOfProperty(k));
        }

        // export representation
        Element repsettings = dfrevo.addElement("representation");
        ComponentXMLData representation = FrevoMain.SELECTED_REPRESENTATION;
        repsettings.addAttribute("class", representation.getClassName());
        keys = new Vector<String>(representation.getProperties().keySet());
        for (String k : keys) {
            Element entry = repsettings.addElement("representationentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", representation.getTypeOfProperty(k).toString());
            entry.addAttribute("value", representation.getValueOfProperty(k));
        }

        // call method's own save solution
        dfrevo.add(representationRootElement);

        // save contents to file

        String location = FREVO_INSTALL_DIRECTORY + File.separator + "Results" + File.separator + customName;
        File rootSaveDir = new File(location);

        // remove spaces from filename
        fileName.replaceAll(" ", "_");

        // create save directory based on given custom name
        rootSaveDir.mkdirs();

        // create sub-directories for different seeds
        if (FrevoMain.getNumberOfSimulationRuns() > 1) {
            // create seed directory if there are more than one run
            File seedDir = new File(location + File.separator + "seed_" + startSeed);
            seedDir.mkdir();
            fileLocation = seedDir + File.separator + fileName + ".zre";
        } else {
            // save it the root location
            fileLocation = rootSaveDir + File.separator + fileName + ".zre";
        }

        File saveFile = new File(fileLocation);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        saveFile.createNewFile();
        FileWriter out = new FileWriter(saveFile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
        System.out.println("XML Writing Completed: " + fileLocation);

        if (isFrevoWithGraphics()) {
            mainWindow.addRecentResult(saveFile);
        }
        return saveFile;
    } catch (OutOfMemoryError mem) {
        System.err.println("Could not export! (Out of memory)");
    } catch (IOException e) {
        System.err.println("IOException while writing to XML! Check path at: " + fileLocation);
        e.printStackTrace();
    }
    return null;
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Saves FREVO settings to the configuration file. Initiates file writing to
 * store data./*from   ww w.jav a  2  s . co  m*/
 */
public static void saveSettings() {
    Document doc;
    File configfile = new File(FREVO_INSTALL_DIRECTORY + "/frevo_config.xml");
    if (configfile.exists()) {
        // load data if it already exists
        doc = SafeSAX.read(configfile, true);

        Node windowsizes = doc.selectSingleNode("/frevo/window-sizes");

        List<?> items = windowsizes.selectNodes(".//window");
        Iterator<?> it = items.iterator();

        while (it.hasNext()) {
            Element el = (Element) it.next();
            String name = el.valueOf("./@name");

            // save main data
            if (name.equals("main")) {
                el.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));
            }
            // save component browser data
            if (name.equals("componentbrowser")) {
                el.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
                el.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
                el.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
            }
        }
    } else {
        try {
            configfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // file does not exist
        doc = DocumentHelper.createDocument();
        doc.addDocType("frevo", null, "config.dtd");
        Element dfrevo = doc.addElement("frevo");

        dfrevo.addElement("tags");

        Element windowsizes = dfrevo.addElement("window-sizes");
        Element mainwindow = windowsizes.addElement("window");
        mainwindow.addAttribute("name", "main");
        mainwindow.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
        mainwindow.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));

        Element compwindow = windowsizes.addElement("window");
        compwindow.addAttribute("name", "componentbrowser");
        compwindow.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
        compwindow.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
        compwindow.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
        compwindow.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
    }

    // write to file
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        configfile.createNewFile();
        FileWriter out = new FileWriter(configfile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Imports a component packaged in the FREVO package format (zcp). Copied
 * files will still persist even if operation fails or the component is bad.
 * /*from   w  w w  .  j  a  va2 s . co m*/
 * @param importfile
 *            The ZCP file to be imported.
 */
public static void importComponent(File importfile) {
    // unzip to the given location
    String outputdir = null;
    URI frevo_install_base = new File(FrevoMain.getInstallDirectory()).toURI();
    try {
        ZipFile zfile = new ZipFile(importfile);
        File directory = new File(FREVO_INSTALL_DIRECTORY + File.separator + "Components");

        Enumeration<? extends ZipEntry> entries = zfile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File file = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                file.getParentFile().mkdirs();
                InputStream in = zfile.getInputStream(entry);
                try {
                    copy(in, file);
                    // copy data from root XML
                    String extension = FrevoMain.getExtension(file);
                    if (extension.equals("xml")) {
                        URI fileURI = frevo_install_base.relativize(file.toURI());
                        String uristring = fileURI.toString();
                        String opath = uristring.substring(0, uristring.length() - extension.length() - 1);
                        if ((outputdir == null) || (opath.length() < outputdir.length())) {
                            outputdir = opath;
                        }
                    }
                } finally {
                    in.close();
                }
            }
        }
        zfile.close();
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // component successfully installed, add to Eclipse classpath
    File classpath = new File(FREVO_INSTALL_DIRECTORY + File.separator + ".classpath");
    if (classpath.exists()) {
        System.out.println("Adjusting Eclipse classpath...");
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();

        Element componentElement = root.addElement("classpathentry");
        componentElement.addAttribute("kind", "src");
        componentElement.addAttribute("output", outputdir);
        componentElement.addAttribute("path", outputdir);

        // save file
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }
    }

}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Removes the component from the installed components. This function also
 * removes all files within the component's directory. Forces FREVO to
 * reload all components afterwards.// w w  w. j a v  a 2s. co m
 * 
 * @param cdata
 *            The component to be removed
 */
public static void deleteComponent(ComponentXMLData cdata) {

    // remove base XML
    File baseXML = cdata.getSourceXMLFile();
    baseXML.delete();

    // erase all files within component directory
    // get class root directory
    String classDir = cdata.getClassDir();

    // extract directory name
    // construct copy
    int i = 0;
    while (i < classDir.length()) {
        char c = classDir.charAt(i);
        if ((c == '/') || (c == '\\')) {
            i++;
        } else {
            break;
        }
    }

    int end = i + 1;
    while (end < classDir.length()) {
        char c = classDir.charAt(end);
        if ((c == '/') || (c == '\\')) {
            break;
        } else {
            end++;
        }
    }

    classDir = classDir.substring(i, end);

    String comprootdirname = classDir.split("/")[0];

    // get component root directory
    String comprootdir = FrevoMain.getComponentDirectory(cdata.getComponentType()) + comprootdirname;

    File rootdir = new File(comprootdir);

    eraseDirectory(rootdir);

    // Remove entry from classpath
    File classpath = new File(FrevoMain.getInstallDirectory() + File.separator + ".classpath");
    if (classpath.exists()) {
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();
        String output; // the string to match the "output" field in
        // classpath xml

        // correct pathname for multiproblems
        if (cdata.getComponentType() == ComponentType.FREVO_MULTIPROBLEM)
            output = "Components/" + "Problems/" + comprootdirname;
        else if (cdata.getComponentType() == ComponentType.FREVO_BULKREPRESENTATION)
            output = "Components/" + "Representations/" + comprootdirname;
        else
            output = "Components/" + FrevoMain.getComponentTypeAsString(cdata.getComponentType()) + "s/"
                    + comprootdirname;
        // System.out.println("removing "+output);
        Node node = root.selectSingleNode("classpathentry[@output='" + output + "']");
        if (node != null)
            node.detach();

        // save XML
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }

    }

    // force reloading components
    FrevoMain.reLoadComponents(true);
}

From source file:net.bpfurtado.ljcolligo.util.Util.java

License:Open Source License

public static void save(Element root, File file) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndentSize(4);/*from   www .  j av a  2  s  . c o m*/
    format.setEncoding("UTF-8");
    format.setNewlines(true);
    format.setLineSeparator(System.getProperty("line.separator"));
    XMLWriter writer;
    try {
        writer = new XMLWriter(new FileWriter(file), format);
        writer.startDocument();
        writer.write(root);
        writer.close();
        logger.debug("All entries saved to file [" + file.getAbsolutePath() + "]");
    } catch (Exception e) {
        throw new LJColligoException("File [" + file.getAbsolutePath() + "]", e);
    }
}

From source file:net.bpfurtado.tas.model.persistence.XMLAdventureWriter.java

License:Open Source License

private File save(Document doc) {
    try {/*  w w  w  . j  av  a  2 s.  c  o  m*/
        if (!saveFile.getName().endsWith(".adv.xml")) {
            saveFile = new File(saveFile.getAbsolutePath() + ".adv.xml");
        }

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        format.setNewlines(true);
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLWriter writer = new XMLWriter(new FileWriter(saveFile), format);

        writer.write(doc);
        writer.close();

        return saveFile;
    } catch (Exception e) {
        throw new AdventureException("Error writing adventure", e);
    }
}

From source file:net.bpfurtado.tas.runner.savegame.SaveGamePersister.java

License:Open Source License

public static void write(Document xml, File saveGameFile, SaveGameListener saveGameListener) {
    try {//from ww w . j  a  v a2 s. c om
        saveGameListener.log("Saving game to file: [" + saveGameFile + "]...");

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        format.setNewlines(true);
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLWriter writer = new XMLWriter(new FileWriter(saveGameFile), format);

        writer.write(xml);
        writer.flush();
        writer.close();

        saveGameListener.log("Game saved!");
    } catch (Exception e) {
        throw new AdventureException("Error writing Save Game", e);
    }
}

From source file:org.ecocean.servlet.ScanResultsServlet.java

License:Open Source License

public boolean writeXML(HttpServletRequest request, Vector results, String num, String newEncDate,
        String newEncShark, String newEncSize) {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    try {//from   w w w .j ava  2s  . c  o  m
        System.out.println("Prepping to write XML file for encounter " + num);

        //now setup the XML write for the encounter
        int resultsSize = results.size();
        MatchObject[] matches = new MatchObject[resultsSize];
        for (int a = 0; a < resultsSize; a++) {
            matches[a] = (MatchObject) results.get(a);
        }
        Arrays.sort(matches, new MatchComparator());
        StringBuffer resultsXML = new StringBuffer();
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("matchSet");
        root.addAttribute("scanDate", (new java.util.Date()).toString());
        root.addAttribute("R", request.getParameter("R"));
        root.addAttribute("epsilon", request.getParameter("epsilon"));
        root.addAttribute("Sizelim", request.getParameter("Sizelim"));
        root.addAttribute("maxTriangleRotation", request.getParameter("maxTriangleRotation"));
        root.addAttribute("C", request.getParameter("C"));
        for (int i = 0; i < matches.length; i++) {
            MatchObject mo = matches[i];
            Element match = root.addElement("match");
            match.addAttribute("points", (new Double(mo.matchValue)).toString());
            match.addAttribute("adjustedpoints", (new Double(mo.adjustedMatchValue)).toString());
            match.addAttribute("pointBreakdown", mo.pointBreakdown);
            String finalscore = (new Double(mo.matchValue * mo.adjustedMatchValue)).toString();
            if (finalscore.length() > 7) {
                finalscore = finalscore.substring(0, 6);
            }
            match.addAttribute("finalscore", finalscore);

            //check if logM is very small...
            try {
                match.addAttribute("logMStdDev", (new Double(mo.getLogMStdDev())).toString());
            } catch (java.lang.NumberFormatException nfe) {
                match.addAttribute("logMStdDev", "<0.01");
            }

            match.addAttribute("evaluation", mo.getEvaluation());

            Element enc = match.addElement("encounter");
            enc.addAttribute("number", mo.encounterNumber);
            enc.addAttribute("date", mo.date);
            enc.addAttribute("sex", mo.catalogSex);
            enc.addAttribute("assignedToShark", mo.getIndividualName());
            enc.addAttribute("size", ((new Double(mo.size)).toString() + " meters"));
            for (int k = 0; k < mo.scores.size(); k++) {
                Element spot = enc.addElement("spot");
                spot.addAttribute("x", (new Double(((VertexPointMatch) mo.scores.get(k)).oldX)).toString());
                spot.addAttribute("y", (new Double(((VertexPointMatch) mo.scores.get(k)).oldY)).toString());
            }
            Element enc2 = match.addElement("encounter");
            enc2.addAttribute("number", num);
            enc2.addAttribute("date", newEncDate);
            enc2.addAttribute("sex", mo.newSex);
            enc2.addAttribute("assignedToShark", newEncShark);
            enc2.addAttribute("size", (newEncSize + " meters"));
            for (int j = 0; j < mo.scores.size(); j++) {
                Element spot = enc2.addElement("spot");
                spot.addAttribute("x", (new Double(((VertexPointMatch) mo.scores.get(j)).newX)).toString());
                spot.addAttribute("y", (new Double(((VertexPointMatch) mo.scores.get(j)).newY)).toString());
            }

        }

        //prep for writing out the XML

        //setup data dir
        String rootWebappPath = getServletContext().getRealPath("/");
        File webappsDir = new File(rootWebappPath).getParentFile();
        File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
        //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();}
        //File encountersDir=new File(shepherdDataDir.getAbsolutePath()+"/encounters");
        //if(!encountersDir.exists()){encountersDir.mkdirs();}

        //in case this is a right-side scan, change file name to save to
        String fileAddition = "";
        if ((request.getParameter("rightSide") != null) && (request.getParameter("rightSide").equals("true"))) {
            fileAddition = "Right";
        }
        //File file=new File((new File(".")).getCanonicalPath()+File.separator+"webapps"+File.separator+"ROOT"+File.separator+"encounters"+File.separator+num+File.separator+"lastFull"+fileAddition+"Scan.xml");
        //File file = new File(encountersDir.getAbsoluteFile()+"/"+ num + "/lastFull" + fileAddition + "Scan.xml");
        File file = new File(Encounter.dir(shepherdDataDir, num) + "/lastFull" + fileAddition + "Scan.xml");

        FileWriter mywriter = new FileWriter(file);
        org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));
        org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(mywriter, format);
        writer.write(document);
        writer.close();
        System.out.println("Successful write.");
        return true;
    } catch (Exception e) {
        System.out.println("Encountered an error trying to write back XML results!");
        e.printStackTrace();
        return false;
    }
}

From source file:org.ecocean.servlet.ServletUtilities.java

License:Open Source License

public static synchronized void addRSSEntry(String title, String link, String description, File rssFile) {
    //File rssFile=new File("nofile.xml");

    try {/*w  w w  .ja  v a 2  s  .  c  om*/
        System.out.println("Looking for RSS file: " + rssFile.getCanonicalPath());
        if (rssFile.exists()) {

            SAXReader reader = new SAXReader();
            Document document = reader.read(rssFile);
            Element root = document.getRootElement();
            Element channel = root.element("channel");
            List items = channel.elements("item");
            int numItems = items.size();
            items = null;
            if (numItems > 9) {
                Element removeThisItem = channel.element("item");
                channel.remove(removeThisItem);
            }

            Element newItem = channel.addElement("item");
            Element newTitle = newItem.addElement("title");
            Element newLink = newItem.addElement("link");
            Element newDescription = newItem.addElement("description");
            newTitle.setText(title);
            newDescription.setText(description);
            newLink.setText(link);

            Element pubDate = channel.element("pubDate");
            pubDate.setText((new java.util.Date()).toString());

            //now save changes
            FileWriter mywriter = new FileWriter(rssFile);
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            XMLWriter writer = new XMLWriter(mywriter, format);
            writer.write(document);
            writer.close();

        }
    } catch (IOException ioe) {
        System.out.println("ERROR: Could not find the RSS file.");
        ioe.printStackTrace();
    } catch (DocumentException de) {
        System.out.println("ERROR: Could not read the RSS file.");
        de.printStackTrace();
    } catch (Exception e) {
        System.out.println("Unknown exception trying to add an entry to the RSS file.");
        e.printStackTrace();
    }
}

From source file:org.ecocean.servlet.WriteOutScanTask.java

License:Open Source License

public boolean writeResult(MatchObject[] swirs, String num, String R, String epsilon, String Sizelim,
        String maxTriangleRotation, String C, String newEncDate, String newEncShark, String newEncSize,
        boolean rightSide, double cutoff, Shepherd myShepherd, String context) {

    try {/*from   w  w w.  j a  v  a 2  s  .  c o m*/
        //System.out.println("Prepping to write XML file for encounter "+num);

        //now setup the XML write for the encounter
        int resultsSize = swirs.length;
        MatchObject[] matches = swirs;

        Arrays.sort(matches, new MatchComparator());
        StringBuffer resultsXML = new StringBuffer();
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("matchSet");
        root.addAttribute("scanDate", (new java.util.Date()).toString());
        root.addAttribute("R", R);
        root.addAttribute("epsilon", epsilon);
        root.addAttribute("Sizelim", Sizelim);
        root.addAttribute("maxTriangleRotation", maxTriangleRotation);
        root.addAttribute("C", C);
        int numMatches = matches.length;

        //hard limit this to 100 matches...no human really goes beyond this...
        if (numMatches > 100)
            numMatches = 100;

        for (int i = 0; i < numMatches; i++) {
            try {
                MatchObject mo = matches[i];
                if ((mo.getMatchValue() > 0) && ((mo.getMatchValue() * mo.getAdjustedMatchValue()) > 2)) {

                    Element match = root.addElement("match");
                    match.addAttribute("points", (new Double(mo.getMatchValue())).toString());
                    match.addAttribute("adjustedpoints", (new Double(mo.getAdjustedMatchValue())).toString());
                    match.addAttribute("pointBreakdown", mo.getPointBreakdown());
                    String finalscore = (new Double(mo.getMatchValue() * mo.getAdjustedMatchValue()))
                            .toString();
                    if (finalscore.length() > 7) {
                        finalscore = finalscore.substring(0, 6);
                    }
                    match.addAttribute("finalscore", finalscore);

                    //check if logM is very small...
                    try {
                        match.addAttribute("logMStdDev", (new Double(mo.getLogMStdDev())).toString());
                    } catch (java.lang.NumberFormatException nfe) {
                        match.addAttribute("logMStdDev", "<0.01");
                    }
                    match.addAttribute("evaluation", mo.getEvaluation());

                    Encounter firstEnc = myShepherd.getEncounter(mo.getEncounterNumber());
                    Element enc = match.addElement("encounter");
                    enc.addAttribute("number", firstEnc.getEncounterNumber());
                    enc.addAttribute("date", firstEnc.getDate());

                    if (firstEnc.getSex() != null) {
                        enc.addAttribute("sex", firstEnc.getSex());
                    } else {
                        enc.addAttribute("sex", "unknown");
                    }

                    enc.addAttribute("assignedToShark",
                            ServletUtilities.handleNullString(firstEnc.getIndividualID()));
                    if (firstEnc.getSizeAsDouble() != null) {
                        enc.addAttribute("size", (firstEnc.getSize() + " meters"));
                    }
                    enc.addAttribute("location", firstEnc.getLocation());
                    enc.addAttribute("locationID", firstEnc.getLocationID());
                    VertexPointMatch[] firstScores = mo.getScores();
                    try {
                        for (int k = 0; k < firstScores.length; k++) {
                            Element spot = enc.addElement("spot");
                            spot.addAttribute("x", (new Double(firstScores[k].getOldX())).toString());
                            spot.addAttribute("y", (new Double(firstScores[k].getOldY())).toString());
                        }
                    } catch (NullPointerException npe) {
                    }
                    Element enc2 = match.addElement("encounter");
                    Encounter secondEnc = myShepherd.getEncounter(num);
                    enc2.addAttribute("number", num);
                    enc2.addAttribute("date", secondEnc.getDate());

                    //enc2.addAttribute("sex", secondEnc.getSex());
                    if (secondEnc.getSex() != null) {
                        enc2.addAttribute("sex", secondEnc.getSex());
                    } else {
                        enc2.addAttribute("sex", "unknown");
                    }

                    enc2.addAttribute("assignedToShark",
                            ServletUtilities.handleNullString(secondEnc.getIndividualID()));
                    if (secondEnc.getSizeAsDouble() != null) {
                        enc2.addAttribute("size", (secondEnc.getSize() + " meters"));
                    } else {
                        enc2.addAttribute("size", "unknown");
                    }
                    enc2.addAttribute("location", secondEnc.getLocation());
                    enc2.addAttribute("locationID", secondEnc.getLocationID());
                    try {
                        for (int j = 0; j < firstScores.length; j++) {
                            Element spot = enc2.addElement("spot");
                            spot.addAttribute("x", (new Double(firstScores[j].getNewX())).toString());
                            spot.addAttribute("y", (new Double(firstScores[j].getNewY())).toString());
                        }
                    } catch (NullPointerException npe) {
                    }

                    //let's find the keywords in common
                    List<String> keywords = myShepherd.getKeywordsInCommon(mo.getEncounterNumber(), num);
                    int keywordsSize = keywords.size();
                    if (keywordsSize > 0) {
                        Element kws = match.addElement("keywords");
                        for (int y = 0; y < keywordsSize; y++) {
                            Element keyword = kws.addElement("keyword");
                            keyword.addAttribute("name", ((String) keywords.get(y)));
                        }
                    }

                } //end if
            } catch (Exception finale) {
                finale.printStackTrace();
            }
        } //end for

        //prep for writing out the XML

        //in case this is a right-side scan, change file name to save to
        String fileAddition = "";
        if (rightSide) {
            fileAddition = "Right";
        }

        //setup data dir
        String rootWebappPath = getServletContext().getRealPath("/");
        File webappsDir = new File(rootWebappPath).getParentFile();
        File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
        //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();}
        File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
        //if(!encountersDir.exists()){encountersDir.mkdirs();}
        String thisEncDirString = Encounter.dir(shepherdDataDir, num);
        File thisEncounterDir = new File(thisEncDirString);
        if (!thisEncounterDir.exists()) {
            thisEncounterDir.mkdirs();
            System.out.println("I am making the encDir: " + thisEncDirString);
        }

        //File file=new File((new File(".")).getCanonicalPath()+File.separator+"webapps"+File.separator+"ROOT"+File.separator+"encounters"+File.separator+num+File.separator+"lastFull"+fileAddition+"Scan.xml");
        File file = new File(Encounter.dir(shepherdDataDir, num) + "/lastFull" + fileAddition + "Scan.xml");

        System.out.println("Writing scanTask XML file to: " + file.getAbsolutePath());

        FileWriter mywriter = new FileWriter(file);
        org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));
        org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(mywriter, format);
        writer.write(document);
        writer.close();
        System.out.println("Successful write.");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}