Example usage for org.jdom2 Element Element

List of usage examples for org.jdom2 Element Element

Introduction

In this page you can find the example usage for org.jdom2 Element Element.

Prototype

public Element(final String name) 

Source Link

Document

Create a new element with the supplied (local) name and no namespace.

Usage

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java

License:Open Source License

/**
 * Replaces all formulas with the html representation of the mapped formula objects
 *
 * @param doc        JDOM Document where to replace the formulas
 * @param formulaMap Map of the indexed Formula Objects
 * @return JDOM Document with replaced formulas
 *///from   w  w  w . j a  va  2 s  . com
public Document replaceFormulas(Document doc, Map<Integer, Formula> formulaMap) {
    List<Element> foundFormulas = xpath.evaluate(doc);

    if (foundFormulas.size() > 0) {
        Map<String, Element> formulaMarkupMap = new HashMap<>();

        // Initialize markup map
        for (Element element : foundFormulas) {
            formulaMarkupMap.put(element.getAttribute("id").getValue(), element);
        }

        // Replace all found formulas
        Iterator<Integer> formulaIterator = formulaMap.keySet().iterator();
        while (formulaIterator.hasNext()) {
            Integer id = formulaIterator.next();

            Element formulaMarkupRoot = formulaMarkupMap.get(FORMULA_ID_PREFIX + id);
            Formula formula = formulaMap.get(id);

            formulaMarkupRoot.removeAttribute("class");
            formulaMarkupRoot.removeContent();
            formulaMarkupRoot.setName("div");

            Element div = (Element) formulaMarkupRoot.getParent();
            div.setName("div");
            div.setAttribute("class", "formula");

            // Potentially there's text inside the paragraph...
            List<Text> texts = div.getContent(Filters.textOnly());
            if (texts.isEmpty() == false) {
                String textString = "";
                for (Text text : texts) {
                    textString += text.getText();
                }
                Element textSpan = new Element("span");
                textSpan.setAttribute("class", "text");
                textSpan.setText(textString);
                div.addContent(textSpan);

                List<Content> content = div.getContent();
                content.removeAll(texts);
            }

            if (generateDebugMarkup) {
                div.setAttribute("style", "border: 1px solid black;");

                // Header
                Element h4 = new Element("h4");
                h4.setText("DEBUG - Formula #" + formula.getId());
                div.addContent(h4);

                // Render LaTeX source
                Element latexPre = new Element("pre");
                latexPre.setAttribute("class", "debug-latex");
                latexPre.setText(formula.getLatexCode());
                div.addContent(latexPre);

                // Render MathML markup
                Element mathmlPre = new Element("pre");
                mathmlPre.setAttribute("class", "debug-mathml");
                mathmlPre.setText(formula.getMathMl());
                div.addContent(mathmlPre);

                // Render HTML Markup
                Element htmlPre = new Element("pre");
                htmlPre.setAttribute("class", "debug-html");
                XMLOutputter xmlOutputter = new XMLOutputter();
                xmlOutputter.setFormat(Format.getRawFormat());
                htmlPre.setText(xmlOutputter.outputString(formula.getHtml()));

                div.addContent(htmlPre);

            }

            // Set formula into
            formulaMarkupRoot.addContent(formula.getHtml());
        }
    }
    return doc;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.FormulaConverter.java

License:Open Source License

public Element renderInvalidFormulaSource(Formula formula) {
    // Render invalid LaTeX code
    Element invalidFormulaPre = new Element("pre");
    invalidFormulaPre.setText("Formula #" + formula.getId() + " is invalid!\n\n" + formula.getLatexCode());
    return invalidFormulaPre;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.mathml2html.ImageFormulaConverter.java

License:Open Source License

/**
 * Takes a single LaTeX formula and converts it to an image in PNG format
 *
 * @param id           formula's number inside the document
 * @param latexFormula LaTeX formula//  ww w.j  a va 2s .  co  m
 * @return Formula object with resulting image file path set
 */
@Override
public Formula parse(int id, String latexFormula) {
    Formula formula = super.parseToMathML(id, latexFormula);
    logger.debug("parse() entered...");
    if (formula.isInvalid() == false) {
        try {
            final org.w3c.dom.Document doc = MathMLParserSupport.parseString(formula.getMathMl());

            final File outFile = Files.createTempFile(tempDirPath, "formula", ".png").toFile();

            formula.setImageFilePath(outFile.toPath());

            // Generate Html Image tag
            Element imageTag = new Element("img");
            imageTag.setAttribute("src", formula.getImageFilePath().getFileName().toString());
            imageTag.setAttribute("alt", FORMULA_ID_PREFIX + formula.getId());
            formula.setHtml(imageTag);

            final MutableLayoutContext params = new LayoutContextImpl(
                    LayoutContextImpl.getDefaultLayoutContext());
            params.setParameter(Parameter.MATHSIZE, 25f);

            // convert to image
            net.sourceforge.jeuclid.converter.Converter imageConverter = net.sourceforge.jeuclid.converter.Converter
                    .getInstance();
            imageConverter.convert(doc, outFile, "image/png", params);
            logger.debug("Image file created at: " + outFile.toPath().toAbsolutePath().toString());
        } catch (SAXException e1) {
            logger.error(e1.getMessage(), e1);
        } catch (ParserConfigurationException e2) {
            logger.error(e2.getMessage(), e2);
        } catch (IOException e3) {
            logger.error(e3.getMessage(), e3);
        }
    } else {
        formula.setHtml(renderInvalidFormulaSource(formula));
    }
    return formula;
}

From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the schema.xml file for the given core according to the core definition.
 *
 * @param engine the engine configuration
 *//*  w ww.  j  a v a2s .c  o  m*/
private void createSchemaXml(SolrCoreConfiguration engine) throws MarmottaException {
    log.info("generating schema.xml for search program {}", engine.getName());

    SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
    File schemaTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "schema-template.xml");
    File schemaFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "schema.xml");
    try {
        Document doc = parser.build(schemaTemplate);

        Element schemaNode = doc.getRootElement();
        Element fieldsNode = schemaNode.getChild("fields");
        if (!schemaNode.getName().equals("schema") || fieldsNode == null)
            throw new MarmottaException(schemaTemplate + " is an invalid SOLR schema file");

        schemaNode.setAttribute("name", engine.getName());

        Program<Value> program = engine.getProgram();

        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {
            String fieldName = fieldMapping.getFieldName();
            String solrType = null;
            try {
                solrType = solrProgramService.getSolrFieldType(fieldMapping.getFieldType().toString());
            } catch (MarmottaException e) {
                solrType = null;
            }
            if (solrType == null) {
                log.error("field {} has an invalid field type; ignoring field definition", fieldName);
                continue;
            }

            Element fieldElement = new Element("field");
            fieldElement.setAttribute("name", fieldName);
            fieldElement.setAttribute("type", solrType);
            // Set the default properties
            fieldElement.setAttribute("stored", "true");
            fieldElement.setAttribute("indexed", "true");
            fieldElement.setAttribute("multiValued", "true");

            // FIXME: Hardcoded Stuff!
            if (solrType.equals("location")) {
                fieldElement.setAttribute("indexed", "true");
                fieldElement.setAttribute("multiValued", "false");
            }

            // Handle extra field configuration
            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();
            if (fieldConfig != null) {
                for (Map.Entry<String, String> attr : fieldConfig.entrySet()) {
                    if (SOLR_FIELD_OPTIONS.contains(attr.getKey())) {
                        fieldElement.setAttribute(attr.getKey(), attr.getValue());
                    }
                }
            }
            fieldsNode.addContent(fieldElement);

            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_COPY_FIELD_OPTION)) {
                String[] copyFields = fieldConfig.get(SOLR_COPY_FIELD_OPTION).split("\\s*,\\s*");
                for (String copyField : copyFields) {
                    if (copyField.trim().length() > 0) { // ignore 'empty' fields
                        Element copyElement = new Element("copyField");
                        copyElement.setAttribute("source", fieldName);
                        copyElement.setAttribute("dest", copyField.trim());
                        schemaNode.addContent(copyElement);
                    }
                }
            } else {
                Element copyElement = new Element("copyField");
                copyElement.setAttribute("source", fieldName);
                copyElement.setAttribute("dest", "lmf.text_all");
                schemaNode.addContent(copyElement);
            }

            //for suggestions, copy all fields to lmf.spellcheck (used for spellcheck and querying);
            //only facet is a supported type at the moment
            if (fieldConfig != null && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                if (suggestionType.equals("facet")) {
                    Element copyElement = new Element("copyField");
                    copyElement.setAttribute("source", fieldName);
                    copyElement.setAttribute("dest", "lmf.spellcheck");
                    schemaNode.addContent(copyElement);
                } else {
                    log.error("suggestionType " + suggestionType + " not supported");
                }
            }
        }

        if (!schemaFile.exists() || schemaFile.canWrite()) {
            FileOutputStream out = new FileOutputStream(schemaFile);

            XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
            xo.output(doc, out);
            out.close();
        } else {
            log.error("schema file {} is not writable", schemaFile);
        }

    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + schemaTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + schemaTemplate, e);
    }

}

