Example usage for javax.xml.transform OutputKeys METHOD

List of usage examples for javax.xml.transform OutputKeys METHOD

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys METHOD.

Prototype

String METHOD

To view the source code for javax.xml.transform OutputKeys METHOD.

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an JSON input stream to a XML stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param JSONStream The XML stream to convert to JSON
 * @param XMLStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the XML text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws IOException Thrown if an IO error occurs.
 *///  w ww .  j a va2 s.  c  o  m
public static void toXml(InputStream JSONStream, OutputStream XMLStream, boolean verbose) throws IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toXml(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform", "Parsing the JSON and a DOM builder.");
        }

        try {
            //Get the JSON from the stream.
            JSONObject jObject = new JSONObject(JSONStream);

            //Create a new document

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbf.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the JSON content to XML");
            }

            convertJSONObject(doc, doc.getDocumentElement(), jObject, "jsonObject");

            //Serialize it.
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer serializer = null;
            if (verbose) {
                serializer = tfactory.newTransformer(new StreamSource(new StringReader(styleSheet)));
                ;
            } else {
                serializer = tfactory.newTransformer();
            }
            Properties oprops = new Properties();
            oprops.put(OutputKeys.METHOD, "xml");
            oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
            oprops.put(OutputKeys.VERSION, "1.0");
            oprops.put(OutputKeys.INDENT, "true");
            serializer.setOutputProperties(oprops);
            serializer.transform(new DOMSource(doc), new StreamResult(XMLStream));

        } catch (Exception ex) {
            IOException iox = new IOException("Problem during conversion");
            iox.initCause(ex);
            throw iox;
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, OutputStream)");
    }
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java

public static byte[] documentToByte(Document document) throws TransformerException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    transformer.transform(new DOMSource(document), new StreamResult(bos));

    return bos.toByteArray();
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

protected static String XmltoString(Document document) throws TransformerException {
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(document.getDocumentElement()), streamResult);
    return stringWriter.toString();
}

From source file:org.openmrs.web.controller.report.CohortReportFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *///  w  w  w. j  ava2 s.c  om
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObj,
        BindException errors) throws Exception {
    CommandObject command = (CommandObject) commandObj;

    // do simpleframework serialization of everything but 'rows', and add those via handcoded xml, since
    // serializing them is not reversible

    ReportSchema rs = new ReportSchema();
    rs.setReportSchemaId(command.getReportId());
    rs.setName(command.getName());
    rs.setDescription(command.getDescription());
    rs.setReportParameters(command.getParameters());
    rs.setDataSetDefinitions(new ArrayList<DataSetDefinition>());
    Serializer serializer = OpenmrsUtil.getSerializer();
    StringWriter sw = new StringWriter();
    serializer.write(rs, sw);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document xml = db.parse(new InputSource(
            new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + sw.toString())));
    Node node = findChild(xml, "reportSchema");
    node = findChild(node, "dataSets");
    Element dsd = xml.createElement("dataSetDefinition");
    dsd.setAttribute("name", "cohorts");
    dsd.setAttribute("class", "org.openmrs.report.CohortDataSetDefinition");
    node.appendChild(dsd);
    Element strategies = xml.createElement("strategies");
    strategies.setAttribute("class", "java.util.LinkedHashMap");
    dsd.appendChild(strategies);
    Element descriptions = xml.createElement("descriptions");
    descriptions.setAttribute("class", "java.util.LinkedHashMap");
    dsd.appendChild(descriptions);
    for (CohortReportRow row : command.getRows()) {
        if (StringUtils.hasText(row.getQuery())) {
            Element entry = xml.createElement("entry");
            strategies.appendChild(entry);
            Element nameEl = xml.createElement("string");
            Text val = xml.createTextNode(row.getName());
            val.setNodeValue(row.getName());
            nameEl.appendChild(val);
            entry.appendChild(nameEl);
            Element cohort = xml.createElement("cohort");
            entry.appendChild(cohort);
            cohort.setAttribute("class", "org.openmrs.reporting.PatientSearch");
            Element strategyEl = xml.createElement("specification");
            val = xml.createTextNode(row.getQuery());
            val.setNodeValue(row.getQuery());
            strategyEl.appendChild(val);
            cohort.appendChild(strategyEl);
        }
        if (StringUtils.hasText(row.getDescription())) {
            Element entry = xml.createElement("entry");
            descriptions.appendChild(entry);
            Element el = xml.createElement("string");
            Text val = xml.createTextNode(row.getName());
            val.setNodeValue(row.getName());
            el.appendChild(val);
            entry.appendChild(el);
            el = xml.createElement("string");
            val = xml.createTextNode(row.getDescription());
            val.setNodeValue(row.getDescription());
            el.appendChild(val);
            entry.appendChild(el);
        }
    }

    // now turn this into an xml string
    System.setProperty("javax.xml.transform.TransformerFactory",
            "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.METHOD, "xml");
    StringWriter out = new StringWriter();
    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(xml);
    trans.transform(source, result);
    String schemaXml = out.toString();

    ReportSchemaXml rsx = new ReportSchemaXml();
    rsx.populateFromReportSchema(rs);
    rsx.setXml(schemaXml);
    rsx.updateXmlFromAttributes();
    rsx.setUuid(request.getParameter("parentUUID"));

    ReportService rptSvc = (ReportService) Context.getService(ReportService.class);
    if (rsx.getReportSchemaId() != null) {
        rptSvc.saveReportSchemaXml(rsx);
    } else {
        rptSvc.saveReportSchemaXml(rsx);
    }

    return new ModelAndView(new RedirectView(getSuccessView() + "?reportId=" + rsx.getReportSchemaId()));
}

