Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

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

Prototype

public XMLOutputter(XMLOutputProcessor processor) 

Source Link

Document

This will create an XMLOutputter with the specified XMLOutputProcessor.

Usage

From source file:sxql.java

License:Open Source License

/**
 * Execute a SQL query and return the result as XML
 * (as a String. But this can be changed to return a DOM/SAX/JDOM tree,
 * to be used, for example, as input to an XSLT processor)
 *///from   w  ww  .  ja v a2s.  c o  m
public static String query(Connection con, String query, String root, String row, String ns, int maxRows,
        Vector<String> attributes, Vector<String> elements) throws Exception {
    // Execute SQL Query
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(query);

    // Create a ResultSetBuilder
    ResultSetBuilder builder = new ResultSetBuilder(rs);

    // Configure some parameters...

    if (root != null) {
        builder.setRootName(root);
    }

    if (row != null) {
        builder.setRowName(row);
    }

    if (ns != null) {
        String namespace = null;
        String url = null;
        int sep = ns.indexOf("/");

        if (sep > 0) {
            namespace = ns.substring(0, sep);
            url = ns.substring(sep + 1);
            builder.setNamespace(Namespace.getNamespace(namespace, url));
        }
    }

    if (maxRows > 0) {
        builder.setMaxRows(maxRows);
    }

    for (int i = 0; i < attributes.size(); i++) {
        String colName = attributes.get(i);
        String attrName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            attrName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (attrName == null) {
                builder.setAsAttribute(colNum); // attrName = column Name
            } else {
                builder.setAsAttribute(colNum, attrName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (attrName == null) {
                builder.setAsAttribute(colName); // attrName = column Name
            } else {
                builder.setAsAttribute(colName, attrName);
            }
        }
    }

    // Rename element
    for (int i = 0; i < elements.size(); i++) {
        String colName = elements.get(i);
        String elemName = null;

        if (colName.indexOf("/") >= 0) {
            String col = colName;
            int sep = col.indexOf("/");
            colName = col.substring(0, sep);
            elemName = col.substring(sep + 1);
        }

        try { // If it looks like an integer, is the column number
            int colNum = Integer.parseInt(colName);

            if (elemName != null) { // It must have an element name
                builder.setAsElement(colNum, elemName);
            }
        } catch (NumberFormatException e) {
            // Otherwise it's the column name
            if (elemName != null) { // It must have an element name
                builder.setAsElement(colName, elemName);
            }
        }
    }

    // Build a JDOM tree
    Document doc = builder.build();

    // Convert the result to XML (as String)
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    outputter.output(doc, output);
    return output.toString();
}

From source file:app.simulation.Exporter.java

License:MIT License

public void exportXML() throws Exception {
    Element root = new Element("simulation");
    Document document = new Document(root);

    if (configuration != null) {
        Element tagConfiguration = new Element("configuration");

        Element delay = new Element("delay");
        delay.setText(String.format("%s", configuration.getDelay()));

        Element iterations = new Element("iterations");
        iterations.setText(String.format("%s", configuration.getIterations()));

        Element agents = new Element("agents");
        agents.setText(String.format("%s", configuration.getAgents()));

        Element latticeSize = new Element("latticeSize");
        latticeSize.setText(String.format("%s", configuration.getLatticeSize()));

        Element description = new Element("description");
        description.setText(String.format("%s", configuration.getDescription()));

        tagConfiguration.addContent(delay);
        tagConfiguration.addContent(iterations);
        tagConfiguration.addContent(agents);
        tagConfiguration.addContent(latticeSize);
        tagConfiguration.addContent(description);

        root.addContent(tagConfiguration);
    }/*from  www . j av  a 2  s. c  o m*/

    if (initialCell != null) {
        Element tagInitialCell = new Element("initialCell");

        Element x = new Element("x");
        x.setText(String.format("%s", initialCell.getX()));

        Element y = new Element("y");
        y.setText(String.format("%s", initialCell.getY()));

        Element z = new Element("z");
        z.setText(String.format("%s", initialCell.getZ()));

        Element state = new Element("state");
        state.setText(String.format("%s", initialCell.getState()));

        Element color = new Element("color");

        Element r = new Element("r");
        r.setText(String.format("%s", initialCell.getColor().getRed()));

        Element g = new Element("g");
        g.setText(String.format("%s", initialCell.getColor().getGreen()));

        Element b = new Element("b");
        b.setText(String.format("%s", initialCell.getColor().getBlue()));

        color.addContent(r);
        color.addContent(g);
        color.addContent(b);

        tagInitialCell.addContent(x);
        tagInitialCell.addContent(y);
        tagInitialCell.addContent(z);
        tagInitialCell.addContent(state);
        tagInitialCell.addContent(color);

        root.addContent(tagInitialCell);
    }

    if (rules != null) {
        Element tagRules = new Element("rules");

        for (Rule rule : rules) {
            Element tagRule = new Element("rule");

            Element neighbourhood = new Element("neighbourhood");
            neighbourhood.setText(rule.getNeighbourhood());

            Element state = new Element("state");
            state.setText(String.format("%s", rule.getState()));

            Element color = new Element("color");

            Element r = new Element("r");
            r.setText(String.format("%s", rule.getColor().getRed()));

            Element g = new Element("g");
            g.setText(String.format("%s", rule.getColor().getGreen()));

            Element b = new Element("b");
            b.setText(String.format("%s", rule.getColor().getBlue()));

            color.addContent(r);
            color.addContent(g);
            color.addContent(b);

            tagRule.addContent(neighbourhood);
            tagRule.addContent(state);
            tagRule.addContent(color);

            tagRules.addContent(tagRule);
        }

        root.addContent(tagRules);
    }

    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    outputter.output(document, new FileWriter(path));
}

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
 *///from  w  w  w . ja  va 2  s . 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
 *//* ww  w  . j a v a 2 s  .c  om*/
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

/**
 * Save the File encrypted to the disk./*from   w w w  . ja v  a 2  s.c om*/
 *
 * @throws StorageException 
 */
public void savePasswords() throws StorageException {
    try {
        OutputStream out = getAccountFileOutputStream();

        XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());
        serializer.output(s_doc, out);
        //serializer.output(s_doc,System.out);
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.fatal(e);
        throw new StorageException(e);
    }
}

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/*from w  w  w . j a v  a2 s.  co m*/
    // 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;
}

