javax.xml.stream.XMLStreamWriter#close ( )源码实例Demo

下面列出了javax.xml.stream.XMLStreamWriter#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cxf   文件: StaxUtilsTest.java
@Test
public void testCopyWithEmptyNamespace() throws Exception {
    StringBuilder in = new StringBuilder(128);
    in.append("<foo xmlns=\"http://example.com/\">");
    in.append("<bar xmlns=\"\"/>");
    in.append("</foo>");

    XMLStreamReader reader = StaxUtils.createXMLStreamReader(
         new ByteArrayInputStream(in.toString().getBytes()));

    Writer out = new StringWriter();
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(out);
    StaxUtils.copy(reader, writer);
    writer.close();

    assertEquals(in.toString(), out.toString());
}
 
源代码2 项目: openjdk-jdk9   文件: SurrogatesTest.java
private void generateXML(XMLStreamWriter writer, String sequence)
        throws XMLStreamException {
    char[] seqArr = sequence.toCharArray();
    writer.writeStartDocument();
    writer.writeStartElement("root");

    // Use writeCharacters( String ) to write characters
    writer.writeStartElement("writeCharactersWithString");
    writer.writeCharacters(sequence);
    writer.writeEndElement();

    // Use writeCharacters( char [], int , int ) to write characters
    writer.writeStartElement("writeCharactersWithArray");
    writer.writeCharacters(seqArr, 0, seqArr.length);
    writer.writeEndElement();

    // Close root element and document
    writer.writeEndElement();
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
源代码3 项目: sailfish-core   文件: XMLTransmitter.java
/**
 * @param output
 * @throws FactoryConfigurationError
 */
private void writeCopyright(OutputStream output) throws FactoryConfigurationError {
    try {
	    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
	    XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(output);//;
	    try {
	        xmlStreamWriter.writeStartDocument(Charset.defaultCharset().name(), "1.0");
	        xmlStreamWriter.writeCharacters("\r\n");
	        xmlStreamWriter.writeComment("\r\n" + PROPRIETARY_COPYRIGHT);
	    } finally {
	        xmlStreamWriter.flush();
            xmlStreamWriter.close();
	    }
	} catch (XMLStreamException e) {
	    throw new EPSCommonException("A XML stream writer instance could not be created", e);
	}
}
 
源代码4 项目: secure-data-service   文件: XmiMappingWriter.java
public static final void writeMappingDocument(final XmiComparison document, final OutputStream outstream) {
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    try {
        final XMLStreamWriter xsw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(outstream, "UTF-8"));
        xsw.writeStartDocument("UTF-8", "1.0");
        try {
            writeMappingDocument(document, xsw);
        } finally {
            xsw.writeEndDocument();
        }
        xsw.flush();
        xsw.close();
    } catch (final XMLStreamException e) {
        throw new XmiCompRuntimeException(e);
    }
}
 
源代码5 项目: cxf   文件: AbstractLoggingInterceptor.java
protected void writePrettyPayload(StringBuilder builder,
                            StringWriter stringWriter,
                            String contentType)
    throws Exception {
    // Just transform the XML message when the cos has content

    StringWriter swriter = new StringWriter();
    XMLStreamWriter xwriter = StaxUtils.createXMLStreamWriter(swriter);
    xwriter = new PrettyPrintXMLStreamWriter(xwriter, 2);
    StaxUtils.copy(new StreamSource(new StringReader(stringWriter.getBuffer().toString())), xwriter);
    xwriter.close();

    String result = swriter.toString();
    if (result.length() < limit || limit == -1) {
        builder.append(swriter.toString());
    } else {
        builder.append(swriter.toString().substring(0, limit));
    }
}
 