From source file:at.newmedialab.lmf.search.services.cores.SolrCoreServiceImpl.java

License:Apache License

/**
 * Create/update the solrconfig.xml file for the given core according to the core configuration.
 *
 * @param engine the solr core configuration
 *//*from ww  w.j  av  a2 s  .co m*/
private void createSolrConfigXml(SolrCoreConfiguration engine) throws MarmottaException {
    File configTemplate = new File(getCoreDirectory(engine.getName()),
            "conf" + File.separator + "solrconfig-template.xml");
    File configFile = new File(getCoreDirectory(engine.getName()), "conf" + File.separator + "solrconfig.xml");

    try {
        SAXBuilder parser = new SAXBuilder(XMLReaders.NONVALIDATING);
        Document solrConfig = parser.build(configTemplate);

        FileOutputStream out = new FileOutputStream(configFile);

        // Configure suggestion service: add fields to suggestion handler
        Program<Value> program = engine.getProgram();
        for (Element handler : solrConfig.getRootElement().getChildren("requestHandler")) {
            if (handler.getAttribute("class").getValue().equals(SuggestionRequestHandler.class.getName())) {
                for (Element lst : handler.getChildren("lst")) {
                    if (lst.getAttribute("name").getValue().equals("defaults")) {
                        //set suggestion fields
                        for (FieldMapping<?, Value> fieldMapping : program.getFields()) {

                            String fieldName = fieldMapping.getFieldName();
                            final Map<String, String> fieldConfig = fieldMapping.getFieldConfig();

                            if (fieldConfig != null
                                    && fieldConfig.keySet().contains(SOLR_SUGGESTION_FIELD_OPTION)) {
                                String suggestionType = fieldConfig.get(SOLR_SUGGESTION_FIELD_OPTION);
                                if (suggestionType.equals("facet")) {
                                    Element field_elem = new Element("str");
                                    field_elem.setAttribute("name", SuggestionRequestParams.SUGGESTION_FIELD);
                                    field_elem.setText(fieldName);
                                    lst.addContent(field_elem);
                                } else {
                                    log.error("suggestionType " + suggestionType + " not supported");
                                }
                            }
                        }
                    }
                }
            }
        }

        XMLOutputter xo = new XMLOutputter(Format.getPrettyFormat().setIndent("    "));
        xo.output(solrConfig, out);
        out.close();
    } catch (JDOMException e) {
        throw new MarmottaException("parse error while parsing SOLR schema template file " + configTemplate, e);
    } catch (IOException e) {
        throw new MarmottaException("I/O error while parsing SOLR schema template file " + configTemplate, e);
    }
}

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Create a new account-Element/*from  ww w. java 2  s .  c om*/
 * 
 * @param entry the AccountEntry
 * @throws JDOMException by Errors with JDOM
 * @throws EntryDoesNotExistException 
 */
