Example usage for org.dom4j.io XMLWriter close

List of usage examples for org.dom4j.io XMLWriter close

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

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 {/*from  ww  w . ja va 2 s . c  o m*/
        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 {//ww  w  . j  a v a 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 = 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;
    }
}

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

License:Open Source License

public boolean i3sWriteThis(Shepherd myShepherd, MatchObject[] matches, String num, String newEncDate,
        String newEncShark, String newEncSize, boolean rightSide, double cutoff, String context) {
    try {/*from   www.j  av a2 s  .  c  om*/

        System.out.println("scanWorkItemResultsHandler: Prepping to write I3S XML file for encounter " + num);

        //now setup the XML write for the encounter
        //int resultsSize=results.size();

        Arrays.sort(matches, new NewI3SMatchComparator());
        StringBuffer resultsXML = new StringBuffer();
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("matchSet");
        root.addAttribute("scanDate", (new java.util.Date()).toString());
        //System.out.println("Total num matches for I3S printing: "+matches.length);

        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 {
                //System.out.println();
                MatchObject mo = matches[i];
                //System.out.println("I3S match value: "+mo.getI3SMatchValue());
                if ((mo.getI3SMatchValue() > 0.001) && (mo.getI3SMatchValue() <= 2.0)) {
                    Element match = root.addElement("match");
                    String finalscore = (new Double(mo.getI3SMatchValue())).toString();
                    if (finalscore.length() > 7) {
                        finalscore = finalscore.substring(0, 6);
                    }
                    match.addAttribute("finalscore", finalscore);
                    match.addAttribute("evaluation", mo.getEvaluation());

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

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

                    enc.addAttribute("assignedToShark", mo.getIndividualName());
                    enc.addAttribute("size", (new Double(mo.getSize())).toString());

                    //get the Map
                    Vector map = mo.getMap2();
                    int mapSize = map.size();
                    Encounter e1 = myShepherd.getEncounter(mo.getEncounterNumber());
                    for (int f = 0; f < mapSize; f++) {
                        Pair tempPair = (com.reijns.I3S.Pair) map.get(f);
                        int M1 = tempPair.getM1();
                        ArrayList<SuperSpot> spts = new ArrayList<SuperSpot>();
                        if (rightSide) {
                            spts = e1.getRightSpots();
                        } else {
                            spts = e1.getSpots();
                        }
                        //System.out.println("scanWorkItemResultsHandler: I3S spots: "+spts.size()+" vs mapSize: "+mapSize);
                        Element spot = enc.addElement("spot");
                        spot.addAttribute("x",
                                (new Double(spts.get(M1).getTheSpot().getCentroidX())).toString());
                        spot.addAttribute("y",
                                (new Double(spts.get(M1).getTheSpot().getCentroidY())).toString());
                    }

                    Element enc2 = match.addElement("encounter");
                    enc2.addAttribute("number", num);
                    enc2.addAttribute("date", newEncDate);
                    enc2.addAttribute("sex", mo.getNewSex());
                    enc2.addAttribute("assignedToShark", newEncShark);
                    enc2.addAttribute("size", newEncSize);

                    //reset the Iterator
                    Encounter e2 = myShepherd.getEncounter(num);
                    for (int g = 0; g < mapSize; g++) {
                        Pair tempPair = (com.reijns.I3S.Pair) map.get(g);
                        int M2 = tempPair.getM2();
                        ArrayList<SuperSpot> spts = new ArrayList<SuperSpot>();
                        if (rightSide) {
                            spts = e2.getRightSpots();
                        } else {
                            spts = e2.getSpots();
                        }
                        Element spot = enc2.addElement("spot");
                        //System.out.println("scanWorkItemResultsHandler: I3S next spots: "+spts.size()+" vs mapSize: "+mapSize);
                        spot.addAttribute("x",
                                (new Double(spts.get(M2).getTheSpot().getCentroidX())).toString());
                        spot.addAttribute("y",
                                (new Double(spts.get(M2).getTheSpot().getCentroidY())).toString());
                    }

                }
            } catch (NullPointerException npe) {
                npe.printStackTrace();
            }
        }

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

        //File file=new File((new File(".")).getCanonicalPath()+File.separator+"webapps"+File.separator+"ROOT"+File.separator+"encounters"+File.separator+num+File.separator+"lastFull"+fileAddition+"I3SScan.xml");
        File file = new File(Encounter.dir(shepherdDataDir, num) + "/lastFull" + fileAddition + "I3SScan.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("writeOutScanTask: Successful I3S write.");
        return true;
    } catch (Exception e) {
        System.out.println("writeOutScanTask: Failed to write out I3S results!");
        e.printStackTrace();
        return false;
    }

}