From source file:broadwick.graph.writer.GraphMl.java

License:Apache License

/**
 * Get the string representation of the network.
 * @param network  the network object to be written.
 * @param directed a boolean flag, true if the network is directed.
 * @return a string representing a document.
 */// ww  w  .  j  ava  2  s  .co  m
public static String toString(final Graph<? extends Vertex, ? extends Edge<?>> network,
        final boolean directed) {
    // graphml document header
    final Element graphml = new Element("graphml", "http://graphml.graphdrawing.org/xmlns");
    final Document document = new Document(graphml);
    final Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    final Namespace schemLocation = Namespace.getNamespace("schemLocation",
            "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0rc/graphml.xsd");

    // add Namespace
    graphml.addNamespaceDeclaration(xsi);
    graphml.addNamespaceDeclaration(schemLocation);

    // keys for graphic representation
    for (VertexAttribute attr : network.getVertexAttributes()) {
        final Element element = new Element("key");
        element.setAttribute("id", attr.getName());
        element.setAttribute("for", "node");
        element.setAttribute("attr.name", attr.getName());
        element.setAttribute("attr.type", attr.getType().getName());
        if (attr.getDefaultValue() != null) {
            final Element defaultValueElement = new Element("default");
            defaultValueElement.addContent(attr.getDefaultValue().toString());
            element.addContent(defaultValueElement);
        }
        graphml.addContent(element);
    }

    for (EdgeAttribute attr : network.getEdgeAttributes()) {
        final Element element = new Element("key");
        element.setAttribute("id", attr.getName());
        element.setAttribute("for", "edge");
        element.setAttribute("attr.name", attr.getName());
        element.setAttribute("attr.type", attr.getType().getName());
        if (attr.getDefaultValue() != null) {
            final Element defaultValueElement = new Element("default");
            defaultValueElement.addContent(attr.getDefaultValue());
            element.addContent(defaultValueElement);
        }
        graphml.addContent(element);
    }

    final Element graph = new Element("graph");
    graph.setAttribute("id", "G");
    if (directed) {
        graph.setAttribute("edgedefault", "directed");
    } else {
        graph.setAttribute("edgedefault", "undirected");
    }
    graphml.addContent(graph);

    final ImmutableList<Vertex> vertices = ImmutableList.copyOf(network.getVertices());
    final Iterator<Vertex> vertexIterator = vertices.iterator();
    while (vertexIterator.hasNext()) {
        final Vertex vertex = vertexIterator.next();
        addNode(vertex, graph);
    }

    final ImmutableList<Edge<? extends Vertex>> edges;
    edges = (ImmutableList<Edge<? extends Vertex>>) ImmutableList.copyOf(network.getEdges());
    final UnmodifiableIterator<Edge<? extends Vertex>> edgeIterator = edges.iterator();
    while (edgeIterator.hasNext()) {
        addEdge(edgeIterator.next(), graph);
    }

    final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    return outputter.outputString(document).replaceAll("xmlns=\"\" ", "");
}

From source file:by.epam.lw05.xml.ListToXml.java