源代码6 项目: wildfly-core   文件: JBossCliXmlConfigTestCase.java
private static File createConfigFile(String version) {
    File f = new File(TestSuiteEnvironment.getTmpDir(), "test-jboss-cli.xml");
    String namespace = "urn:jboss:cli:" + version;
    XMLOutputFactory output = XMLOutputFactory.newInstance();
    try (Writer stream = Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8)) {
        XMLStreamWriter writer = output.createXMLStreamWriter(stream);
        writer.writeStartDocument();
        writer.writeStartElement("jboss-cli");
        writer.writeDefaultNamespace(namespace);
        writer.writeStartElement("ssl");
        writer.writeEndElement(); //ssl
        writer.writeEndElement(); //jboss-cli
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (XMLStreamException | IOException ex) {
        fail("Failure creating config file " + ex);
    }
    return f;
}
 
源代码7 项目: JavaCommon   文件: StaxDemo.java
public static void writeXMLByStAX() throws XMLStreamException, FileNotFoundException {
	XMLOutputFactory factory = XMLOutputFactory.newInstance();
	XMLStreamWriter writer = factory.createXMLStreamWriter(new FileOutputStream("output.xml"));
	writer.writeStartDocument();
	writer.writeCharacters(" ");
	writer.writeComment("testing comment");
	writer.writeCharacters(" ");
	writer.writeStartElement("catalogs");
	writer.writeNamespace("myNS", "http://blog.csdn.net/Chinajash");
	writer.writeAttribute("owner", "sina");
	writer.writeCharacters(" ");
	writer.writeStartElement("http://blog.csdn.net/Chinajash", "catalog");
	writer.writeAttribute("id", "007");
	writer.writeCharacters("Apparel");
	// 写入catalog元素的结束标签
	writer.writeEndElement();
	// 写入catalogs元素的结束标签
	writer.writeEndElement();
	// 结束 XML 文档
	writer.writeEndDocument();
	writer.close();
	System.out.println("ok");
}
 
源代码8 项目: cxf   文件: StaxUtils.java
public static void writeTo(Node node, OutputStream os, int indent) throws XMLStreamException {
    if (indent > 0) {
        XMLStreamWriter writer = new PrettyPrintXMLStreamWriter(createXMLStreamWriter(os), indent);
        try {
            copy(new DOMSource(node), writer);
        } finally {
            writer.close();
        }
    } else {
        copy(new DOMSource(node), os);
    }
}
 
源代码9 项目: ironjacamar   文件: DataSources20TestCase.java
/**
 * Write
 * @throws Exception In case of an error
 */
@Test
public void testWrite() throws Exception
{
   DsParser parser = new DsParser();

   InputStream is = DataSources20TestCase.class.getClassLoader().
      getResourceAsStream("../../resources/test/ds/dashds-2.0.xml");
   assertNotNull(is);

   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);

   DataSources ds = parser.parse(xsr);
   assertNotNull(ds);

   is.close();

   StringWriter sw = new StringWriter();
   XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw);
   xsw.setDefaultNamespace("");

   xsw.writeStartDocument("UTF-8", "1.0");
   parser.store(ds, xsw);
   xsw.writeEndDocument();

   xsw.flush();
   xsw.close();

   assertEquals(ds.toString(), sw.toString());
}
 