From source file:org.efaps.webdav4vfs.handler.PropFindHandler.java

License:Apache License

/**
 * Handle a PROPFIND request.//from ww w  . j  a v a2 s.  c o  m
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        logXml(propDoc);

        Element propFindEl = propDoc.getRootElement();
        for (Object propElObject : propFindEl.elements()) {
            Element propEl = (Element) propElObject;
            if (VALID_PROPFIND_TAGS.contains(propEl.getName())) {
                FileObject object = VFSBackend.resolveFile(request.getPathInfo());
                if (object.exists()) {
                    // respond as XML encoded multi status
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(SC_MULTI_STATUS);

                    Document multiStatusResponse = getMultiStatusResponse(object, propEl, getBaseUrl(request),
                            getDepth(request));
                    logXml(multiStatusResponse);

                    // write the actual response
                    XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
                    writer.write(multiStatusResponse);
                    writer.flush();
                    writer.close();

                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                break;
            }
        }
    } catch (DocumentException e) {
        LOG.error("invalid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.efaps.webdav4vfs.handler.PropPatchHandler.java

License:Apache License

/**
 * Handle a PROPPATCH request./* w w w .j a v a  2  s . c o m*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.etudes.api.app.melete.util.XMLHelper.java

License:Apache License

/**
 * creates xml file for the give path//from   w  ww .  j  a va 2 s .c om
 * @param url - path to create xml file
 * @throws IOException
 */
static public void generateXMLFile(String url, Document document) throws Exception {
    XMLWriter writer = null;
    FileOutputStream out = null;
    try {
        if (document == null)
            document = DocumentHelper.createDocument();

        out = new FileOutputStream(new File(url));
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        //outformat.setEncoding(aEncodingScheme);
        writer = new XMLWriter(out, outformat);
        writer.write(document);
        writer.flush();
    } catch (IOException e1) {
        throw e1;
    } catch (Exception e) {
        throw e;
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e2) {
        }

        try {
            if (out != null)
                out.close();
        } catch (IOException e3) {
        }
    }
}

From source file:org.foxbpm.engine.test.AbstractFoxBpmTestCase.java

License:Apache License

