Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToXML.java

public Document convertToDOM(List<ReportBean> items, boolean withHistory, Locale locale, String personName,
        String filterName, String filterExpression, boolean useProjectSpecificID) {
    boolean budgetActive = ApplicationBean.getInstance().getBudgetActive();
    Document dom = null;//from w ww.  ja va2 s.  c om
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        dom = builder.newDocument();
    } catch (FactoryConfigurationError e) {
        LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    } catch (ParserConfigurationException e) {
        LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }
    Element root = dom.createElement("track-report");
    appendChild(root, "createdBy", personName, dom);
    Element filter = dom.createElement("filter");
    appendChild(filter, "name", filterName, dom);
    appendChild(filter, "expression", filterExpression, dom);
    root.appendChild(filter);
    Map<Integer, ILinkType> linkTypeIDToLinkTypeMap = LinkTypeBL.getLinkTypeIDToLinkTypeMap();
    List<TFieldBean> fields = FieldBL.loadAll();
    String issueNoName = null;
    if (useProjectSpecificID) {
        for (Iterator<TFieldBean> iterator = fields.iterator(); iterator.hasNext();) {
            TFieldBean fieldBean = iterator.next();
            if (SystemFields.INTEGER_ISSUENO.equals(fieldBean.getObjectID())) {
                issueNoName = fieldBean.getName();
                break;
            }
        }
    }
    for (Iterator<TFieldBean> iterator = fields.iterator(); iterator.hasNext();) {
        //only one from INTEGER_ISSUENO and INTEGER_PROJECT_SPECIFIC_ISSUENO should be shown
        TFieldBean fieldBean = iterator.next();
        if (useProjectSpecificID) {
            if (SystemFields.INTEGER_ISSUENO.equals(fieldBean.getObjectID())) {
                iterator.remove();
            }
            if (SystemFields.INTEGER_PROJECT_SPECIFIC_ISSUENO.equals(fieldBean.getObjectID())) {
                fieldBean.setName(issueNoName);
            }
        } else {
            if (SystemFields.INTEGER_PROJECT_SPECIFIC_ISSUENO.equals(fieldBean.getObjectID())) {
                iterator.remove();
            }
        }
    }
    String unavailable = LocalizeUtil.getLocalizedTextFromApplicationResources("itemov.lbl.unavailable",
            locale);
    for (ReportBean reportBean : items) {
        Element item = dom.createElement("item");
        TWorkItemBean workItemBean = reportBean.getWorkItemBean();
        for (TFieldBean fieldBean : fields) {
            Integer fieldID = fieldBean.getObjectID();
            String fieldName = fieldBean.getName();
            Object attributeValue = workItemBean.getAttribute(fieldID);
            if (attributeValue != null) {
                IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID);
                if (fieldTypeRT != null) {
                    if (fieldTypeRT.isLong()) {
                        String isoValue = (String) reportBean.getShowISOValue(fieldID);
                        if (isoValue != null && !isoValue.equals(unavailable)) {
                            String plainDescription = (String) workItemBean.getAttribute(fieldID);
                            try {
                                plainDescription = Html2Text.getNewInstance().convert((String) attributeValue);
                            } catch (Exception e) {
                                LOGGER.info("Transforming the HTML to plain text for workItemID "
                                        + workItemBean.getObjectID() + " and field " + fieldID + " failed with "
                                        + e);
                            }
                            appendChild(item, fieldName + PLAIN_SUFFIX, plainDescription, dom);
                            appendChild(item, fieldName, HTMLSanitiser.stripHTML((String) attributeValue), dom);
                        }
                    } else {
                        String isoValue = (String) reportBean.getShowISOValue(fieldID);
                        appendChild(item, fieldName, isoValue, dom);
                    }
                    if (fieldTypeRT.getValueType() == ValueType.CUSTOMOPTION || fieldTypeRT.isComposite()) {
                        //add custom list sortOrder
                        appendChild(item,
                                fieldBean.getName()
                                        + TReportLayoutBean.PSEUDO_COLUMN_NAMES.CUSTOM_OPTION_SYMBOL,
                                (String) reportBean.getShowISOValue(Integer.valueOf(-fieldID)), dom);
                    }
                    if (hasExtraSortField(fieldID)) {
                        Comparable sortOrder = reportBean.getSortOrder(fieldID);
                        if (sortOrder != null) {
                            appendChild(item, fieldBean.getName() + TReportLayoutBean.PSEUDO_COLUMN_NAMES.ORDER,
                                    sortOrder.toString(), dom);
                        }
                    }
                }
            }
        }
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.GLOBAL_ITEM_NO,
                workItemBean.getObjectID().toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.PROJECT_TYPE, reportBean.getProjectType(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.STATUS_FLAG,
                reportBean.getStateFlag().toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.COMMITTED_DATE_CONFLICT,
                new Boolean(reportBean.isCommittedDateConflict()).toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.TARGET_DATE_CONFLICT,
                new Boolean(reportBean.isTargetDateConflict()).toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.PLANNED_VALUE_CONFLICT,
                new Boolean(reportBean.isPlannedValueConflict()).toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.BUDGET_CONFLICT,
                new Boolean(reportBean.isBudgetConflict()).toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.SUMMARY,
                new Boolean(reportBean.isSummary()).toString(), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.INDENT_LEVEL,
                String.valueOf(reportBean.getLevel()), dom);
        String consultants = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.CONSULTANT_LIST);
        if (consultants != null && !"".equals(consultants)) {
            appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.CONSULTANT_LIST, consultants, dom);
        }
        String informed = (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST);
        if (informed != null && !"".equals(informed)) {
            appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.INFORMANT_LIST, informed, dom);
        }
        String linkedItems = (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.LINKED_ITEMS);
        if (linkedItems != null && !"".equals(linkedItems)) {
            appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.LINKED_ITEMS, linkedItems, dom);
        }
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.PRIVATE_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.PRIVATE_SYMBOL), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.OVERFLOW_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.OVERFLOW_ICONS), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.PRIORITY_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.PRIORITY_SYMBOL), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.SEVERITY_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.SEVERITY_SYMBOL), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.STATUS_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.STATUS_SYMBOL), dom);
        appendChild(item, TReportLayoutBean.PSEUDO_COLUMN_NAMES.ISSUETYPE_SYMBOL,
                (String) reportBean.getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.ISSUETYPE_SYMBOL), dom);
        String valueAndMeasurementUnit;
        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_COST);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.TOTAL_EXPENSE_COST,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_EXPENSE_TIME);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.TOTAL_EXPENSE_TIME,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_COST);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.MY_EXPENSE_COST,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.MY_EXPENSE_TIME,
                valueAndMeasurementUnit, dom, item);
        if (budgetActive) {
            valueAndMeasurementUnit = (String) reportBean
                    .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST);
            createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.BUDGET_COST,
                    valueAndMeasurementUnit, dom, item);

            valueAndMeasurementUnit = (String) reportBean
                    .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME);
            createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.BUDGET_TIME,
                    valueAndMeasurementUnit, dom, item);
        }
        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_COST);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.TOTAL_PLANNED_COST,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.TOTAL_PLANNED_TIME);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.TOTAL_PLANNED_TIME,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_COST);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.REMAINING_PLANNED_COST,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.REMAINING_PLANNED_TIME);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.REMAINING_PLANNED_TIME,
                valueAndMeasurementUnit, dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_COST);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.BUDGET_COST, valueAndMeasurementUnit,
                dom, item);

        valueAndMeasurementUnit = (String) reportBean
                .getShowISOValue(TReportLayoutBean.PSEUDO_COLUMNS.BUDGET_TIME);
        createComputedValueElement(TReportLayoutBean.PSEUDO_COLUMN_NAMES.BUDGET_TIME, valueAndMeasurementUnit,
                dom, item);

        Element links = createLinkElement(reportBean.getReportBeanLinksSet(), linkTypeIDToLinkTypeMap, locale,
                dom);
        if (links != null) {
            item.appendChild(links);
        }
        if (withHistory) {
            ReportBeanWithHistory reportBeanWithHistory = (ReportBeanWithHistory) reportBean;
            Element historyElement = createHistoryElement(reportBeanWithHistory.getHistoryValuesMap(), dom);
            if (historyElement != null) {
                item.appendChild(historyElement);
            }
            Element commentElement = createCommentElement(reportBeanWithHistory.getComments(), dom);
            if (commentElement != null) {
                item.appendChild(commentElement);
            }
            Element budgetElement = createBudgetElement(reportBeanWithHistory.getBudgetHistory(), dom, locale);
            if (budgetElement != null) {
                item.appendChild(budgetElement);
            }
            Element plannedValueElement = createBudgetElement(reportBeanWithHistory.getPlannedValueHistory(),
                    dom, locale);
            if (plannedValueElement != null) {
                item.appendChild(plannedValueElement);
            }
            if (plannedValueElement != null) {
                //do not add estimated remaining budget element if no budget exists
                Element remainingBudgetElement = createRemainingBudgetElement(
                        reportBeanWithHistory.getActualEstimatedBudgetBean(), dom, locale);
                if (remainingBudgetElement != null) {
                    item.appendChild(remainingBudgetElement);
                }
            }
            Element costElement = createExpenseElement(reportBeanWithHistory.getCosts(), dom, locale);
            if (costElement != null) {
                item.appendChild(costElement);
            }
        }
        root.appendChild(item);
    }
    dom.appendChild(root);
    return dom;
}

