Java Code Examples for javax.xml.stream.XMLStreamWriter#close()

The following examples show how to use javax.xml.stream.XMLStreamWriter#close() . 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: StaxUtilsTest.java    From cxf with Apache License 2.0 7 votes vote down vote up
@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());
}
 
Example 2
Source File: SurrogatesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: StaxDemo.java    From JavaCommon with Apache License 2.0 6 votes vote down vote up
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");
}
 
Example 4
Source File: JBossCliXmlConfigTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
}
 
Example 5
Source File: AbstractLoggingInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 6
Source File: XmiMappingWriter.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 7
Source File: XMLTransmitter.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
	}
}
 
Example 8
Source File: StaxUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 9
Source File: DataSources20TestCase.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 10
Source File: NoNSWriter.java    From softwarecave with GNU General Public License v3.0 5 votes vote down vote up
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();
        }
    }
}
 
Example 11
Source File: EntityXMLWriter.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 12
Source File: TemCorrectionDocumentServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
@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);
    }

}
 
Example 13
Source File: ServletHelper.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
public static void submitXML(XMLStreamWriter writer) throws Exception
{
    writer.writeEndDocument();
    writer.flush();
    writer.close();
}
 
Example 14
Source File: WSDLFetcher.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
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;


    }
 
Example 15
Source File: CfgNet.java    From aion with MIT License 4 votes vote down vote up
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 "";
    }
}
 
Example 16
Source File: TrackData.java    From Course_Generator with GNU General Public License v3.0 4 votes vote down vote up
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();
	}
}
 
Example 17
Source File: BpmnXMLConverter.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 18
Source File: JpaProcessor.java    From karaf-boot with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 19
Source File: WSDLFetcher.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
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;


    }
 
Example 20
Source File: WriterTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@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();
    }

}