@Before
public void annotationDeploymentSetUp() throws Exception {

    Method method = null;/*from w w  w.j  a  v a 2  s.  c  om*/
    try {
        method = this.getClass().getDeclaredMethod(name.getMethodName(), (Class<?>[]) null);
    } catch (Exception e) {
        throw new FoxBPMException("?!", e);
    }
    if (method.isAnnotationPresent(Clear.class)) {
        Clear clearAnnotation = method.getAnnotation(Clear.class);
        String[] tableNames = clearAnnotation.tables();
        for (String tableName : tableNames) {
            jdbcTemplate.execute("delete from " + tableName);
        }
    }
    Deployment deploymentAnnotation = method.getAnnotation(Deployment.class);
    if (deploymentAnnotation != null) {
        String[] resources = deploymentAnnotation.resources();
        if (resources.length == 0) {
            return;
        }
        DeploymentBuilder deploymentBuilder = null;// processEngine.getModelService().createDeployment().name("??");
        // ?????
        BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
        BpmnModel bpmnModel = null;
        SAXReader reader = new SAXReader();
        ByteArrayOutputStream out = null;
        OutputFormat format = null;
        for (String resource : resources) {
            bpmnModel = bpmnXMLConverter
                    .convertToBpmnModel(reader.read(ReflectUtil.getResourceAsStream(resource)));
            deploymentBuilder = processEngine.getModelService().createDeployment().name("??");
            // deploymentBuilder.addClasspathResource(resource);
            try {
                out = new ByteArrayOutputStream();
                // ?
                format = OutputFormat.createPrettyPrint();
                format.setEncoding("UTF-8");
                XMLWriter xmlWriter = new XMLWriter(out, format);
                xmlWriter.setEscapeText(false);
                xmlWriter.write(bpmnXMLConverter.convertToXML(bpmnModel));
                xmlWriter.close();
                System.out.println(resource + "---------------" + out.toString());
                deploymentBuilder.addInputStream(resource, new ByteArrayInputStream(out.toByteArray()));
                deploymentBuilder.deploy();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java

License:Open Source License

/**
 * @see org.gbif.portal.util.mhf.Message#getRawData()
 *//*from   w  w  w.  ja  v  a2  s  .c om*/
public String getRawData() throws MessageAccessException {
    if (rawXml != null)
        return rawXml.toString();
    else {
        // build a short string
        StringWriter writer = new StringWriter();
        OutputFormat outformat = OutputFormat.createCompactFormat();
        outformat.setSuppressDeclaration(true);

        XMLWriter xmlWriter = new XMLWriter(writer, outformat);
        try {
            xmlWriter.write(getDocument());
            xmlWriter.flush();
            String rawXml = writer.toString();
            setRawData(rawXml);
            return rawXml;
        } catch (IOException e) {
            throw new MessageAccessException("Error writing the XML Document", e);
        } finally {
            try {
                xmlWriter.close();
            } catch (IOException e) {
            }
            try {
                writer.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java

License:Open Source License

/**
 * @see org.gbif.portal.util.mhf.message.impl.xml.BeautifiedData#getBeautifiedData()
 *//* ww w  .  j a v a 2 s  .  com*/
public String getLoggableData() throws MessageAccessException {
    // build a beautiful string
    StringWriter writer = new StringWriter();
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setSuppressDeclaration(true);
    XMLWriter xmlWriter = new XMLWriter(writer, outformat);
    try {
        xmlWriter.write(getDocument());
        xmlWriter.flush();
        String rawXml = writer.toString();
        setRawData(rawXml);
        return rawXml.trim();
    } catch (IOException e) {
        throw new MessageAccessException("Error writing the XML Document", e);
    } finally {
        try {
            xmlWriter.close();
        } catch (IOException e) {
        }
        try {
            writer.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.goodoldai.jeff.report.xml.XMLReportBuilder.java

License:Open Source License

/**
 * Creates a report based on the provided explanation and writes it to the
 * provided object that is type of org.dom4j.Document before it is written
 * in the file// w w  w . ja  va 2s .c o m
 * 
 * @param explanation
 *            the explanation that needs to be transformed into a report
 * @param stream
 *            output stream to which the report is to be written
 * 
 * @throws org.goodoldai.jeff.explanation.ExplanationException
 *             if any of the arguments are null
 */
@Override
public void buildReport(Explanation explanation, Object stream) {

    if (explanation == null) {
        throw new ExplanationException("The entered explanation must not be null");
    }

    if (stream == null) {
        throw new ExplanationException("The entered stream must not be null");
    }

    if (!(stream instanceof PrintWriter)) {
        throw new ExplanationException("The argument 'stream' must be the type of java.io.PrintWriter");
    }

    Document document = DocumentHelper.createDocument();
    document.addElement("explanation");

    insertHeader(explanation, document);

    ArrayList<ExplanationChunk> chunks = explanation.getChunks();

    for (int i = 0; i < chunks.size(); i++) {

        ExplanationChunk chunk = chunks.get(i);
        ReportChunkBuilder cbuilder = factory.getReportChunkBuilder(chunk);

        cbuilder.buildReportChunk(chunk, document, isInsertChunkHeaders());
    }

    XMLWriter writer = new XMLWriter(((PrintWriter) stream));
    try {
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        throw new ExplanationException(
                "The file could not be writen due to fallowing IO error: " + ex.getMessage());
    }
}