From source file:com.phresco.pom.util.PomProcessor.java

/**
 * Sets the property.//from ww w.ja  v  a 2  s . com
 *
 * @param name the name
 * @param value the value
 * @throws ParserConfigurationException the parser configuration exception
 */

public void setProperty(String name, String value) throws ParserConfigurationException {

    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element element = doc.createElement(name);
    element.setTextContent(value);

    if (model.getProperties() == null) {
        Properties properties = new Properties();
        model.setProperties(properties);
    }
    for (Element proElement : model.getProperties().getAny()) {
        if (proElement.getTagName().equals(name)) {
            proElement.setTextContent(value);
            return;
        }
    }
    model.getProperties().getAny().add(element);
}

From source file:com.photon.phresco.framework.rest.api.ParameterService.java

private static boolean saveCofiguration(String appDirName, String module, Publication config)
        throws PhrescoException {
    boolean fileSaved = false;
    try {//from w w w  .  j  a va2s. c  om
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(module)) {
            rootModulePath = Utility.getProjectHome() + appDirName;
            subModuleName = module;
        } else {
            rootModulePath = Utility.getProjectHome() + appDirName;
        }
        String appDirPath = Utility.getProjectHome() + appDirName;
        String dotPhrescoFolderPath = Utility.getDotPhrescoFolderPath(appDirPath, subModuleName);

        String publicationConfigPath = dotPhrescoFolderPath + File.separator + PUBLICATION_CONFIG_FILE;

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(PUBLICATIONS);
        doc.appendChild(rootElement);

        Element publication = doc.createElement(PUBLICATION);
        publication.setAttribute(PUBLICATION_NAME, config.getPublicationName());
        publication.setAttribute(PUBLICATION_TYPE, config.getPublicationType());
        rootElement.appendChild(publication);

        Element publicationPath = doc.createElement(PUBLICATION_PATH);
        publicationPath.setTextContent(config.getPublicationPath());
        rootElement.appendChild(publicationPath);

        Element publicationUrl = doc.createElement(PUBLICATION_URL);
        publicationUrl.setTextContent(config.getPublicationUrl());
        rootElement.appendChild(publicationUrl);

        Element imageUrl = doc.createElement(IMAGE_URL);
        imageUrl.setTextContent(config.getImageUrl());
        rootElement.appendChild(imageUrl);

        Element imagePath = doc.createElement(IMAGE_PATH);
        imagePath.setTextContent(config.getImagePath());
        rootElement.appendChild(imagePath);

        Element environment = doc.createElement(ENVIRONMENT);
        environment.setTextContent(config.getEnvironment());
        rootElement.appendChild(environment);

        Element publicationKey = doc.createElement(PUBLICATION_KEY);
        publicationKey.setTextContent(config.getPublicationKey());
        rootElement.appendChild(publicationKey);

        Element parentPublications = doc.createElement(PARENT_PUBLICATIONS);
        List<Map<String, String>> subPublications = config.getParentPublications();
        if (CollectionUtils.isNotEmpty(subPublications)) {
            for (Map<String, String> map : subPublications) {
                Element parentPublication = doc.createElement(PARENT_SUB_PUBLICATION);
                Set<String> keySet = map.keySet();
                if (CollectionUtils.isNotEmpty(keySet)) {
                    for (String keys : keySet) {
                        if (keys.equalsIgnoreCase(PARENT_NAME)) {
                            parentPublication.setAttribute(PARENT_NAME, map.get(keys));
                            parentPublications.appendChild(parentPublication);
                        } else if (keys.equalsIgnoreCase(PRIORITY)) {
                            parentPublication.setAttribute(PRIORITY, map.get(keys));
                            parentPublications.appendChild(parentPublication);
                        }
                    }
                }
            }
        }

        rootElement.appendChild(parentPublications);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, YES);

        Pattern p = Pattern.compile("%20");
        p.matcher(publicationConfigPath);
        File path = new File(publicationConfigPath);

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(path.toString());

        transformer.transform(source, result);
        fileSaved = true;

    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerConfigurationException e) {
        throw new PhrescoException(e);
    } catch (TransformerException e) {
        throw new PhrescoException(e);
    } catch (PhrescoException e) {
        throw new PhrescoException(e);
    }
    return fileSaved;
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, javax.xml.transform.Result)} method. </p>
 *
 * @throws IllegalArgumentException is expected.
 * @throws Exception                if any error occurs during test
 *///from   w  w w  .  j  av a 2 s  .co  m