private void createAccountElement(AccountEntry entry) throws JDOMException, EntryDoesNotExistException {
    // create Element sub-structure
    Element newAccountElement = new Element("account");
    newAccountElement.setAttribute("id", entry.getId());

    Element newName = new Element("name");
    newName.setText(entry.getName());

    Element newPass = new Element("password");
    newPass.setText(entry.getPassword());

    Element newLink = new Element("link");
    newLink.setText(entry.getLink());

    Element newComment = new Element("comment");
    newComment.setText(entry.getComment());

    // put newPWElement together
    newAccountElement.addContent(newName);
    newAccountElement.addContent(newPass);
    newAccountElement.addContent(newLink);
    newAccountElement.addContent(newComment);

    // add parent
    if (entry.getParentEntry() == null) {
        s_rootElement.addContent(newAccountElement);
    } else {
        try {
            Element parrent = getElement(entry.getParentEntry().getId());
            parrent.addContent(newAccountElement);
        } catch (JDOMException e) {
            logger.fatal(e);
            throw new EntryDoesNotExistException("No such parent");
        }
    }
}

From source file:ataraxis.passwordmanager.XMLHandler.java

License:Open Source License

/**
 * Create a group-Element/*from   w ww  . j  ava  2 s .co  m*/
 * 
 * @param GroupName the Name of the Group (== Element ID)
 */
private void createGroupElement(String GroupName) {

    // Create Element
    Element newGroupElement = new Element("group");
    newGroupElement.setAttribute("id", GroupName);

    // add to root
    s_doc.getRootElement().addContent(newGroupElement);
}

From source file:backtesting.BackTesterNinety.java