From source file:net.sourceforge.eclipsetrader.charts.ChartsPlugin.java

public static void saveDefaultChart(Chart chart) {
    Log logger = LogFactory.getLog(ChartsPlugin.class);
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //$NON-NLS-1$

    try {//from   w  ww .  j  av a 2  s. c om
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.getDOMImplementation().createDocument(null, "chart", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();

        Element node = document.createElement("title"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(chart.getTitle()));
        root.appendChild(node);
        node = document.createElement("compression"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
        root.appendChild(node);
        node = document.createElement("period"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
        root.appendChild(node);
        node = document.createElement("autoScale"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
        root.appendChild(node);
        if (chart.getBeginDate() != null) {
            node = document.createElement("begin"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
            root.appendChild(node);
        }
        if (chart.getEndDate() != null) {
            node = document.createElement("end"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
            root.appendChild(node);
        }
        for (int r = 0; r < chart.getRows().size(); r++) {
            ChartRow row = (ChartRow) chart.getRows().get(r);
            row.setId(new Integer(r));

            Element rowNode = document.createElement("row"); //$NON-NLS-1$
            root.appendChild(rowNode);

            for (int t = 0; t < row.getTabs().size(); t++) {
                ChartTab tab = (ChartTab) row.getTabs().get(t);
                tab.setId(new Integer(t));

                Element tabNode = document.createElement("tab"); //$NON-NLS-1$
                tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
                rowNode.appendChild(tabNode);

                for (int i = 0; i < tab.getIndicators().size(); i++) {
                    ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                    indicator.setId(new Integer(i));

                    Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }

                for (int i = 0; i < tab.getObjects().size(); i++) {
                    ChartObject object = (ChartObject) tab.getObjects().get(i);
                    object.setId(new Integer(i));

                    Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                    indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                    tabNode.appendChild(indicatorNode);

                    for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                        String key = (String) iter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                        indicatorNode.appendChild(node);
                    }
                }
            }
        }

        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
        } catch (Exception e) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http\u003a//xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMSource source = new DOMSource(document);

        File file = ChartsPlugin.getDefault().getStateLocation().append("defaultChart.xml").toFile(); //$NON-NLS-1$

        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        out.close();

    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Initialize the output properties to the values specified in the
 * transformation sheet or to their default values, resp.
 */// w  w w  .j av  a 2s. c  om
public void initOutputProperties() {
    outputProperties = new Properties();
    outputProperties.setProperty(OutputKeys.ENCODING, transformNode.outputEncoding);
    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, "text/xml");
    outputProperties.setProperty(OutputKeys.METHOD, transformNode.outputMethod);
    outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    outputProperties.setProperty(OutputKeys.STANDALONE, "no");
    outputProperties.setProperty(OutputKeys.VERSION, "1.0");
}

From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java

/**
 * @throws XtentisException// w  w w .j a  v a  2s.co  m
 * 
 * @ejb.interface-method view-type = "local"
 * @ejb.facade-method
 */
public void execute(TransformerPluginContext context) throws XtentisException {
    try {
        // fetch data from context
        Transformer transformer = (Transformer) context.get(TRANSFORMER);
        String outputMethod = (String) context.get(OUTPUT_METHOD);
        TypedContent xmlTC = (TypedContent) context.get(INPUT_XML);

        // get the charset
        String charset = Util.extractCharset(xmlTC.getContentType());

        // get the xml String
        String xml = new String(xmlTC.getContentBytes(), charset);

        // get the xml parameters
        TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS);
        if (parametersTC != null) {
            String parametersCharset = Util.extractCharset(parametersTC.getContentType());

            byte[] parametersBytes = parametersTC.getContentBytes();
            if (parametersBytes != null) {
                String parameters = new String(parametersBytes, parametersCharset);

                Document parametersDoc = Util.parse(parameters);
                NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$
                for (int i = 0; i < paramList.getLength(); i++) {
                    String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$
                    String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$
                    if (paramValue == null)
                        paramValue = ""; //$NON-NLS-1$

                    if (paramName != null) {
                        transformer.setParameter(paramName, paramValue);
                    }
                }
            }
        }

        // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions?

        // Sets the current time
        transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$
        transformer.setErrorListener(new ErrorListener() {

            public void error(TransformerException exception) throws TransformerException {
                transformatioError = exception.getMessage();
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                transformatioError = exception.getMessage();
            }

            public void warning(TransformerException exception) throws TransformerException {
                transformationeWarning = exception.getMessage();

            }
        });
        transformatioError = null;
        transformationeWarning = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.newDocument();
            DOMResult domResult = new DOMResult(document);

            transformer.transform(new StreamSource(new StringReader(xml)), domResult);

            if (transformationeWarning != null) {
                String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$
                LOG.warn(err);
            }
            if (transformatioError != null) {
                String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$
                LOG.error(err);
                throw new XtentisException(err);
            }
            Node rootNode = document.getDocumentElement();
            // process the cross-referencings
            NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$
            int len = xrefl.getLength();
            for (int i = 0; i < len; i++) {
                Element xrefe = (Element) xrefl.item(i);
                xrefe = processMappings(xrefe);
            }
            TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl();
            Transformer serializer = transFactory.newTransformer();
            serializer.setOutputProperty(OutputKeys.METHOD, outputMethod);
            serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
            serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
            serializer.transform(new DOMSource(rootNode), new StreamResult(baos));
        } else {
            if (transformationeWarning != null) {
                String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$
                LOG.warn(err);
            }
            if (transformatioError != null) {
                String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$
                LOG.error(err);
                throw new XtentisException(err);
            }
            // transform the item
            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos));
        }
        // Call Back
        byte[] bytes = baos.toByteArray();
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
        context.put(OUTPUT_TEXT,
                new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$
                        : "text/" //$NON-NLS-1$
                                + outputMethod)
                        + "; charset=utf-8")); //$NON-NLS-1$
        context.getPluginCallBack().contentIsReady(context);
    } catch (Exception e) {
        String err = "Could not start the XSLT plugin"; //$NON-NLS-1$
        LOG.error(err, e);
        throw new XtentisException(err);
    }
}

