Java Code Examples for org.w3c.dom.ls.LSSerializer#write()

The following examples show how to use org.w3c.dom.ls.LSSerializer#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private static String marshall(XMLObject xmlObject) throws org.wso2.carbon.identity.base.IdentityException {
    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString("UTF-8");
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw IdentityException.error("Error Serializing the SAML Response", e);
    }
}
 
Example 2
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * `
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example 3
Source File: AuctionController.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
 * DOMConfiguration.setParameter("well-formed",true) throws an exception.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewItem2Sell() throws Exception {
    String xmlFile = XML_DIR + "novelsInvalid.xml";

    Document document = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse(xmlFile);

    document.getDomConfig().setParameter("well-formed", true);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    MyDOMOutput domOutput = new MyDOMOutput();
    domOutput.setByteStream(System.out);
    LSSerializer writer = impl.createLSSerializer();
    writer.write(document, domOutput);
}
 
Example 4
Source File: WSXACMLMessageReceiver.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * `
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example 5
Source File: SSOUtils.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object
 * @throws SAMLSSOException
 */
public static String marshall(XMLObject xmlObject) throws SAMLSSOException {
    try {

        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration
                .getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new SAMLSSOException("Error Serializing the SAML Response", e);
    }
}
 
Example 6
Source File: Helper.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/***
 * Helper method which converts XML Document into pretty formatted string
 *
 * @param doc to convert
 * @return converted XML as String
 */
public static String documentToString(Document doc) {

    String strMsg = "";
    try {
        DOMImplementation domImpl = doc.getImplementation();
        DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

        Writer stringWriter = new StringWriter();
        LSOutput lsOutput = domImplLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(doc, lsOutput);
        strMsg = stringWriter.toString();
    } catch (Exception e) {
        logger.warn("Error occurred when converting document to string", e);
    }
    return strMsg;
}
 
Example 7
Source File: Util.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object
 * @throws Exception
 */
public static String marshall(XMLObject xmlObject) throws Exception {
    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString();
    } catch (Exception e) {
        throw new Exception("Error Serializing the SAML Response", e);
    }
}
 
Example 8
Source File: OrganisationGroupServlet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
   private void getGroupings(Integer organisationId, HttpServletResponse response) throws IOException {
Document doc = OrganisationGroupServlet.docBuilder.newDocument();
Element groupsElement = doc.createElement("groups");
doc.appendChild(groupsElement);

List<OrganisationGrouping> groupings = userManagementService.findByProperty(OrganisationGrouping.class,
	"organisationId", organisationId);
for (OrganisationGrouping grouping : groupings) {
    Element groupingElement = doc.createElement("grouping");
    groupingElement.setAttribute("id", grouping.getGroupingId().toString());
    groupingElement.setAttribute("name", StringEscapeUtils.escapeXml(grouping.getName()));
    groupsElement.appendChild(groupingElement);
    for (OrganisationGroup group : grouping.getGroups()) {
	Element groupElement = doc.createElement("group");
	groupElement.setAttribute("id", group.getGroupId().toString());
	groupElement.setAttribute("name", StringEscapeUtils.escapeXml(group.getName()));
	groupingElement.appendChild(groupElement);
	for (User user : group.getUsers()) {
	    Element userElement = doc.createElement("user");
	    userElement.setAttribute("id", user.getUserId().toString());
	    userElement.setAttribute("firstname", StringEscapeUtils.escapeXml(user.getFirstName()));
	    userElement.setAttribute("lastname", StringEscapeUtils.escapeXml(user.getLastName()));
	    groupElement.appendChild(userElement);
	}
    }
}

response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setEncoding("UTF-8");
lsOutput.setByteStream(response.getOutputStream());
lsSerializer.write(doc, lsOutput);
   }
 
Example 9
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 */
private String marshall(XMLObject xmlObject) throws EntitlementProxyException {

    try {
        doBootstrap();
        System.setProperty(
                DOCUMENT_BUILDER_FACTORY,
                DOCUMENT_BUILDER_FACTORY_IMPL);

        MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return new String(byteArrayOutputStrm.toByteArray(), Charset.forName("UTF-8"));
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementProxyException("Error Serializing the SAML Response", e);
    }
}
 
Example 10
Source File: StorageUtils.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		  DocumentBuilder builder = dbFactory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 11
Source File: XmlStringBuffer.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * string value of document
 *
 * @return the string
 */