private static void documentToXML(Document doc, String path) {

    Format format = Format.getPrettyFormat();
    format.setEncoding("UTF-8");
    XMLOutputter outputter = new XMLOutputter(format);
    try {/*from  w  ww. j  a v  a 2 s  . c o m*/
        outputter.output(doc, new FileOutputStream(path));
    } catch (FileNotFoundException ex) {
    } catch (IOException ex) {
    }

}

From source file:ca.nrc.cadc.tap.writer.RssTableWriter.java

License:Open Source License

@Override
public void write(ResultSet resultSet, Writer out, Long maxrec) throws IOException {
    if (selectList == null)
        throw new IllegalStateException("SelectList cannot be null, set using setSelectList()");

    List<Format<Object>> formats = formatFactory.getFormats(selectList);

    if (resultSet != null)
        try {/* w ww .j  a va 2 s  . c  o m*/
            log.debug("resultSet column count: " + resultSet.getMetaData().getColumnCount());
        } catch (Exception oops) {
            log.error("failed to check resultset column count", oops);
        }

    // JDOM document.
    Document document = new Document();

    // Root element.
    Element rss = new Element("rss");
    rss.setAttribute("version", "2.0");
    document.setRootElement(rss);

    // channel element.
    Element channel = new Element("channel");
    rss.addContent(channel);

    // channel title.
    Element channelTitle = new Element("title");
    channelTitle.setText(info);
    channel.addContent(channelTitle);

    StringBuilder qp = new StringBuilder();
    qp.append("http://");
    qp.append(NetUtil.getServerName(null));
    qp.append(job.getRequestPath());
    qp.append("?");
    for (Parameter parameter : job.getParameterList()) {
        qp.append(parameter.getName());
        qp.append("=");
        qp.append(parameter.getValue());
        qp.append("&");
    }
    String queryString = qp.substring(0, qp.length() - 1); // strip trailing &
    Element link = new Element("link");
    link.setText(queryString);
    channel.addContent(link);

    // items.
    int itemCount = 0;
    try {
        while (resultSet.next()) {
            // item element.
            Element item = new Element("item");

            // item description.
            Element itemDescription = new Element("description");
            StringBuilder sb = new StringBuilder();
            sb.append("<table>");

            // Loop through the ResultSet adding the table data elements.
            for (int columnIndex = 1; columnIndex <= resultSet.getMetaData().getColumnCount(); columnIndex++) {
                String columnLabel = resultSet.getMetaData().getColumnLabel(columnIndex);

                if (columnLabel.equalsIgnoreCase("rss_title")) {
                    String titleStr = resultSet.getString("rss_title");
                    log.debug("item title: " + titleStr);
                    Element itemTitle = new Element("title");
                    itemTitle.setText(titleStr);
                    item.addContent(itemTitle);
                } else if (columnLabel.equalsIgnoreCase("rss_link")) {
                    String linkStr = resultSet.getString("rss_link");
                    log.debug("item link: " + linkStr);
                    Element itemLink = new Element("link");
                    itemLink.setText(linkStr);
                    item.addContent(itemLink);
                } else if (columnLabel.equalsIgnoreCase("rss_pubDate")) {
                    Timestamp ts = resultSet.getTimestamp("rss_pubDate");
                    String pubDateStr = dateFormat.format(ts);
                    log.debug("item pubDate: " + pubDateStr);
                    Element itemPubDate = new Element("pubDate");
                    itemPubDate.setText(pubDateStr);
                    item.addContent(itemPubDate);
                } else {
                    ParamDesc paramDesc = selectList.get(columnIndex - 1);
                    sb.append("<tr><td align=\"right\">");
                    sb.append(paramDesc.name);
                    sb.append("</td><td align=\"left\">");
                    Format<Object> format = formats.get(columnIndex - 1);
                    Object obj = null;
                    if (format instanceof ResultSetFormat)
                        obj = ((ResultSetFormat) format).extract(resultSet, columnIndex);
                    else
                        obj = resultSet.getObject(columnIndex);
                    sb.append(format.format(obj));
                    sb.append("</td></tr>");
                }
            }
            sb.append("</table>");
            itemDescription.setText(sb.toString());
            item.addContent(itemDescription);
            channel.addContent(item);
            itemCount++;

            // Write MaxRows
            if (itemCount == maxrec)
                break;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage());
    }

    // channel description.
    Element channelDescription = new Element("description");
    channelDescription.setText("The " + itemCount + " most recent from " + info);
    channel.addContent(channelDescription);

    // Write out the VOTABLE.
    XMLOutputter outputter = new XMLOutputter(org.jdom2.output.Format.getPrettyFormat());
    outputter.output(document, out);

}

From source file:ca.nrc.cadc.vosi.TableSetWriter.java

License:Open Source License

public void write(TapSchema ts, Writer writer) throws IOException {
    TableSet tset = new TableSet(ts);
    Document doc = tset.getDocument();
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(doc, writer);/*w ww.  jav a 2  s. c o  m*/
}