Example usage for org.jdom2.output Format getPrettyFormat

List of usage examples for org.jdom2.output Format getPrettyFormat

Introduction

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

Prototype

public static Format getPrettyFormat() 

Source Link

Document

Returns a new Format object that performs whitespace beautification with 2-space indents, uses the UTF-8 encoding, doesn't expand empty elements, includes the declaration and encoding, and uses the default entity escape strategy.

Usage

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   w  w w. ja  v  a2s  .  c o  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

/**
 * Save the File encrypted to the disk.//w  w w. j  a  va2s  .  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:backtesting.BackTesterNinety.java

private static void SaveSettings(BTSettings settings) {
    BufferedWriter output = null;
    try {//from ww w  . j  a  v a2 s.c o m
        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.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//ww w.  j  av a 2  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.
 *//*w w  w.ja  v a 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 {/* w  ww.  ja  v a  2 s.co  m*/
        outputter.output(doc, new FileOutputStream(path));
    } catch (FileNotFoundException ex) {
    } catch (IOException ex) {
    }

}

From source file:ca.nrc.cadc.ac.xml.AbstractReaderWriter.java

License:Open Source License

/**
 * Write to root Element to a writer.//  www .j  a  va 2s  .  c  o m
 *
 * @param root Root Element to write.
 * @param writer Writer to write to.
 * @throws IOException if the writer fails to write.
 */
protected void write(Element root, Writer writer) throws IOException {
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat());
    outputter.output(new Document(root), writer);
}

From source file:ca.nrc.cadc.caom2.xml.ArtifactAccessWriter.java

License:Open Source License

public void write(ArtifactAccess aa, Writer writer) throws IOException {
    Element root = new Element(ArtifactAccessReader.ENAMES.artifactAccess.name());

    Element ae = new Element(ArtifactAccessReader.ENAMES.artifact.name());
    root.addContent(ae);/*from   w  w w .  j  a  v  a  2s. c om*/

    addChild(ae, ArtifactAccessReader.ENAMES.uri.name(), aa.getArtifact().getURI().toASCIIString());
    addChild(ae, ArtifactAccessReader.ENAMES.productType.name(), aa.getArtifact().getProductType().getValue());
    addChild(ae, ArtifactAccessReader.ENAMES.releaseType.name(), aa.getArtifact().getReleaseType().getValue());
    if (aa.getArtifact().contentChecksum != null) {
        addChild(ae, ArtifactAccessReader.ENAMES.contentChecksum.name(),
                aa.getArtifact().contentChecksum.toASCIIString());
    }
    if (aa.getArtifact().contentLength != null) {
        addChild(ae, ArtifactAccessReader.ENAMES.contentLength.name(),
                aa.getArtifact().contentLength.toString());
    }
    if (aa.getArtifact().contentType != null) {
        addChild(ae, ArtifactAccessReader.ENAMES.contentType.name(), aa.getArtifact().contentType);
    }

    Element pub = new Element(ArtifactAccessReader.ENAMES.isPublic.name());
    pub.setText(Boolean.toString(aa.isPublic));
    root.addContent(pub);

    Element rg = new Element(ArtifactAccessReader.ENAMES.readGroups.name());
    if (!aa.getReadGroups().isEmpty() || writeEmptyCollections) {
        root.addContent(rg);
    }
    addGroups(aa.getReadGroups(), rg);

    Document doc = new Document(root);
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat());
    outputter.output(doc, writer);
}

From source file:ca.nrc.cadc.caom2.xml.JsonWriter.java

License:Open Source License

/**
 * Write the root Element to a writer./*from w  w w . j  a v  a 2  s .c  o  m*/
 *
 * @param root
 *            Root Element to write.
 * @param writer
 *            Writer to write to.
 * @throws IOException
 *             if the writer fails to write.
 */
@Override
protected void write(Element root, Writer writer) throws IOException {
    JsonOutputter outputter = new JsonOutputter();
    outputter.getListElementNames().add("planes");
    outputter.getListElementNames().add("artifacts");
    outputter.getListElementNames().add("parts");
    outputter.getListElementNames().add("vertices");
    outputter.getListElementNames().add("points");
    outputter.getListElementNames().add("inputs");
    outputter.getListElementNames().add("states");
    outputter.getListElementNames().add("samples");
    outputter.getListElementNames().add("members");
    if (docVersion >= 23) {
        outputter.getListElementNames().add("keywords");
    }

    outputter.getStringElementNames().add("observationID");
    outputter.getStringElementNames().add("productID");
    outputter.getStringElementNames().add("sequenceNumber");
    outputter.getStringElementNames().add("name"); // anything with a name

    Format fmt = null;
    if (prettyPrint) {
        fmt = Format.getPrettyFormat();
        fmt.setIndent("  "); // 2 spaces
    }
    outputter.setFormat(fmt);
    Document document = new Document(root);
    outputter.output(document, writer);
}

From source file:ca.nrc.cadc.caom2.xml.ObservationWriter.java

License:Open Source License

/**
 * Write the root Element to a writer.//w  w  w  . ja v a 2 s .c o  m
 *
 * @param root
 *            Root Element to write.
 * @param writer
 *            Writer to write to.
 * @throws IOException
 *             if the writer fails to write.
 */
@SuppressWarnings("unchecked")
protected void write(Element root, Writer writer) throws IOException {
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat());
    Document document = new Document(root);
    if (stylesheetURL != null) {
        Map<String, String> instructionMap = new HashMap<String, String>(2);
        instructionMap.put("type", "text/xsl");
        instructionMap.put("href", stylesheetURL);
        ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet", instructionMap);
        document.getContent().add(0, pi);
    }
    outputter.output(document, writer);
}