Example usage for org.jdom2 Document setRootElement

List of usage examples for org.jdom2 Document setRootElement

Introduction

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

Prototype

public Document setRootElement(Element rootElement) 

Source Link

Document

This sets the root Element for the Document.

Usage

From source file:arquivo.ArquivoF.java

public ArquivoF() {
    super(new File("empregados.xml"));
    if (!arquivo.exists()) {
        try {/*from  w  w w.j a  v a  2  s.co m*/
            Document doc = new Document();
            Element root = new Element("list");
            doc.setRootElement(root);
            XMLOutputter xout = new XMLOutputter();

            xout.output(doc, new FileOutputStream(arquivo));
            System.out.println("Documento criado com sucesso!");

        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

From source file:arquivo.ArquivoFilme.java

public ArquivoFilme() {
    super(new File("filmes.xml"));
    if (!arquivo.exists()) {
        try {/*w w w  .j  a va  2  s  .  co m*/
            Document doc = new Document();
            Element root = new Element("list");
            doc.setRootElement(root);
            XMLOutputter xout = new XMLOutputter();

            xout.output(doc, new FileOutputStream(arquivo));
            System.out.println("Documento criado com sucesso!");

        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

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   ww w  . ja v a2  s  .c  o  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:ca.nrc.cadc.ac.json.JsonGroupWriter.java

License:Open Source License

/**
 * Write a Group to a Writer./* ww  w .  j a  v a  2  s .  c o m*/
 *
 * @param group Group to write.
 * @param writer  Writer to write to.
 * @throws IOException if the writer fails to write.
 * @throws WriterException
 */
@Override
public void write(Group group, Writer writer) throws WriterException, IOException {
    if (group == null) {
        throw new WriterException("null group");
    }

    Element groupElement = getElement(group, true);
    Document document = new Document();
    document.setRootElement(groupElement);

    JsonOutputter jsonOutputter = new JsonOutputter();
    jsonOutputter.getListElementNames().add(GROUPS);
    jsonOutputter.getListElementNames().add(USERS);
    jsonOutputter.getListElementNames().add(IDENTITIES);
    jsonOutputter.getListElementNames().add(PROPERTIES);
    jsonOutputter.getListElementNames().add(GROUP_MEMBERS);
    jsonOutputter.getListElementNames().add(GROUP_ADMINS);
    jsonOutputter.getListElementNames().add(USER_MEMBERS);
    jsonOutputter.getListElementNames().add(USER_ADMINS);

    jsonOutputter.output(document, writer);
}

From source file:ca.nrc.cadc.ac.json.JsonUserListWriter.java

License:Open Source License

/**
 * Write a Collection of Users to a Writer.
 *
 * @param users  Users to write.//w ww  .j  a  v  a 2  s.  c  om
 * @param writer Writer to write to.
 * @throws IOException     if the writer fails to write.
 */
@Override
public <T extends Principal> void write(Collection<User> users, Writer writer)
        throws WriterException, IOException {
    if (users == null) {
        throw new WriterException("null users");
    }

    Element usersElement = getElement(users);
    Document document = new Document();
    document.setRootElement(usersElement);

    JsonOutputter jsonOutputter = new JsonOutputter();
    jsonOutputter.getListElementNames().add(GROUPS);
    jsonOutputter.getListElementNames().add(USERS);
    jsonOutputter.getListElementNames().add(IDENTITIES);

    jsonOutputter.output(document, writer);
}

From source file:ca.nrc.cadc.ac.json.JsonUserRequestWriter.java

License:Open Source License

/**
 * Write a UserRequest to a Writer.//from w  w w .  j  a va 2 s .c  om
 *
 * @param userRequest UserRequest to write.
 * @param writer Writer to write to.
 * @throws IOException if the writer fails to write.
 * @throws WriterException
 */
@Override
public void write(UserRequest userRequest, Writer writer) throws WriterException, IOException {
    if (userRequest == null) {
        throw new WriterException("null UserRequest");
    }

    Element userRequestElement = getElement(userRequest);
    Document document = new Document();
    document.setRootElement(userRequestElement);

    JsonOutputter jsonOutputter = new JsonOutputter();
    jsonOutputter.getListElementNames().add(GROUPS);
    jsonOutputter.getListElementNames().add(USERS);
    jsonOutputter.getListElementNames().add(IDENTITIES);
    jsonOutputter.getListElementNames().add(PROPERTIES);
    jsonOutputter.getListElementNames().add(GROUP_MEMBERS);
    jsonOutputter.getListElementNames().add(GROUP_ADMINS);
    jsonOutputter.getListElementNames().add(USER_MEMBERS);
    jsonOutputter.getListElementNames().add(USER_ADMINS);

    jsonOutputter.output(document, writer);
}

From source file:ca.nrc.cadc.ac.json.JsonUserWriter.java

License:Open Source License

/**
 * Write a User as a JSON string to a Writer.
 *
 * @param user User to write./*from w ww .ja  va2 s.  c om*/
 * @param writer Writer to write to.
 * @throws IOException if the writer fails to write.
 * @throws WriterException
 */
@Override
public void write(User user, Writer writer) throws WriterException, IOException {
    if (user == null) {
        throw new WriterException("null User");
    }

    Element userElement = getElement(user);
    Document document = new Document();
    document.setRootElement(userElement);

    JsonOutputter jsonOutputter = new JsonOutputter();
    jsonOutputter.getListElementNames().add(GROUPS);
    jsonOutputter.getListElementNames().add(USERS);
    jsonOutputter.getListElementNames().add(IDENTITIES);
    jsonOutputter.getListElementNames().add(PROPERTIES);
    jsonOutputter.getListElementNames().add(GROUP_MEMBERS);
    jsonOutputter.getListElementNames().add(GROUP_ADMINS);
    jsonOutputter.getListElementNames().add(USER_MEMBERS);
    jsonOutputter.getListElementNames().add(USER_ADMINS);

    jsonOutputter.output(document, writer);
}

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 w w  .  jav a2 s . c  om
            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.uws.web.restlet.resources.AsynchResource.java

License:Open Source License

private void doBuildXML(final Document document) throws IOException {
    Form query = getQuery();//from w  ww. j  av  a2s. c  o  m
    String[] phases = query.getValuesArray("PHASE", true);
    String after = query.getFirstValue("AFTER", true);
    String last = query.getFirstValue("LAST", true);
    try {
        Subject caller = AuthenticationUtil.getCurrentSubject();
        AuthMethod am = AuthenticationUtil.getAuthMethod(caller);
        if (am == null || AuthMethod.ANON.equals(am)) {
            generateErrorRepresentation(Status.CLIENT_ERROR_FORBIDDEN, "anonymous job listing not permitted");
        }

        List<ExecutionPhase> phaseList = new ArrayList<ExecutionPhase>();
        for (String es : phases) {
            try {
                phaseList.add(ExecutionPhase.toValue(es));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("invalid parameter: PHASE=" + es);
            }
        }

        String path = getRequestPath();
        int i = path.indexOf('/', 2); // the second /
        String appname = path.substring(0, i + 1); // include second /

        // parse 'last' parameter
        Integer lastInt = null;
        if (last != null) {
            try {
                lastInt = Integer.parseInt(last);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("invalid parameter: LAST=" + last);
            }

            if (lastInt < 1)
                throw new IllegalArgumentException("invalid parameter: LAST=" + last);
        }

        // parse 'after' parameter
        Date afterDate = null;
        if (after != null) {
            try {
                afterDate = dateFormat.parse(after);
            } catch (ParseException e) {
                throw new IllegalArgumentException("invalid parameter: AFTER=" + after);
            }
        }

        Iterator<JobRef> jobs = getJobManager().iterator(appname, phaseList, afterDate, lastInt);
        JobListWriter jobListWriter = new JobListWriter();
        Element root = jobListWriter.getRootElement(jobs);
        document.setRootElement(root);
    } catch (IllegalArgumentException ex) {
        String msg = ex.getMessage();
        LOGGER.debug(msg);
        generateErrorRepresentation(Status.CLIENT_ERROR_BAD_REQUEST, msg);
    } catch (UnsupportedOperationException e) {
        // not implemented--turn into a 'Forbidden'
        throw new AccessControlException("permission denied: " + e.getMessage());
    } catch (TransientException e) {
        LOGGER.error(e);
        generateErrorRepresentation(Status.SERVER_ERROR_SERVICE_UNAVAILABLE, "Transient error.");
    } catch (JobPersistenceException e) {
        LOGGER.error("persistence fail", e);
        generateErrorRepresentation(Status.SERVER_ERROR_INTERNAL, "Internal error.");
    }
}

From source file:ca.nrc.cadc.uws.web.restlet.resources.JobAsynchResource.java

License:Open Source License

/**
 * Assemble the XML for this Resource's Representation into the given
 * Document./* w w  w. j a  v a 2s .c o  m*/
 *
 * @param document The Document to build up.
 * @throws java.io.IOException If something went wrong or the XML cannot be
 *                             built.
 */
protected void buildXML(final Document document) throws IOException {
    JobWriter writer = new JobWriter();
    Element root = writer.getRootElement(job);
    document.setRootElement(root);
}