@Test(expected = IllegalArgumentException.class)
public void testMarshallResultNull1() throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(null, new DOMResult(document));
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java

@Override
public String createXmlData(String metricName, String rrdFilename, long startTime, long endTime)
        throws IOException, MetricsGraphException {
    LOGGER.trace("ENTERING: createXmlData");

    MetricData metricData = getMetricData(rrdFilename, startTime, endTime);

    String displayableMetricName = convertCamelCase(metricName);

    String title = displayableMetricName + " for " + getCalendarTime(startTime) + " to "
            + getCalendarTime(endTime);//from   ww  w .j av  a2s. c o m

    String xmlString = null;

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(metricName);
        doc.appendChild(rootElement);

        Element titleElement = doc.createElement("title");
        titleElement.appendChild(doc.createTextNode(title));
        rootElement.appendChild(titleElement);

        Element dataElement = doc.createElement("data");
        rootElement.appendChild(dataElement);

        List<Long> timestamps = metricData.getTimestamps();
        List<Double> values = metricData.getValues();

        for (int i = 0; i < timestamps.size(); i++) {
            Element sampleElement = doc.createElement("sample");
            dataElement.appendChild(sampleElement);

            String timestamp = getCalendarTime(timestamps.get(i));
            Element timestampElement = doc.createElement("timestamp");
            timestampElement.appendChild(doc.createTextNode(timestamp));
            sampleElement.appendChild(timestampElement);

            Element valueElement = doc.createElement("value");
            valueElement.appendChild(doc.createTextNode(String.valueOf(values.get(i))));
            sampleElement.appendChild(valueElement);
        }

        if (metricData.hasTotalCount()) {
            Element totalCountElement = doc.createElement("totalCount");
            totalCountElement.appendChild(doc.createTextNode(Long.toString(metricData.getTotalCount())));
            dataElement.appendChild(totalCountElement);
        }

        // Write the content into xml stringwriter
        xmlString = XMLUtils.prettyFormat(doc);
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing error while creating xml data", pce);
    }

    LOGGER.trace("xml = {}", xmlString);

    LOGGER.trace("EXITING: createXmlData");

    return xmlString;
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link Node}.
 *
 * @param entity the object to marshall/*from  ww  w. ja  v a  2s .  c  o m*/
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallNode(Object entity) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(entity, document);

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link DOMResult}.
 *
 * @param entity the object to marshall// w  w  w. j a  va2  s  .c  om
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallDOMResult(Object entity) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Node document = builder.newDocument();

    marshaller.marshal(entity, new DOMResult(document));

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(writer));

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, Node)} method when jaxbElement is null. </p> {@link
 * IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///from  w w w.  jav  a2  s  .c o m
@Test(expected = IllegalArgumentException.class)
public void testMarshallNodeNull1() throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    marshaller.marshal(null, builder.newDocument());
}