From source file:it.drwolf.ridire.session.async.Mapper.java

/**
 * Returns a transformer handler that serializes incoming SAX events to
 * XHTML or HTML (depending the given method) using the given output
 * encoding./*from  ww  w.  j  a  va 2s .  co m*/
 * 
 * @see <a
 *      href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
 * @param method
 *            "xml" or "html"
 * @param encoding
 *            output encoding, or <code>null</code> for the platform default
 * @param writer
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *             if the transformer can not be created
 */
private TransformerHandler getTransformerHandler(String method, String encoding, Writer writer)
        throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    handler.setResult(new StreamResult(writer));
    return handler;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Transforms (serializes) XML DOM document to string.
 *
 * @param doc//from   w  w w .  ja  v a 2  s.c om
 *            document to transform to string
 * @return XML string representation of document
 * @throws javax.xml.transform.TransformerException
 *             If an exception occurs while transforming XML DOM document to string
 */
public static String documentToString(Node doc) throws TransformerException {
    StringWriter sw = new StringWriter();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NON-NLS
    transformer.setOutputProperty(OutputKeys.ENCODING, UTF8);

    transformer.transform(new DOMSource(doc), new StreamResult(sw));

    return sw.toString();
    // NOTE: if return as single line
    // return sw.toString().replaceAll("\n|\r", ""); // NON-NLS
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * writes an editable, unlocked exam to a file
 *
 * @param exam      the exam to be written
 * @param examFile  the target file//from  w ww. j a v a 2 s  .  c o  m
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the file write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeRaw(@Nonnull Exam exam, @Nonnull File examFile, boolean overwrite)
        throws VaSolSimException {
    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        //can't overwrite
        if (!overwrite) {
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            if (!examFile.createNewFile()) {
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    /*
     * build exam info
     */
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);

    //start security xml section
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            exam.getStatsDestinationEmail(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, exam.getStatsSenderEmail(),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            exam.getStatsSenderSMTPAddress(), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            Integer.toString(exam.getStatsSenderSMTPPort()), security, examDoc);

    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.verifyQuestionSetsIntegrity(questionSets)) {
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName() == null || qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1)
                            : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResources() != null) {
                for (BufferedImage img : qSet.getResources()) {
                    try {
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out);
                        out.flush();
                        GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                convertBytesToHexString(out.toByteArray()), qSetElement, examDoc);
                    } catch (IOException e) {
                        throw new VaSolSimException("Error: cannot write images to byte array for transport");
                    }
                }
            }

            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName() == null || question.getName().equals(""))
                                ? "Question " + (setIndex + 1)
                                : question.getName(),
                        qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    GenericUtils.appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, answer.getAnswerText(),
                            qElement, examDoc);
                }

                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    AnswerChoice ac = question.getAnswerChoices().get(questionIndex);

                    Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                    qElement.appendChild(acElement);

                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                            Integer.toString(questionIndex + 1), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                            ac.getVisibleChoiceID(), acElement, examDoc);
                    GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                            examDoc);
                }
            }
        }
    }

    return true;
}