List of usage examples for javax.xml.stream XMLStreamWriter writeEndDocument
public void writeEndDocument() throws XMLStreamException;
From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java
public void saveModelerFile(ModelerFile modelerFile) { Definitions definitions = (Definitions) modelerFile.getDefinitionElement(); try {// ww w . j a va 2 s . com updateBatchDiagram(modelerFile); List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions()); List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList); // definitionIdList.addAll(definitions.getGarbageDefinitions()); definitionIdList.add(definitions.getId()); File savedFile = modelerFile.getFile(); BufferedReader br = new BufferedReader(new FileReader(savedFile)); String line = null; while ((line = br.readLine()) != null) { System.out.println("savedFile : " + line); } File cloneSavedFile = File.createTempFile("TMP", "job"); FileUtils.copyFile(savedFile, cloneSavedFile); // br = new BufferedReader(new FileReader(cloneSavedFile)); // line = null; // while ((line = br.readLine()) != null) { // System.out.println("line2 : " + line); // } XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile)); xsw.setDefaultNamespace("http://jbatchsuite.java.net"); xsw.writeStartDocument(); xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net"); xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee"); xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net"); xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270"); xsw.writeNamespace("nbm", "http://nbmodeler.java.net"); // br = new BufferedReader(new FileReader(savedFile)); // line = null; // while ((line = br.readLine()) != null) { // System.out.println("line3 : " + line); // } if (cloneSavedFile.length() != 0) { try { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource(cloneSavedFile); XMLStreamReader xsr = xif.createXMLStreamReader(xml); xsr.nextTag(); while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) { // Def Y N // Tag N(D) Y(D) // ________________ // T T // ---------------- // // Def Y N // Tag Y(S) N(S) // ________________ // S S // ---------------- // // Def Y N // Tag Y(D) N(S) // ________________ // T S // ---------------- // // (D) => Different // (S) => Same // Y => Id Exist // N => Id is null // T => Transform // S => Skip if (xsr.getLocalName().equals("definitions")) { // if (definitions.getId() == null) { // if (xsr.getAttributeValue(null, "id") != null) { // transformXMLStream(xsr, xsw); // } else { // skipXMLStream(xsr); // } // } else { if (xsr.getAttributeValue(null, "id") == null) { if (definitions.getId() == null) { skipXMLStream(xsr); } else { transformXMLStream(xsr, xsw); } } else { if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) { transformXMLStream(xsr, xsw); } else { skipXMLStream(xsr); } } // } } xsr.nextTag(); } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } } JAXBElement<Definitions> je = new JAXBElement<Definitions>( new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class, definitions); if (jobContext == null) { jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class }); } if (jobMarshaller == null) { jobMarshaller = jobContext.createMarshaller(); } // output pretty printed jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd"); jobMarshaller.setEventHandler(new ValidateJAXB()); jobMarshaller.marshal(je, System.out); jobMarshaller.marshal(je, xsw); // xsw.writeEndElement(); xsw.writeEndDocument(); xsw.close(); // StringWriter sw = new StringWriter(); // jobMarshaller.marshal(file.getDefinitionElement(), sw); // FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"", // "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\"")); } catch (JAXBException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.ops4j.pax.exam.karaf.container.internal.DependenciesDeployer.java
/** * Write a feature xml structure for test dependencies specified as ProvisionOption * in system to the given writer/*from ww w. j a v a 2 s .co m*/ * * @param writer where to write the feature xml * @param provisionOptions dependencies */ static void writeDependenciesFeature(Writer writer, ProvisionOption<?>... provisionOptions) { XMLOutputFactory xof = XMLOutputFactory.newInstance(); xof.setProperty("javax.xml.stream.isRepairingNamespaces", true); XMLStreamWriter sw = null; try { sw = xof.createXMLStreamWriter(writer); sw.writeStartDocument("UTF-8", "1.0"); sw.setDefaultNamespace(KARAF_FEATURE_NS); sw.writeCharacters("\n"); sw.writeStartElement("features"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); sw.writeStartElement("feature"); sw.writeAttribute("name", "test-dependencies"); sw.writeCharacters("\n"); for (ProvisionOption<?> provisionOption : provisionOptions) { if (provisionOption.getURL().startsWith("link") || provisionOption.getURL().startsWith("scan-features")) { // well those we've already handled at another location... continue; } sw.writeStartElement("bundle"); if (provisionOption.getStartLevel() != null) { sw.writeAttribute("start-level", provisionOption.getStartLevel().toString()); } sw.writeCharacters(provisionOption.getURL()); endElement(sw); } endElement(sw); endElement(sw); sw.writeEndDocument(); } catch (XMLStreamException e) { throw new RuntimeException("Error writing feature " + e.getMessage(), e); } finally { close(sw); } }
From source file:org.osaf.cosmo.dav.impl.StandardDavResponse.java
public void sendDavError(DavException e) throws IOException { setStatus(e.getErrorCode());/*from w ww.j a va 2 s . c o m*/ if (!e.hasContent()) return; XMLStreamWriter writer = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); writer.writeStartDocument(); e.writeTo(writer); writer.writeEndDocument(); setContentType("text/xml; charset=UTF-8"); byte[] bytes = out.toByteArray(); setContentLength(bytes.length); getOutputStream().write(bytes); } catch (Throwable e2) { log.error("Error writing XML", e2); log.error("Original exception", e); setStatus(500); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException e2) { log.warn("Unable to close XML writer", e2); } } } }
From source file:org.osaf.cosmo.mc.CollectionService.java
public void writeTo(OutputStream out) throws IOException, XMLStreamException { XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); writer.setPrefix(PRE_XML, NS_XML);//from w ww. j av a 2s. co m writer.setDefaultNamespace(NS_MC); try { writer.writeStartDocument(); writer.writeStartElement(EL_MC_SERVICE); writer.writeDefaultNamespace(NS_MC); writer.writeAttribute(NS_XML, EL_XML_BASE, locator.getMorseCodeBase()); for (CollectionItem collection : collections) { writer.writeStartElement(EL_MC_COLLECTION); writer.writeAttribute(ATTR_MC_UUID, collection.getUid()); writer.writeAttribute(ATTR_MC_HREF, href(collection)); writer.writeStartElement(EL_MC_NAME); writer.writeCharacters(collection.getDisplayName()); writer.writeEndElement(); for (Ticket ticket : visibleTickets(collection)) { writer.writeStartElement(EL_MC_TICKET); writer.writeAttribute(ATTR_MC_TYPE, ticket.getType().toString()); writer.writeCharacters(ticket.getKey()); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); } finally { writer.close(); } }
From source file:org.osaf.cosmo.mc.MorseCodeServlet.java
private void handleGeneralException(MorseCodeException e, HttpServletResponse resp) throws IOException { if (e.getCode() >= 500) log.error("Unknown Morse Code exception", e); else if (e.getCode() >= 400) log.info("Client error (" + e.getCode() + "): " + e.getMessage()); resp.setStatus(e.getCode());//from ww w . j a va2 s . c om if (!e.hasContent()) return; XMLStreamWriter writer = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); writer.writeStartDocument(); e.writeTo(writer); writer.writeEndDocument(); resp.setContentType("application/xml"); byte[] bytes = out.toByteArray(); resp.setContentLength(bytes.length); resp.getOutputStream().write(bytes); } catch (Throwable e2) { log.error("Error writing XML", e2); log.error("Original exception", e); resp.setStatus(500); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException e2) { log.warn("Unable to close XML writer", e2); } } } }
From source file:org.plasma.sdo.xml.StreamMarshaller.java
private void write(XMLStreamWriter writer) throws XMLStreamException { setup();//from w ww . j av a 2s . c o m if (this.document.isXMLDeclaration()) { String encoding = findEncoding(); if (encoding != null) writer.writeStartDocument(encoding, this.document.getXMLVersion()); else writer.writeStartDocument(this.document.getXMLVersion()); } // Write a processing instruction //writer.writeProcessingInstruction( // "xml-stylesheet href='catalog.xsl' type='text/xsl'"); if (this.document.getRootElementName() != null) { //writer.writeDefaultNamespace(this.document.getRootElementURI()); writer.writeStartElement(namespacePrefix, this.document.getRootElementName(), this.document.getRootElementURI()); writeRootAttributes(writer); } EventVisitor visitor = new EventVisitor(writer); ((PlasmaDataObject) this.document.getRootObject()).accept(visitor); if (this.document.getRootElementName() != null) { writer.writeEndElement(); } writer.writeEndDocument(); }
From source file:org.qi4j.valueserialization.stax.StaxValueSerializer.java
@Override protected void onSerializationEnd(Object object, XMLStreamWriter output) throws Exception { output.writeEndDocument(); output.flush();//from ww w . j a v a 2 s. c om output.close(); }
From source file:org.rhq.enterprise.server.sync.ExportingInputStream.java
/** * @param wrt//from w w w .j a v a 2 s.com * @throws XMLStreamException */ private void exportEpilogue(XMLStreamWriter wrt) throws XMLStreamException { wrt.writeEndDocument(); }
From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java
public void testCanExportAndImportState() throws Exception { final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class); final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager); context.checking(new Expectations() { {// w ww .j a v a 2 s. co m oneOf(pluginManager).getInstalledPlugins(); will(returnValue(new ArrayList<Plugin>(getDeployedPlugins()))); } }); validator.initialize(null, null); StringWriter output = new StringWriter(); try { XMLOutputFactory ofactory = XMLOutputFactory.newInstance(); XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output); //wrap the exported plugins in "something" so that we produce //a valid xml wrt.writeStartDocument(); wrt.writeStartElement("root"); validator.exportState(new ExportWriter(wrt)); wrt.writeEndDocument(); wrt.close(); StringReader input = new StringReader(output.toString()); try { XMLInputFactory ifactory = XMLInputFactory.newInstance(); XMLStreamReader rdr = ifactory.createXMLStreamReader(input); //push the reader to the start of the plugin elements //this is what is expected by the validators rdr.nextTag(); validator.initializeExportedStateValidation(new ExportReader(rdr)); rdr.close(); assertEquals(validator.getPluginsToValidate(), getDeployedPlugins()); } finally { input.close(); } } catch (Exception e) { LOG.error("Test failed. Output generated so far:\n" + output, e); throw e; } finally { output.close(); } }
From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java
private static void updateFile(File configFile, Map<String, PropertySimple> allProps) throws IOException, InterruptedException, XMLStreamException { InputStream in = null;/*w w w.j av a 2 s . c om*/ XMLStreamReader rdr = null; OutputStream out = null; XMLStreamWriter outWrt = null; try { Set<String> processedPropertyNames = new HashSet<String>(); in = new BufferedInputStream(new FileInputStream(configFile)); rdr = XML_INPUT_FACTORY.createXMLStreamReader(in); File tmpFile = File.createTempFile("hadoop-plugin", null); out = new FileOutputStream(tmpFile); outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out); ByteArrayOutputStream stash = new ByteArrayOutputStream(); XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash); boolean outputActive = true; outWrt.writeStartDocument(); while (rdr.hasNext()) { int event = rdr.next(); XMLStreamWriter wrt = outputActive ? outWrt : stashWrt; switch (event) { case XMLStreamConstants.ATTRIBUTE: break; case XMLStreamConstants.CDATA: wrt.writeCData(rdr.getText()); break; case XMLStreamConstants.CHARACTERS: wrt.writeCharacters(rdr.getText()); break; case XMLStreamConstants.COMMENT: wrt.writeComment(rdr.getText()); break; case XMLStreamConstants.DTD: wrt.writeDTD(rdr.getText()); break; case XMLStreamConstants.END_DOCUMENT: wrt.writeEndDocument(); break; case XMLStreamConstants.END_ELEMENT: if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) { String encoding = rdr.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } String propertyTagSoFar = Charset.forName(encoding) .decode(ByteBuffer.wrap(stash.toByteArray())).toString(); DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps); //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write. outWrt.flush(); out.write(propAndTag.updatedTag.getBytes("UTF-8")); processedPropertyNames.add(propAndTag.propertyName); //reset stuff stash.reset(); wrt = outWrt; outputActive = true; } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) { //now add the new props for (String prop : processedPropertyNames) { allProps.remove(prop); } for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) { outWrt.writeStartElement(PROPERTY_TAG_NAME); outWrt.writeStartElement(NAME_TAG_NAME); outWrt.writeCharacters(e.getKey()); outWrt.writeEndElement(); outWrt.writeStartElement(VALUE_TAG_NAME); outWrt.writeCharacters(e.getValue().getStringValue()); outWrt.writeEndElement(); outWrt.writeEndElement(); } } wrt.writeEndElement(); break; case XMLStreamConstants.ENTITY_DECLARATION: //XXX could not find what to do with this break; case XMLStreamConstants.ENTITY_REFERENCE: wrt.writeEntityRef(rdr.getText()); break; case XMLStreamConstants.NAMESPACE: for (int i = 0; i < rdr.getNamespaceCount(); ++i) { wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i)); } break; case XMLStreamConstants.NOTATION_DECLARATION: //XXX could not find what to do with this break; case XMLStreamConstants.PROCESSING_INSTRUCTION: wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData()); break; case XMLStreamConstants.SPACE: wrt.writeCharacters(rdr.getText()); break; case XMLStreamConstants.START_DOCUMENT: //this seems to be never called for some strange reason //wrt.writeStartDocument(); break; case XMLStreamConstants.START_ELEMENT: wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(), rdr.getName().getNamespaceURI()); for (int i = 0; i < rdr.getAttributeCount(); ++i) { wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i), rdr.getAttributeLocalName(i), rdr.getAttributeValue(i)); } if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) { wrt.writeCharacters(""); outputActive = false; } break; } } outWrt.flush(); out.flush(); out.close(); in.close(); //now copy the temp file in the place of the original one FileUtil.copyFile(tmpFile, configFile); } finally { rdr.close(); outWrt.flush(); outWrt.close(); try { in.close(); } finally { out.flush(); out.close(); } } }