From source file:fr.cls.atoll.motu.processor.wps.StringList.java

public static void readXML(Element object) {
    // XMLReader parser = XMLReaderFactory.createXMLReader();
    // InputSource inputSource = new InputSource()
    // parser.parse(input);

    try {/*w  w w .  j  a  v a  2 s  . c  o  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Source src = new DOMSource(object);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tformer = tFactory.newTransformer();

        Result result = new StreamResult(System.out);
        tformer.transform(src, result);
        // doc.getDocumentElement().normalize();
        // System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        // NodeList nodeLst = doc.getElementsByTagName("employee");
        // System.out.println("Information of all employees");

        Element copyElement = (Element) object.cloneNode(true);
        Document doc = db.newDocument();
        Node node = doc.importNode(copyElement, true);
        NodeList nodeList = doc.getElementsByTagName("Arc");
        System.out.println(doc.getElementsByTagName("Curve"));
        // Node node = object;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private Document handleSoapResponse(SOAPMessage response, HttpResponseBean responseBean)
        throws TransformerException, SOAPException, ParserConfigurationException {

    Node responseNode = null;//from  w w  w.ja  va 2s  . co m

    if (response != null) {
        responseNode = extractResponseNode(response);
        extractHeaderDataSOAP(response, responseBean);
    }

    // build new xml document for assertion
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document newDocument = builder.newDocument();

    Node adoptedBlob = newDocument.importNode(responseNode, true);
    newDocument.appendChild(adoptedBlob);

    // Output as String if required
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    transformer.transform(new DOMSource(newDocument), new StreamResult(out));

    if (logger.isDebugEnabled()) {
        logger.debug("\n Return Doc \n");
        logger.debug(new String(out.toByteArray()));
    }

    return newDocument;
}