public final String stringValue()
{
  if(log.isDebugEnabled())
  {
    log.debug("stringValue()");
  }

  if(document == null)
  {
    return this.xml.toString();
  }
  else
  {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
	DOMImplementationRegistry registry = DOMImplementationRegistry
			.newInstance();
	DOMImplementationLS impl = (DOMImplementationLS) registry
			.getDOMImplementation("LS");
	LSSerializer writer = impl.createLSSerializer();
	writer.getDomConfig().setParameter("format-pretty-print",
			Boolean.TRUE);
	LSOutput output = impl.createLSOutput();
	output.setByteStream(out);
	writer.write(document, output);
} catch (Exception e) {
	log.error(e.getMessage(), e);
}
return out.toString();	
  }
}
 
Example 12
Source File: StorageUtils.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		  DocumentBuilder builder = dbFactory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 13
Source File: XMLHelper.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Writes a Node out to a Writer using the DOM, level 3, Load/Save serializer. The written content is encoded using
 * the encoding specified in the writer configuration.
 *
 * @param node the node to write out
 * @param output the writer to write the XML to
 * @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
 *         instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
 */
public static void writeNode(Node node, Writer output, Map<String, Object> serializerParams) {
  DOMImplementationLS domImplLS = getLSDOMImpl(node);

  LSSerializer serializer = getLSSerializer(domImplLS, serializerParams);

  LSOutput serializerOut = domImplLS.createLSOutput();
  serializerOut.setCharacterStream(output);

  serializer.write(node, serializerOut);
}
 
Example 14
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checking for namespace normalization.
 * @see <a href="content/screenName.xml">screenName.xml</a> has prefix of
 * userName is bound to "http://hibid.com/user" namespace normalization
 * will create a namespace of prefix us and attach userEmail.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckScreenNameExists() throws Exception {
    String resultFile = USER_DIR + "screenName.out";
    String xmlFile = XML_DIR + "screenName.xml";
    String goldFile = GOLDEN_DIR + "screenNameGold.xml";

    String nsTagName = "http://hibid.com/screenName";
    String userNs = "http://hibid.com/user";

    try (FileOutputStream output = new FileOutputStream(resultFile)) {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
        Document document = builder.parseURI(xmlFile);
        NodeList nl = document.getElementsByTagNameNS(nsTagName, "screen-name");
        assertEquals(nl.getLength(), 1);
        Element screenName = (Element)nl.item(0);
        Element userEmail = document.createElementNS(userNs, "userEmail");
        assertTrue(userEmail.isDefaultNamespace(userNs));

        Text email = document.createTextNode("[email protected]");
        userEmail.appendChild(email);
        screenName.appendChild(userEmail);
        document.normalizeDocument();

        MyDOMOutput domoutput = new MyDOMOutput();
        domoutput.setByteStream(output);
        writer.write(document, domoutput);
    }
    assertTrue(compareDocumentWithGold(goldFile, resultFile));
}
 
Example 15
Source File: XMLIndentUtil.java    From rest-client with Apache License 2.0 5 votes vote down vote up
public static String getIndented(String inXml) throws IOException {
    try {
        final InputSource src = new InputSource(new StringReader(inXml));
        final Document domDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src);
        String encoding = domDoc.getXmlEncoding();
        if (encoding == null) {
            // defaults to UTF-8
            encoding = "UTF-8";
        }
        final Node document = domDoc.getDocumentElement();
        final boolean keepDeclaration = inXml.startsWith("<?xml");
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();
        writer.setNewLine("\n");
        writer.getDomConfig().setParameter("format-pretty-print", true); // Set this to true if the output needs to be beautified.
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.
        LSOutput lsOutput = impl.createLSOutput();
        lsOutput.setEncoding(encoding);
        Writer stringWriter = new StringWriter();
        lsOutput.setCharacterStream(stringWriter);
        writer.write(document, lsOutput);
        return stringWriter.toString();
    }
    catch (ParserConfigurationException | SAXException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        throw new XMLException(null, ex);
    }
}
 
Example 16
Source File: XmlConverter.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void serialize(final Element value, final JsonWriter sw) {
	Document document = value.getOwnerDocument();
	DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
	LSSerializer serializer = domImplLS.createLSSerializer();
	LSOutput lsOutput = domImplLS.createLSOutput();
	lsOutput.setEncoding("UTF-8");
	StringWriter writer = new StringWriter();
	lsOutput.setCharacterStream(writer);
	serializer.write(document, lsOutput);
	StringConverter.serialize(writer.toString(), sw);
}
 
Example 17
Source File: XmlDocumentBuilder.java    From archistar-core with GNU General Public License v2.0 5 votes vote down vote up
public String stringFromDoc(Document doc) {
    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = implLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(doc, lsOutput);

    return stringWriter.toString();
}
 