private static void SaveSettings(BTSettings settings) {
    BufferedWriter output = null;
    try {//from w  w  w.  j ava 2  s  . c  om
        Element rootElement = new Element("Settings");
        Document doc = new Document(rootElement);
        rootElement.setAttribute("start", settings.startDate.toString());
        rootElement.setAttribute("end", settings.endDate.toString());

        rootElement.setAttribute("capital", Double.toString(settings.capital));
        rootElement.setAttribute("leverage", Double.toString(settings.leverage));

        rootElement.setAttribute("reinvest", Boolean.toString(settings.reinvest));

        XMLOutputter xmlOutput = new XMLOutputter();

        File fileSettings = new File("backtest/cache/_settings.xml");
        fileSettings.createNewFile();
        FileOutputStream oFile = new FileOutputStream(fileSettings, false);

        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, oFile);

    } catch (IOException ex) {
        Logger.getLogger(BackTesterNinety.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:br.com.nfe.util.Chave.java

public void criarChave(String uf, String tpEmis, String nNfe, String cNf, String serie, String AnoMes,
        String cnpj) {//from w  w  w  .  j a  v  a  2  s. c o  m
    this.cNf = cNf;
    Element gerarChave = new Element("gerarChave");
    Document documento = new Document(gerarChave);
    Element UF = new Element("UF");
    UF.setText(uf);

    Element NNFE = new Element("nNF");
    NNFE.setText(nNfe);

    Element CNF = new Element("cNF");
    CNF.setText(cNf);

    Element TPEMIS = new Element("tpEmis");
    TPEMIS.setText(tpEmis);

    Element SERIE = new Element("serie");
    SERIE.setText(serie);

    Element ANOMES = new Element("AAMM");
    ANOMES.setText(AnoMes);

    Element CNPJ = new Element("CNPJ");
    CNPJ.setText(cnpj);

    gerarChave.addContent(UF);
    gerarChave.addContent(TPEMIS);
    gerarChave.addContent(NNFE);
    //gerarChave.addContent(CNF);
    gerarChave.addContent(SERIE);
    gerarChave.addContent(ANOMES);
    gerarChave.addContent(CNPJ);
    XMLOutputter xout = new XMLOutputter();
    try {

        FileWriter arquivo = new FileWriter(
                new File("c:/unimake/uninfe/" + pasta + "/envio/" + cNf + "-gerar-chave.xml"));

        xout.output(documento, arquivo);

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:br.ufrgs.inf.dsmoura.repository.controller.util.XMLUtil.java

public static InputStream fromAssetToRassetXML(Asset asset) {

    // Order by RAS:
    // 1. profile
    // 2. description
    // 3. classification
    // 4. solution
    // 5. usage//w  ww.j a  v a2  s .  com
    // 6. relatedAsset

    /* GENERAL */

    Element ecp = new Element("Asset");
    ecp.setAttribute("name", asset.getName());
    ecp.setAttribute("id", asset.getId());
    if (asset.getType() != null) {
        ecp.setAttribute("type", asset.getType().getName());
        if (FieldsUtil.isValidType(asset.getType()) && asset.getType().getName().equalsIgnoreCase("Other")) {
            ecp.setAttribute("other_type", asset.getOtherType());
        }
    }
    if (asset.getState() != null) {
        ecp.setAttribute("state", asset.getState().getName());
    }
    if (asset.getSoftwareLicenseDTO() != null) {
        ecp.setAttribute("software_license", asset.getSoftwareLicenseDTO().getName());
        if (FieldsUtil.isValidSoftwareLicense(asset.getSoftwareLicenseDTO())
                && asset.getSoftwareLicenseDTO().getName().equalsIgnoreCase("Other")) {
            ecp.setAttribute("other_software_license", asset.getOtherSoftwareLicense());
        }
    }
    ecp.setAttribute("version", asset.getVersion());
    ecp.setAttribute("date", asset.getStrDate());
    ecp.setAttribute("creation_date", asset.getStrCreationDate());
    ecp.setAttribute("access_rights", asset.getAccessRights());
    ecp.setAttribute("short_description", asset.getShortDescription());

    Element description = new Element("description");
    description.addContent(asset.getDescription());
    ecp.addContent(description);

    /* CLASSIFICATION */

    Element classification = new Element("classification");
    ecp.addContent(classification);

    /* Application Domains */
    for (ApplicationSubdomain as : asset.getClassification().getApplicationSubdomains()) {
        Element applicationSubdomain = new Element("application_subdomain");
        applicationSubdomain.setAttribute("name", as.getName());

        Element applicationDomain = new Element("application_domain");
        applicationDomain.setAttribute("name", as.getApplicationDomain().getName());

        if (FieldsUtil.isValidApplicationSubdomain(as) && as.getName().equalsIgnoreCase("Other")) {
            applicationDomain.setAttribute("name", asset.getClassification().getOtherApplicationDomain());
            applicationSubdomain.setAttribute("name", asset.getClassification().getOtherApplicationSubdomain());
        }

        applicationSubdomain.addContent(applicationDomain);
        classification.addContent(applicationSubdomain);
    }

    /* Projects */
    for (ProjectDTO proj : asset.getClassification().getProjectDTOs()) {
        Element project = new Element("project");
        project.setAttribute("name", proj.getName());
        classification.addContent(project);

        Element organization = new Element("organization");
        organization.setAttribute("name", proj.getOrganizationDTO().getName());
        project.addContent(organization);
    }

    /* Tags */
    for (TagDTO t : asset.getClassification().getTagDTOs()) {
        Element tag = new Element("tag");
        tag.setAttribute("name", t.getName());
        classification.addContent(tag);
    }

    /* Group Descriptors */
    for (DescriptorGroupDTO groupDTO : asset.getClassification().getDescriptorGroupDTOs()) {
        Element group = new Element("descriptor_group");
        group.setAttribute("name", groupDTO.getName());
        classification.addContent(group);
        /* Descriptors */
        for (FreeFormDescriptorDTO descriptorDTO : groupDTO.getFreeFormDescriptorDTOs()) {
            Element descriptor = new Element("free_form_escriptor");
            descriptor.setAttribute("name", descriptorDTO.getName());
            descriptor.setAttribute("value", descriptorDTO.getFreeFormValue());
            group.addContent(descriptor);
        }
    }

    /* SOLUTION */

    Element solution = new Element("solution");
    ecp.addContent(solution);

    /* EFFORT */
    Element effort = new Element("effort");
    solution.addContent(effort);
    if (asset.getEffortDTO().getEstimatedTime() != null) {
        effort.setAttribute("estimated_time", asset.getEffortDTO().getEstimatedTime().toString());
    }
    if (asset.getEffortDTO().getRealTime() != null) {
        effort.setAttribute("real_time", asset.getEffortDTO().getRealTime().toString());
    }
    if (asset.getEffortDTO().getMonetary() != null) {
        effort.setAttribute("monetary", asset.getEffortDTO().getMonetary().toString());
    }
    if (asset.getEffortDTO().getTeamMembers() != null) {
        effort.setAttribute("team_members", asset.getEffortDTO().getTeamMembers().toString());
    }
    if (asset.getEffortDTO().getLinesOfCode() != null) {
        effort.setAttribute("linesOfCode", asset.getEffortDTO().getLinesOfCode().toString());
    }

    /* REQUIREMENTS */
    Element requirements = new Element("requirements");
    solution.addContent(requirements);

    requirements.addContent(
            fromArtifactsToElements(asset.getSolution().getRequirements().getFunctionalRequirementDTOs(),
                    RequirementsMB.FUNCTIONAL_REQ_REFERENCE_PATH));

    requirements.addContent(fromArtifactsToElements(asset.getSolution().getRequirements().getUseCaseDTOs(),
            RequirementsMB.USE_CASE_REFERENCE_PATH));

    requirements
            .addContent(fromArtifactsToElements(asset.getSolution().getRequirements().getUserInterfaceDTOs(),
                    RequirementsMB.USER_INTERFACE_REFERENCE_PATH));

    requirements.addContent(
            fromArtifactsToElements(asset.getSolution().getRequirements().getNonFunctionalRequirementDTOs(),
                    RequirementsMB.NON_FUNCTIONAL_REQ_REFERENCE_PATH));

    /* Internationalization */
    for (InternationalizationTypeDTO i : asset.getSolution().getRequirements()
            .getInternationalizationTypeDTOs()) {
        Element internat = new Element("language");
        internat.setAttribute("name", i.getName());
        requirements.addContent(internat);
    }

    /* Operational Systems */
    for (OperationalSystemTypeDTO o : asset.getSolution().getRequirements().getOperationalSystemTypeDTOs()) {
        Element operSyst = new Element("operational_system");
        operSyst.setAttribute("name", o.getName());
        requirements.addContent(operSyst);
    }

    /* ANALYSIS */

    Element analysis = new Element("analysis");
    solution.addContent(analysis);

    /* Interface Specs */
    for (InterfaceSpecDTO intSpecDTO : asset.getSolution().getAnalysis().getInterfaceSpecDTOs()) {
        Element interfaceSpec = new Element("interface_spec");
        if (intSpecDTO.getDescription() != null) {
            interfaceSpec.setAttribute("description", intSpecDTO.getDescription());
        }
        interfaceSpec.setAttribute("name", intSpecDTO.getName());
        analysis.addContent(interfaceSpec);
        /* Descriptors */
        for (OperationDTO operationDTO : intSpecDTO.getOperationDTOs()) {
            Element operation = new Element("operation");
            operation.setAttribute("name", operationDTO.getName());
            operation.setAttribute("initiates_transaction", operationDTO.getInitiatesTransaction().toString());
            if (operationDTO.getDescription() != null) {
                operation.setAttribute("description", operationDTO.getDescription());
            }
            interfaceSpec.addContent(operation);
        }
    }

    /* Use Case */
    analysis.addContent(fromArtifactsToElements(asset.getSolution().getAnalysis().getUseCaseDTOs(),
            AnalysisMB.USE_CASE_REFERENCE_PATH));

    /* User Interfaces */
    analysis.addContent(fromArtifactsToElements(asset.getSolution().getAnalysis().getUserInterfaceDTOs(),
            AnalysisMB.USER_INTERFACE_REFERENCE_PATH));

    /* General Artifacts */
    analysis.addContent(fromArtifactsToElements(asset.getSolution().getAnalysis().getArtifactDTOs(),
            AnalysisMB.GENERAL_ARTIFACT_REFERENCE_PATH));

    /* DESIGN */

    Element design = new Element("design");
    solution.addContent(design);

    /* Interface Specs */
    for (InterfaceSpecDTO intSpecDTO : asset.getSolution().getDesign().getInterfaceSpecDTOs()) {
        Element interfaceSpec = new Element("interface_spec");
        interfaceSpec.setAttribute("name", intSpecDTO.getName());
        if (intSpecDTO.getDescription() != null) {
            interfaceSpec.setAttribute("description", intSpecDTO.getDescription());
        }
        design.addContent(interfaceSpec);
        /* Descriptors */
        for (OperationDTO operationDTO : intSpecDTO.getOperationDTOs()) {
            Element operation = new Element("operation");
            operation.setAttribute("name", operationDTO.getName());
            operation.setAttribute("initiates_transaction", operationDTO.getInitiatesTransaction().toString());
            if (operationDTO.getDescription() != null) {
                operation.setAttribute("description", operationDTO.getDescription());
            }
            interfaceSpec.addContent(operation);
        }
    }
    /* Design Patterns */
    for (DesignPatternDTO dp : asset.getSolution().getDesign().getDesignPatternDTOs()) {
        Element designPat = new Element("design_pattern");
        designPat.setAttribute("name", dp.getName());
        design.addContent(designPat);
    }

    /* User Interfaces */
    design.addContent(fromArtifactsToElements(asset.getSolution().getDesign().getUserInterfaceDTOs(),
            DesignMB.USER_INTERFACE_REFERENCE_PATH));

    /* General Artifacts */
    design.addContent(fromArtifactsToElements(asset.getSolution().getDesign().getArtifactDTOs(),
            DesignMB.GENERAL_ARTIFACT_REFERENCE_PATH));

    /* IMPLEMENTATION */

    Element implementation = new Element("implementation");
    solution.addContent(implementation);

    /* Programming Languages */
    for (ProgrammingLanguageDTO pl : asset.getSolution().getImplementation().getProgrammingLanguageDTOs()) {
        Element progLang = new Element("programming_language");
        progLang.setAttribute("name", pl.getName());
        if (FieldsUtil.isValidProgrammingLanguage(pl) && pl.getName().equalsIgnoreCase("Other")) {
            progLang.setAttribute("other_name",
                    asset.getSolution().getImplementation().getOtherProgrammingLanguage());
        }
        implementation.addContent(progLang);
    }

    /* Design Patterns */
    for (DesignPatternDTO dp : asset.getSolution().getImplementation().getDesignPatternDTOs()) {
        Element designPat = new Element("design_pattern");
        designPat.setAttribute("name", dp.getName());
        implementation.addContent(designPat);
    }

    /* Source Codes */
    implementation
            .addContent(fromArtifactsToElements(asset.getSolution().getImplementation().getSourceCodeDTOs(),
                    ImplementationMB.SOURCE_CODE_REFERENCE_PATH));

    /* User Interfaces */
    implementation
            .addContent(fromArtifactsToElements(asset.getSolution().getImplementation().getUserInterfaceDTOs(),
                    ImplementationMB.USER_INTERFACE_REFERENCE_PATH));

    /* WSDL */
    implementation.addContent(fromArtifactsToElements(asset.getSolution().getImplementation().getWsdlDTOs(),
            ImplementationMB.WSDL_REFERENCE_PATH));

    /* General Artifacts */
    implementation.addContent(fromArtifactsToElements(asset.getSolution().getImplementation().getArtifactDTOs(),
            ImplementationMB.GENERAL_ARTIFACT_REFERENCE_PATH));

    /* TEST */
    Element test = new Element("test");
    solution.addContent(test);

    /* Test Type */
    for (TestTypeDTO tt : asset.getSolution().getTest().getTestTypeDTOs()) {
        Element testMethod = new Element("test_type");
        testMethod.setAttribute("name", tt.getName());
        test.addContent(testMethod);
    }

    /* Test Method Type */
    for (TestMethodTypeDTO tmt : asset.getSolution().getTest().getTestMethodTypeDTOs()) {
        Element testMethod = new Element("test_method_type");
        testMethod.setAttribute("name", tmt.getName());
        test.addContent(testMethod);
    }

    /* Programming Languages */
    for (ProgrammingLanguageDTO pl : asset.getSolution().getTest().getProgrammingLanguageDTOs()) {
        Element progLang = new Element("programming_language");
        progLang.setAttribute("name", pl.getName());
        if (FieldsUtil.isValidProgrammingLanguage(pl) && pl.getName().equalsIgnoreCase("Other")) {
            progLang.setAttribute("other_name", asset.getSolution().getTest().getOtherProgrammingLanguage());
        }
        test.addContent(progLang);
    }

    /* Design Patterns */
    for (DesignPatternDTO dp : asset.getSolution().getTest().getDesignPatternDTOs()) {
        Element designPat = new Element("design_pattern");
        designPat.setAttribute("name", dp.getName());
        test.addContent(designPat);
    }

    /* Source Codes */
    test.addContent(fromArtifactsToElements(asset.getSolution().getTest().getSourceCodeDTOs(),
            TestMB.SOURCE_CODE_REFERENCE_PATH));

    /* General Artifacts */
    test.addContent(fromArtifactsToElements(asset.getSolution().getTest().getArtifactDTOs(),
            TestMB.GENERAL_ARTIFACT_REFERENCE_PATH));

    /* USAGE */

    Element usage = new Element("usage");
    ecp.addContent(usage);

    Element usageDescription = new Element("description");
    usageDescription.addContent(asset.getUsage().getDescription());
    usage.addContent(usageDescription);

    usage.addContent(fromArtifactsToElements(asset.getUsage().getArtifactDTOs(),
            UsageMB.GENERAL_ARTIFACT_REFERENCE_PATH));

    /* Author User */
    Element author = new Element("author");
    author.setAttribute("username", asset.getUsage().getAuthorUserDTO().getUsername());
    author.setAttribute("name", asset.getUsage().getAuthorUserDTO().getName());
    usage.addContent(author);

    usage.setAttribute("authorship_date", asset.getUsage().getStrAuthorshipDate());

    usage.setAttribute("creator_name", asset.getUsage().getCreatorUsername());

    /* Certifier User */
    if (asset.getUsage().getCertifierUserDTO() != null) {
        Element certifier = new Element("certifier");
        certifier.setAttribute("username", asset.getUsage().getCertifierUserDTO().getUsername());
        certifier.setAttribute("name", asset.getUsage().getCertifierUserDTO().getName());
        usage.addContent(certifier);
    }
    if (asset.getUsage().getCertificationDate() != null) {
        usage.setAttribute("certification_date", asset.getUsage().getStrCertificationDate());
    }

    /* Feedbacks */
    for (FeedbackDTO feedbackDTO : asset.getFeedbackDTOs()) {
        if (feedbackDTO.getHasFeedback()) {
            Element feedback = new Element("feedback");
            feedback.setAttribute("date", feedbackDTO.getStrDate());
            feedback.setAttribute("comment", feedbackDTO.getComment());

            /* Feedback User */
            Element user = new Element("feedback_user");
            user.setAttribute("username", feedbackDTO.getFeedbackUserDTO().getUsername());
            user.setAttribute("name", feedbackDTO.getFeedbackUserDTO().getName());
            feedback.addContent(user);

            /* Scores */
            feedback.setAttribute("general_score", feedbackDTO.getGeneralScore().toString());

            Element qualityInUse = new Element("quality_in_use");
            if (feedbackDTO.getQualityInUseDTO().getContextCoverageScore() != null) {
                qualityInUse.setAttribute("context_coverage_score",
                        feedbackDTO.getQualityInUseDTO().getContextCoverageScore().toString());
            }
            if (feedbackDTO.getQualityInUseDTO().getEfficiencyScore() != null) {
                qualityInUse.setAttribute("efficiency_score",
                        feedbackDTO.getQualityInUseDTO().getEfficiencyScore().toString());
            }
            if (feedbackDTO.getQualityInUseDTO().getEffectivenessScore() != null) {
                qualityInUse.setAttribute("effectiveness_score",
                        feedbackDTO.getQualityInUseDTO().getEffectivenessScore().toString());
            }
            if (feedbackDTO.getQualityInUseDTO().getSafetyScore() != null) {
                qualityInUse.setAttribute("safety_score",
                        feedbackDTO.getQualityInUseDTO().getSafetyScore().toString());
            }
            if (feedbackDTO.getQualityInUseDTO().getSatisfactionScore() != null) {
                qualityInUse.setAttribute("satisfaction_score",
                        feedbackDTO.getQualityInUseDTO().getSatisfactionScore().toString());
            }
            feedback.addContent(qualityInUse);

            Element softProdQuality = new Element("software_product_quality");
            if (feedbackDTO.getSoftwareProductQualityDTO().getCompatibilityScore() != null) {
                softProdQuality.setAttribute("compatibility_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getCompatibilityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getFunctionalSuitabilityScore() != null) {
                softProdQuality.setAttribute("functional_suitability_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getFunctionalSuitabilityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getMaintainabilityScore() != null) {
                softProdQuality.setAttribute("maintainability_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getMaintainabilityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getPerformanceEfficiencyScore() != null) {
                softProdQuality.setAttribute("performance_efficiency_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getPerformanceEfficiencyScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getPortabilityScore() != null) {
                softProdQuality.setAttribute("portability_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getPortabilityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getReliabilityScore() != null) {
                softProdQuality.setAttribute("reliability_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getReliabilityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getSecurityScore() != null) {
                softProdQuality.setAttribute("security_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getSecurityScore().toString());
            }
            if (feedbackDTO.getSoftwareProductQualityDTO().getUsabilityScore() != null) {
                softProdQuality.setAttribute("usability_score",
                        feedbackDTO.getSoftwareProductQualityDTO().getUsabilityScore().toString());
            }
            feedback.addContent(softProdQuality);

            usage.addContent(feedback);
        }
    }

    /* Adjustments */
    for (AdjustmentDTO adjustmentDTO : asset.getUsage().getAdjustmentDTOs()) {
        Element adjustment = new Element("adjustment");
        adjustment.setAttribute("date", adjustmentDTO.getStrDate());
        Element user = new Element("adjuster_user");
        user.setAttribute("username", adjustmentDTO.getAdjusterUserDTO().getUsername());
        user.setAttribute("name", adjustmentDTO.getAdjusterUserDTO().getName());
        adjustment.addContent(user);
        Element adjustmentDescription = new Element("description");
        adjustmentDescription.addContent(adjustmentDTO.getDescription());
        adjustment.addContent(adjustmentDescription);
        usage.addContent(adjustment);
    }

    /* Consumptions */
    for (ConsumptionDTO consumptionDTO : asset.getUsage().getConsumptionDTOs()) {
        Element consumption = new Element("consumption");
        consumption.setAttribute("date", consumptionDTO.getStrDate());
        Element user = new Element("comsumer_user");
        user.setAttribute("username", consumptionDTO.getConsumerUserDTO().getUsername());
        user.setAttribute("name", consumptionDTO.getConsumerUserDTO().getName());
        consumption.addContent(user);
        usage.addContent(consumption);
    }

    /* User Comments */
    for (UserCommentDTO userCommentDTO : asset.getUsage().getUserCommentDTOs()) {
        Element consumption = new Element("user_comment");
        consumption.setAttribute("date", userCommentDTO.getStrDate());
        Element user = new Element("user");
        user.setAttribute("username", userCommentDTO.getUserDTO().getUsername());
        user.setAttribute("name", userCommentDTO.getUserDTO().getName());
        consumption.addContent(user);
        Element comment = new Element("comment");
        comment.addContent(userCommentDTO.getComment());
        consumption.addContent(comment);
        usage.addContent(consumption);
    }

    /* RELATED ASSETS */

    Element relatedAssets = new Element("related_assets");
    ecp.addContent(relatedAssets);
    for (RelatedAsset ra : asset.getRelatedAssets()) {
        Element relatedAsset = new Element("related_asset");
        relatedAsset.setAttribute("id", ra.getId());
        relatedAsset.setAttribute("name", ra.getName());
        relatedAsset.setAttribute("version", ra.getVersion());
        relatedAsset.setAttribute("reference", ra.getReference());
        if (ra.getRelatedAssetTypeDTO() != null) {
            relatedAsset.setAttribute("relationshipType", ra.getRelatedAssetTypeDTO().getName());
        }
        relatedAssets.addContent(relatedAsset);
    }

    /* Generate XML */
    Document doc = new Document();
    doc.setRootElement(ecp);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
    try {
        xmlOut.output(doc, outputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

    return is;
}