源代码10 项目: softwarecave   文件: NoNSWriter.java
public void writeToXml(Path path, List<Book> books) throws IOException, XMLStreamException {
    try (OutputStream os = Files.newOutputStream(path)) {
        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter writer = null;
        try {
            writer = outputFactory.createXMLStreamWriter(os, "utf-8");
            writeBooksElem(writer, books);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
 
源代码11 项目: secure-data-service   文件: EntityXMLWriter.java
/**
 * Serializes an entity to xml
 * @param entityResponse
 * @param entityStream
 * @throws XMLStreamException
 */
protected void writeEntity(EntityResponse entityResponse, OutputStream entityStream) throws XMLStreamException {
    XMLStreamWriter writer = null;

    try {
        //create the factory
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        //get the stream writer
        writer = factory.createXMLStreamWriter(entityStream);

        String resourceName = entityResponse.getEntityCollectionName();
        if (isList(entityResponse.getEntity())) {
            resourceName += "List";
        }

        //start the document
        writer.writeStartDocument();
        writer.writeStartElement(resourceName);
        writer.writeNamespace(PREFIX, NS);
        //recursively add the objects
        writeToXml(entityResponse.getEntity(), entityResponse.getEntityCollectionName(), writer);
        //end the document
        writer.writeEndElement();
        writer.writeEndDocument();
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}
 
源代码12 项目: karaf-boot   文件: JpaProcessor.java
public void process(Writer writer, Map<PersistentUnit, List<? extends AnnotationMirror>> units) throws Exception {
    Set<String> puNames = new HashSet<String>();
    XMLOutputFactory xof =  XMLOutputFactory.newInstance();
    XMLStreamWriter w = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(writer));
    w.setDefaultNamespace("http://java.sun.com/xml/ns/persistence");
    w.writeStartDocument();
    w.writeStartElement("persistence");
    w.writeAttribute("verson", "2.0");
    
    //w.println("<persistence version=\"2.0\" xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\">");
    for (PersistentUnit pu : units.keySet()) {
        if (pu.name() == null || pu.name().isEmpty()) {
            throw new IOException("Missing persistent unit name");
        }
        if (!puNames.add(pu.name())) {
            throw new IOException("Duplicate persistent unit name: " + pu.name());
        }
        w.writeStartElement("persistence-unit");
        w.writeAttribute("name", pu.name());
        w.writeAttribute("transaction-type", pu.transactionType().toString());
        writeElement(w, "description", pu.description());
        String providerName = getProvider(pu);
        writeElement(w, "provider", providerName);
        writeElement(w, "jta-data-source", pu.jtaDataSource());
        writeElement(w, "non-jta-data-source", pu.nonJtaDataSource());
        Map<String, String> props = new HashMap<>();
        addProperties(pu, props);
        addAnnProperties(units.get(pu), props);
        if (props.size() > 0) {
            w.writeStartElement("properties");
            for (String key : props.keySet()) {
                w.writeEmptyElement("property");
                w.writeAttribute("name", key);
                w.writeAttribute("value", props.get(key));
            }
            w.writeEndElement();
        }
        w.writeEndElement();
    }
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    w.close();
}
 
源代码13 项目: Course_Generator   文件: TrackData.java
public void SaveWaypoint(String name, int mask) {
	if (data.size() <= 0) {
		return;
	}

	// -- Save the data in the home directory
	XMLOutputFactory factory = XMLOutputFactory.newInstance();
	try {
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(name));
		XMLStreamWriter writer = new IndentingXMLStreamWriter(
				factory.createXMLStreamWriter(bufferedOutputStream, "UTF-8"));

		writer.writeStartDocument("UTF-8", "1.0");
		writer.writeStartElement("gpx");
		writer.writeAttribute("creator", "Course Generator http://www.techandrun.com");
		writer.writeAttribute("version", "1.1");
		writer.writeAttribute("xsi:schemaLocation",
				"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/WaypointExtension/v1 http://www8.garmin.com/xmlschemas/WaypointExtensionv1.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www8.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/ActivityExtension/v1 http://www8.garmin.com/xmlschemas/ActivityExtensionv1.xsd http://www.garmin.com/xmlschemas/AdventuresExtensions/v1 http://www8.garmin.com/xmlschemas/AdventuresExtensionv1.xsd http://www.garmin.com/xmlschemas/PressureExtension/v1 http://www.garmin.com/xmlschemas/PressureExtensionv1.xsd http://www.garmin.com/xmlschemas/TripExtensions/v1 http://www.garmin.com/xmlschemas/TripExtensionsv1.xsd http://www.garmin.com/xmlschemas/TripMetaDataExtensions/v1 http://www.garmin.com/xmlschemas/TripMetaDataExtensionsv1.xsd http://www.garmin.com/xmlschemas/ViaPointTransportationModeExtensions/v1 http://www.garmin.com/xmlschemas/ViaPointTransportationModeExtensionsv1.xsd http://www.garmin.com/xmlschemas/CreationTimeExtension/v1 http://www.garmin.com/xmlschemas/CreationTimeExtensionsv1.xsd http://www.garmin.com/xmlschemas/AccelerationExtension/v1 http://www.garmin.com/xmlschemas/AccelerationExtensionv1.xsd http://www.garmin.com/xmlschemas/PowerExtension/v1 http://www.garmin.com/xmlschemas/PowerExtensionv1.xsd http://www.garmin.com/xmlschemas/VideoExtension/v1 http://www.garmin.com/xmlschemas/VideoExtensionv1.xsd");
		writer.writeAttribute("xmlns", "http://www.topografix.com/GPX/1/1");
		writer.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		writer.writeAttribute("xmlns:wptx1", "http://www.garmin.com/xmlschemas/WaypointExtension/v1");
		writer.writeAttribute("xmlns:gpxtrx", "http://www.garmin.com/xmlschemas/GpxExtensions/v3");
		writer.writeAttribute("xmlns:gpxtpx", "http://www.garmin.com/xmlschemas/TrackPointExtension/v1");
		writer.writeAttribute("xmlns:gpxx", "http://www.garmin.com/xmlschemas/GpxExtensions/v3");
		writer.writeAttribute("xmlns:trp", "http://www.garmin.com/xmlschemas/TripExtensions/v1");
		writer.writeAttribute("xmlns:adv", "http://www.garmin.com/xmlschemas/AdventuresExtensions/v1");
		writer.writeAttribute("xmlns:prs", "http://www.garmin.com/xmlschemas/PressureExtension/v1");
		writer.writeAttribute("xmlns:tmd", "http://www.garmin.com/xmlschemas/TripMetaDataExtensions/v1");
		writer.writeAttribute("xmlns:vptm",
				"http://www.garmin.com/xmlschemas/ViaPointTransportationModeExtensions/v1");
		writer.writeAttribute("xmlns:ctx", "http://www.garmin.com/xmlschemas/CreationTimeExtension/v1");
		writer.writeAttribute("xmlns:gpxacc", "http://www.garmin.com/xmlschemas/AccelerationExtension/v1");
		writer.writeAttribute("xmlns:gpxpx", "http://www.garmin.com/xmlschemas/PowerExtension/v1");
		writer.writeAttribute("xmlns:vidx1", "http://www.garmin.com/xmlschemas/VideoExtension/v1");

		int i = 1;
		String s;
		for (CgData r : data) {
			if ((r.getTag() != 0) && ((r.getTag() & mask) != 0)) {
				// <wpt>
				writer.writeStartElement("wpt");
				writer.writeAttribute("lat", String.format(Locale.ROOT, "%1.14f", r.getLatitude()));
				writer.writeAttribute("lon", String.format(Locale.ROOT, "%1.14f", r.getLongitude()));

				// <time>2010-08-18T07:57:07.000Z</time>
				// Utils.WriteStringToXML(writer,"time",
				// r.getHour().toString()+"Z");

				// <name>toto</name>
				if (r.getName().isEmpty()) {
					Utils.WriteStringToXML(writer, "name", String.format("NoName%d", i));
					i++;
				} else
					Utils.WriteStringToXML(writer, "name", r.getName());

				// <sym>Flag, Green</sym>
				s = "Flag, Green"; // Par defaut
				if ((r.getTag() & CgConst.TAG_HIGH_PT) != 0)
					s = "Summit";
				if ((r.getTag() & CgConst.TAG_WATER_PT) != 0)
					s = "Bar";
				if ((r.getTag() & CgConst.TAG_EAT_PT) != 0)
					s = "Restaurant";

				Utils.WriteStringToXML(writer, "sym", s);

				// <type>user</type>
				Utils.WriteStringToXML(writer, "type", "user");

				writer.writeEndElement();// wpt
			} // if
		} // for
		writer.writeEndElement();// gpx
		writer.writeEndDocument();
		writer.flush();
		writer.close();
		CgLog.info("TrackData.SaveWaypoint : '" + name + "' saved");
	} catch (XMLStreamException | IOException e) {
		e.printStackTrace();
	}
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: WSDLFetcher.java
private String fetchFile(final String doc, DOMForest forest, final Map<String, String> documentMap, File destDir) throws IOException, XMLStreamException {

        DocumentLocationResolver docLocator = createDocResolver(doc, forest, documentMap);
        WSDLPatcher wsdlPatcher = new WSDLPatcher(new PortAddressResolver() {
            @Override
            public String getAddressFor(@NotNull QName serviceName, @NotNull String portName) {
                return null;
            }
        }, docLocator);

        XMLStreamReader xsr = null;
        XMLStreamWriter xsw = null;
        OutputStream os = null;
        String resolvedRootWsdl = null;
        try {
            XMLOutputFactory writerfactory;
            xsr = SourceReaderFactory.createSourceReader(new DOMSource(forest.get(doc)), false);
            writerfactory = XMLOutputFactory.newInstance();
            resolvedRootWsdl = docLocator.getLocationFor(null, doc);
            File outFile = new File(destDir, resolvedRootWsdl);
            os = new FileOutputStream(outFile);
            if(options.verbose) {
                listener.message(WscompileMessages.WSIMPORT_DOCUMENT_DOWNLOAD(doc,outFile));
            }
            xsw = writerfactory.createXMLStreamWriter(os);
            //DOMForest eats away the whitespace loosing all the indentation, so write it through
            // indenting writer for better readability of fetched documents
            IndentingXMLStreamWriter indentingWriter = new IndentingXMLStreamWriter(xsw);
            wsdlPatcher.bridge(xsr, indentingWriter);
            options.addGeneratedFile(outFile);
        } finally {
            try {
                if (xsr != null) {xsr.close();}
                if (xsw != null) {xsw.close();}
            } finally {
                if (os != null) {os.close();}
            }
        }
        return resolvedRootWsdl;


    }
 
源代码15 项目: kfs   文件: TemCorrectionDocumentServiceImpl.java
@Override
public void persistAgencyEntryGroupsForDocumentSave(TemCorrectionProcessDocument document, TemCorrectionForm correctionForm) {
    FileWriter out;
    try {
        out = new FileWriter(this.getBatchFileDirectoryName() + File.separator + correctionForm.getInputGroupId());
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(out);
        writer.writeStartDocument();
        writer.writeStartElement("agencyData");

        for (AgencyEntryFull agency: correctionForm.getAllEntries()) {
            writer.writeStartElement("record");
            writer.writeStartElement("creditCardOrAgencyCode"); writer.writeCharacters(agency.getCreditCardOrAgencyCode()); writer.writeEndElement();
            writer.writeStartElement("agency"); writer.writeCharacters(agency.getAgency()); writer.writeEndElement();
            writer.writeStartElement("agencyFileName"); writer.writeCharacters(agency.getAgencyFileName()); writer.writeEndElement();
            writer.writeStartElement("merchantName"); writer.writeCharacters(agency.getMerchantName()); writer.writeEndElement();
            writer.writeStartElement("tripInvoiceNumber"); writer.writeCharacters(agency.getTripInvoiceNumber()); writer.writeEndElement();
            writer.writeStartElement("travelerName"); writer.writeCharacters(agency.getTravelerName()); writer.writeEndElement();
            writer.writeStartElement("travelerId"); writer.writeCharacters(agency.getTravelerId()); writer.writeEndElement();
            writer.writeStartElement("tripExpenseAmount"); writer.writeCharacters(agency.getTripExpenseAmount().toString()); writer.writeEndElement();
            writer.writeStartElement("tripArrangerName"); writer.writeCharacters(agency.getTripArrangerName()); writer.writeEndElement();
            writer.writeStartElement("tripDepartureDate"); writer.writeCharacters(agency.getTripDepartureDate().toString()); writer.writeEndElement();
            writer.writeStartElement("airBookDate"); writer.writeCharacters(agency.getAirBookDate().toString()); writer.writeEndElement();
            writer.writeStartElement("airCarrierCode"); writer.writeCharacters(agency.getAirCarrierCode()); writer.writeEndElement();
            writer.writeStartElement("airTicketNumber"); writer.writeCharacters(agency.getAirTicketNumber()); writer.writeEndElement();
            writer.writeStartElement("pnrNumber"); writer.writeCharacters(agency.getPnrNumber()); writer.writeEndElement();
            writer.writeStartElement("transactionUniqueId"); writer.writeCharacters(agency.getTransactionUniqueId()); writer.writeEndElement();
            writer.writeStartElement("transactionPostingDate"); writer.writeCharacters(agency.getTransactionPostingDate().toString()); writer.writeEndElement();
            writer.writeEndElement(); // end the record element
        }


        writer.writeEndElement();
        writer.writeEndDocument();
        writer.close();
        out.close();
    }
    catch (IOException ioe) {
        throw new RuntimeException("Could not write XML for agency groups", ioe);
    }
    catch (XMLStreamException xmlse) {
        throw new RuntimeException("Could not write XML for agency groups", xmlse);
    }

}
 
源代码16 项目: phoebus   文件: ServletHelper.java
public static void submitXML(XMLStreamWriter writer) throws Exception
{
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
源代码17 项目: aion   文件: CfgNet.java
public String toXML() {
    final XMLOutputFactory output = XMLOutputFactory.newInstance();
    output.setProperty("escapeCharacters", false);
    XMLStreamWriter xmlWriter;
    String xml;
    try {
        Writer strWriter = new StringWriter();
        xmlWriter = output.createXMLStreamWriter(strWriter);

        // start element net
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeStartElement("net");

        // sub-element id
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("id");
        xmlWriter.writeCharacters(this.id + "");
        xmlWriter.writeEndElement();

        // sub-element nodes
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeStartElement("nodes");
        for (String node : nodes) {
            xmlWriter.writeCharacters("\r\n\t\t\t");
            xmlWriter.writeStartElement("node");
            xmlWriter.writeCharacters(node);
            xmlWriter.writeEndElement();
        }
        xmlWriter.writeCharacters("\r\n\t\t");
        xmlWriter.writeEndElement();

        // sub-element p2p
        xmlWriter.writeCharacters(this.p2p.toXML());

        // close element net
        xmlWriter.writeCharacters("\r\n\t");
        xmlWriter.writeEndElement();

        xml = strWriter.toString();
        strWriter.flush();
        strWriter.close();
        xmlWriter.flush();
        xmlWriter.close();
        return xml;
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码18 项目: flowable-engine   文件: BpmnXMLConverter.java
public byte[] convertToXML(BpmnModel model, String encoding) {
    try {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStreamWriter out = new OutputStreamWriter(outputStream, encoding);

        XMLStreamWriter writer = xof.createXMLStreamWriter(out);
        XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

        DefinitionsRootExport.writeRootElement(model, xtw, encoding);
        CollaborationExport.writePools(model, xtw);
        DataStoreExport.writeDataStores(model, xtw);
        SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw);
        EscalationDefinitionExport.writeEscalations(model, xtw);

        for (Process process : model.getProcesses()) {

            if (process.getFlowElements().isEmpty() && process.getLanes().isEmpty()) {
                // empty process, ignore it
                continue;
            }

            ProcessExport.writeProcess(process, model, xtw);

            for (FlowElement flowElement : process.getFlowElements()) {
                createXML(flowElement, model, xtw);
            }

            for (Artifact artifact : process.getArtifacts()) {
                createXML(artifact, model, xtw);
            }

            // end process element
            xtw.writeEndElement();
        }

        BPMNDIExport.writeBPMNDI(model, xtw);

        // end definitions root element
        xtw.writeEndElement();
        xtw.writeEndDocument();

        xtw.flush();

        outputStream.close();

        xtw.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        LOGGER.error("Error writing BPMN XML", e);
        throw new XMLException("Error writing BPMN XML", e);
    }
}
 
源代码19 项目: hottub   文件: WSDLFetcher.java
private String fetchFile(final String doc, DOMForest forest, final Map<String, String> documentMap, File destDir) throws IOException, XMLStreamException {

        DocumentLocationResolver docLocator = createDocResolver(doc, forest, documentMap);
        WSDLPatcher wsdlPatcher = new WSDLPatcher(new PortAddressResolver() {
            @Override
            public String getAddressFor(@NotNull QName serviceName, @NotNull String portName) {
                return null;
            }
        }, docLocator);

        XMLStreamReader xsr = null;
        XMLStreamWriter xsw = null;
        OutputStream os = null;
        String resolvedRootWsdl = null;
        try {
            XMLOutputFactory writerfactory;
            xsr = SourceReaderFactory.createSourceReader(new DOMSource(forest.get(doc)), false);
            writerfactory = XMLOutputFactory.newInstance();
            resolvedRootWsdl = docLocator.getLocationFor(null, doc);
            File outFile = new File(destDir, resolvedRootWsdl);
            os = new FileOutputStream(outFile);
            if(options.verbose) {
                listener.message(WscompileMessages.WSIMPORT_DOCUMENT_DOWNLOAD(doc,outFile));
            }
            xsw = writerfactory.createXMLStreamWriter(os);
            //DOMForest eats away the whitespace loosing all the indentation, so write it through
            // indenting writer for better readability of fetched documents
            IndentingXMLStreamWriter indentingWriter = new IndentingXMLStreamWriter(xsw);
            wsdlPatcher.bridge(xsr, indentingWriter);
            options.addGeneratedFile(outFile);
        } finally {
            try {
                if (xsr != null) {xsr.close();}
                if (xsw != null) {xsw.close();}
            } finally {
                if (os != null) {os.close();}
            }
        }
        return resolvedRootWsdl;


    }
 
源代码20 项目: openjdk-jdk9   文件: WriterTest.java
@Test
public void testTwo() {

    System.out.println("Test StreamWriter's Namespace Context");

    try {
        String outputFile = USER_DIR + files[1] + ".out";
        System.out.println("Writing output to " + outputFile);

        xtw = outputFactory.createXMLStreamWriter(System.out);
        xtw.writeStartDocument();
        xtw.writeStartElement("elemTwo");
        xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40");
        xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40");
        xtw.writeEndDocument();
        NamespaceContext nc = xtw.getNamespaceContext();
        // Got a Namespace Context.class

        XMLStreamWriter xtw1 = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);

        xtw1.writeComment("all elements here are explicitly in the HTML namespace");
        xtw1.setNamespaceContext(nc);
        xtw1.writeStartDocument("utf-8", "1.0");
        xtw1.setPrefix("htmlOne", "http://www.w3.org/TR/REC-html40");
        NamespaceContext nc1 = xtw1.getNamespaceContext();
        xtw1.close();
        Iterator it = nc1.getPrefixes("http://www.w3.org/TR/REC-html40");

        // FileWriter fw = new FileWriter(outputFile);
        while (it.hasNext()) {
            System.out.println("Prefixes :" + it.next());
            // fw.write((String)it.next());
            // fw.write(";");
        }
        // fw.close();
        // assertTrue(checkResults(testTwo+".out", testTwo+".org"));
        System.out.println("Done");
    } catch (Exception ex) {
        Assert.fail("testTwo Failed " + ex);
        ex.printStackTrace();
    }

}