Example 18
Source File: UserController.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Checking conflicting namespaces and use renameNode and normalizeDocument.
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testAddUser() throws Exception {
    String resultFile = USER_DIR + "accountRole.out";
    String xmlFile = XML_DIR + "accountInfo.xml";

    // Copy schema for outputfile
    Files.copy(Paths.get(XML_DIR, "accountInfo.xsd"),
            Paths.get(USER_DIR, "accountInfo.xsd"),
            StandardCopyOption.REPLACE_EXISTING);
    MyErrorHandler eh = new MyErrorHandler();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(xmlFile);
    Element sell = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Sell").item(0);
    Element role = (Element) sell.getParentNode();

    Element buy = (Element) document.renameNode(sell, PORTAL_ACCOUNT_NS, "acc:Buy");
    role.appendChild(buy);

    DOMImplementationLS impl
            = (DOMImplementationLS) DOMImplementationRegistry
                    .newInstance().getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();


    try(FileOutputStream output = new FileOutputStream(resultFile)) {
        MyDOMOutput mydomoutput = new MyDOMOutput();
        mydomoutput.setByteStream(output);
        writer.write(document, mydomoutput);
    }

    docBuilder.parse(resultFile);
    assertFalse(eh.isAnyError());
}
 
Example 19
Source File: MainUIModel.java    From Motion_Profile_Generator with MIT License 4 votes vote down vote up
/**
 * Saves the working project.
 */
public void saveWorkingProject() throws ParserConfigurationException
{
    if( workingProject != null )
    {
        // Create document
        DocumentBuilder db = dbFactory.newDocumentBuilder();
        Document dom = db.newDocument();

        // XML entry for the path waypoints and vars
        Element pathElement = dom.createElement("Path" );

        // Save generator type
        pathElement.setAttribute( "GeneratorType", settings.getGeneratorType().name() );

        // Save shared vars
        settings.getSharedGeneratorVars().writeXMLAttributes( pathElement );

        // Write generator vars to xml file
        settings.getGeneratorVars().writeXMLAttributes( pathElement );
        dom.appendChild( pathElement );

        // Write waypoints to xml file
        for( Waypoint wp : waypointList )
        {
            Element waypointEle = dom.createElement("Waypoint" );
            Element xEle = dom.createElement("X" );
            Element yEle = dom.createElement("Y" );
            Element angleEle = dom.createElement("Angle" );
            Text xText = dom.createTextNode("" + wp.getX() );
            Text yText = dom.createTextNode("" + wp.getY() );
            Text angleText = dom.createTextNode("" + wp.getAngle() );

            xEle.appendChild( xText );
            yEle.appendChild( yText );
            angleEle.appendChild( angleText );

            waypointEle.appendChild( xEle );
            waypointEle.appendChild( yEle );
            waypointEle.appendChild( angleEle );

            pathElement.appendChild( waypointEle );
        }

        FileOutputStream fos;
        try
        {
            fos = new FileOutputStream( workingProject );
            DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS" );
            LSSerializer serializer = impl.createLSSerializer();
            
            serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE );
            
            LSOutput lso = impl.createLSOutput();
            lso.setByteStream( fos );
            serializer.write( dom, lso );
           
        }
        catch( Exception e )
        {
            throw new RuntimeException( e );
        }
    }
}
 
Example 20
Source File: CompoundXmlRequest.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
public String toXml()
{
    Document document;
    DocumentBuilder docBuilder;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try
    {
        docBuilder = factory.newDocumentBuilder();
        document = docBuilder.newDocument();
    }
    catch (ParserConfigurationException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    DOMImplementationLS implLS = (DOMImplementationLS) docBuilder.getDOMImplementation();
    LSSerializer domWriter = implLS.createLSSerializer();
    LSOutput output = implLS.createLSOutput();
    
    //DOMException: FEATURE_NOT_SUPPORTED: The parameter format-pretty-print is recognized but the requested value cannot be set.
    //domWriter.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
    
    output.setEncoding("UTF-8");
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    output.setByteStream(outStream);
    
    
    Element root = document.createElement("requests");
    for(Request req : _requests)
    {
        Element reqNode = document.createElement("request");
        reqNode.setAttribute("id", Integer.toString(req.getId()));
        reqNode.setAttribute("type", req.getType());
        for(RequestPart part : req.getParts())
        {
            Element partNode = null;
            if(part instanceof RequestForPart)
            {
                partNode = document.createElement("for");
                writeForPart(partNode, (RequestForPart) part, document);
            }
            else
            {
                partNode = document.createElement("part");
                partNode.setAttribute("name", part.getName());
                partNode.setAttribute("value", part.getValue());
            }
            reqNode.appendChild(partNode);
        }
        root.appendChild(reqNode);
    }
    
    document.appendChild(root);
    domWriter.write(document, output);
    
    return outStream.toString();
}