List of usage examples for javax.xml.stream XMLOutputFactory createXMLStreamWriter
public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;
From source file:org.intermine.template.xml.TemplateQueryBinding.java
/** * Convert a TemplateQuery to XML//from w w w .j av a 2s .c o m * * @param template the TemplateQuery * @return the corresponding XML String * @param version the version number of the XML format */ public static String marshal(TemplateQuery template, int version) { StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(sw); marshal(template, writer, version); } catch (XMLStreamException e) { throw new RuntimeException(e); } return sw.toString(); }
From source file:org.intermine.web.logic.template.TemplateHelper.java
/** * Given a Map of TemplateQueries (mapping from template name to TemplateQuery) * return a string containing each template seriaised as XML. The root element * will be a <code>template-queries</code> element. * * @param templates map from template name to TemplateQuery * @param version the version number of the XML format * @return all template queries serialised as XML * @see TemplateQuery/*from w w w. j a v a 2 s . co m*/ */ public static String templateMapToXml(Map<String, TemplateQuery> templates, int version) { StringWriter sw = new StringWriter(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(sw); writer.writeStartElement("template-queries"); for (TemplateQuery template : templates.values()) { TemplateQueryBinding.marshal(template, writer, version); } writer.writeEndElement(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return sw.toString(); }
From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java
public static void unload(ModelerFile file, List<String> definitionIdList) { File savedFile = file.getFile(); if (definitionIdList.isEmpty()) { return;// w ww.j a va 2 s . c o m } try { File cloneSavedFile = File.createTempFile("TMP", "job"); FileUtils.copyFile(savedFile, cloneSavedFile); BufferedReader br = new BufferedReader(new FileReader(savedFile)); String line = null; while ((line = br.readLine()) != null) { System.out.println("pre savedFile : " + 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"); 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 => Def Id is null // T => Transform // S => Skip if (xsr.getLocalName().equals("definitions")) { // if (definitionId == null) { // if (xsr.getAttributeValue(null, "id") != null) { // transformXMLStream(xsr, xsw); // } // } else { if (xsr.getAttributeValue(null, "id") == null) { System.out.println("transformXMLStream " + null); transformXMLStream(xsr, xsw); } else { if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) { System.out.println("transformXMLStream " + xsr.getAttributeValue(null, "id")); transformXMLStream(xsr, xsw); } else { System.out.println("skipXMLStream " + xsr.getAttributeValue(null, "id")); skipXMLStream(xsr); } } // } } System.out.println( "pre xsr.getEventType() : " + xsr.getEventType() + " " + xsr.getLocalName()); xsr.nextTag(); System.out.println( "post xsr.getEventType() : " + xsr.getEventType() + " " + xsr.getLocalName()); } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } } xsw.writeEndDocument(); xsw.close(); br = new BufferedReader(new FileReader(savedFile)); line = null; while ((line = br.readLine()) != null) { System.out.println("post savedFile : " + line); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
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 v a 2 s . c o m*/ 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 w w w . j av a 2s . 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.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() { {/*from ww w.j a v a2s.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.simbasecurity.core.saml.SAMLServiceImpl.java
@Override public String createAuthRequest(String authRequestId, Date issueInstant) throws XMLStreamException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(baos); writer.writeStartElement("samlp", "AuthnRequest", NS_SAMLP); writer.writeNamespace("samlp", NS_SAMLP); writer.writeAttribute("ID", "_" + authRequestId); writer.writeAttribute("Version", "2.0"); writer.writeAttribute("IssueInstant", SAML_DATE_FORMAT.format(issueInstant)); writer.writeAttribute("ForceAuthn", "false"); writer.writeAttribute("IsPassive", "false"); writer.writeAttribute("ProtocolBinding", BINDING_HTTP_POST); writer.writeAttribute("AssertionConsumerServiceURL", configurationService.getValue(SimbaConfigurationParameter.SAML_ASSERTION_CONSUMER_SERVICE_URL)); writer.writeStartElement("saml", "Issuer", NS_SAML); writer.writeNamespace("saml", NS_SAML); writer.writeCharacters(configurationService.getValue(SimbaConfigurationParameter.SAML_ISSUER)); writer.writeEndElement();/*from w ww .j a va 2 s . com*/ writer.writeStartElement("samlp", "NameIDPolicy", NS_SAMLP); writer.writeAttribute("Format", NAMEID_TRANSIENT); writer.writeAttribute("SPNameQualifier", configurationService.getValue(SimbaConfigurationParameter.SAML_ISSUER)); writer.writeAttribute("AllowCreate", "true"); writer.writeEndElement(); writer.writeStartElement("samlp", "RequestedAuthnContext", NS_SAMLP); writer.writeNamespace("samlp", NS_SAMLP); writer.writeAttribute("Comparison", "exact"); writer.writeStartElement("saml", "AuthnContextClassRef", NS_SAML); writer.writeNamespace("saml", NS_SAML); writer.writeCharacters(AC_FAS_EID); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.flush(); return encodeSAMLRequest(baos.toByteArray()); }
From source file:org.simbasecurity.core.saml.SAMLServiceImpl.java
@Override public String createLogoutRequest(String logoutRequestId, Date issueInstant, String nameId, String sessionIndex) throws XMLStreamException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(baos); writer.writeStartElement("samlp", "LogoutRequest", NS_SAMLP); writer.writeNamespace("samlp", NS_SAMLP); writer.writeAttribute("ID", "_" + logoutRequestId); writer.writeAttribute("Version", "2.0"); writer.writeAttribute("IssueInstant", SAML_DATE_FORMAT.format(issueInstant)); writer.writeStartElement("saml", "Issuer", NS_SAML); writer.writeNamespace("saml", NS_SAML); writer.writeCharacters("https://iamapps.belgium.be/"); writer.writeEndElement();/*from w w w . ja v a 2s.c o m*/ writer.writeStartElement("saml", "NameID", NS_SAML); writer.writeNamespace("saml", NS_SAML); writer.writeAttribute("NameQualifier", configurationService.getValue(SimbaConfigurationParameter.SAML_IDP_SLO_TARGET_URL)); writer.writeAttribute("SPNameQualifier", "https://iamapps.belgium.be/"); writer.writeAttribute("Format", NAMEID_TRANSIENT); writer.writeCharacters(nameId); writer.writeEndElement(); writer.writeStartElement("samlp", "SessionIndex", NS_SAMLP); writer.writeNamespace("saml", NS_SAMLP); writer.writeCharacters(sessionIndex); writer.writeEndElement(); writer.writeEndElement(); writer.flush(); return encodeSAMLRequest(baos.toByteArray()); }
From source file:org.staxcel.internal.SpreadSheetImpl.java
protected void flushDynamicTemplateWriter(TokenEnumerableTemplateWriter templateWriter, XMLOutputFactory xmlOutFactory) throws IOException { String token = templateWriter.getToken(); while (token != null) { XMLStreamWriter xmlWriter = null; try {//from ww w . j a va 2s . co m if (token.equals("worksheets.count")) { templateWriter.getOutputWriter().write(String.valueOf(this.worksheetList.size())); } else if (token.equals("worksheets.vector")) { xmlWriter = xmlOutFactory.createXMLStreamWriter(appXmlTemplateWriter.getOutputWriter()); xmlWriter.writeStartElement("vt:vector"); xmlWriter.writeAttribute("size", String.valueOf(this.worksheetList.size())); xmlWriter.writeAttribute("baseType", "lpstr"); for (int index = 0; index < this.worksheetList.size(); ++index) { xmlWriter.writeStartElement("vt:lpstr"); xmlWriter.writeCharacters(this.worksheetList.get(index).getName()); xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); } else if (token.equals("worksheet.relationships")) { xmlWriter = xmlOutFactory.createXMLStreamWriter(templateWriter.getOutputWriter()); for (int index = 0; index < worksheetList.size(); ++index) { WorksheetImpl worksheet = worksheetList.get(index); xmlWriter.writeStartElement("Relationship"); xmlWriter.writeAttribute("Id", "rId" + worksheet.getResourceId()); xmlWriter.writeAttribute("Type", OpenXMLNamespace.NS_OPENXML_OFFICE_DOC_2006_REL_WORKSHEET); xmlWriter.writeAttribute("Target", "worksheets/sheet" + worksheet.getWorksheetNumber() + ".xml"); xmlWriter.writeEndElement(); } } else if (token.equals("workbook.sheets")) { xmlWriter = xmlOutFactory.createXMLStreamWriter(templateWriter.getOutputWriter()); for (int index = 0; index < worksheetList.size(); ++index) { WorksheetImpl worksheet = worksheetList.get(index); xmlWriter.writeStartElement("sheet"); xmlWriter.writeAttribute("name", "Sheet" + worksheet.getWorksheetNumber()); xmlWriter.writeAttribute("sheetId", String.valueOf(worksheet.getWorksheetNumber())); xmlWriter.writeAttribute("r:id", "rId" + worksheet.getResourceId()); xmlWriter.writeEndElement(); } } else { // unknown. Invoke a protected method which can be // overridden by derived classes // to add new template variables and interpret them // accordingly. expandToken(token, templateWriter); } } catch (XMLStreamException ex) { throw new StaxcelException("Error when replacing " + token + " from template file", ex); } finally { if (xmlWriter != null) { try { xmlWriter.flush(); xmlWriter.close(); } catch (XMLStreamException ex2) { logger.error("Error when closing xmlstream", ex2); } } } token = templateWriter.nextElement(); } templateWriter.getOutputWriter().flush(); templateWriter.getOutputWriter().close(); }
From source file:org.tolven.app.bean.DataExtractBean.java
public void streamResultsXML(Writer out, DataQueryResults dq) { Long totalCount = null;/* w ww. j a va 2 s .c om*/ if (dq.isReturnTotalCount()) { getMDQueryResults(dq, true); totalCount = (Long) dq.getIterator().next(); } if (dq.getLimit() != 0) { getMDQueryResults(dq, false); } try { XMLStreamWriter xmlStreamWriter = null; try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); xmlStreamWriter = factory.createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument("UTF-8", "1.0"); xmlStreamWriter.writeStartElement("results"); xmlStreamWriter.writeAttribute("path", dq.getPath()); xmlStreamWriter.writeAttribute("account", String.valueOf(dq.getAccount().getId())); xmlStreamWriter.writeAttribute("database", getTolvenPropertiesBean().getProperty("tolven.repository.oid")); GregorianCalendar nowCal = new GregorianCalendar(); nowCal.setTime(dq.getNow()); DatatypeFactory xmlFactory = DatatypeFactory.newInstance(); XMLGregorianCalendar ts = xmlFactory.newXMLGregorianCalendar(nowCal); xmlStreamWriter.writeAttribute("timestamp", ts.toXMLFormat()); if (!dq.isItemQuery()) { xmlStreamWriter.writeAttribute("offset", Long.toString(dq.getOffset())); xmlStreamWriter.writeAttribute("limit", Long.toString(dq.getLimit())); xmlStreamWriter.writeAttribute("count", Long.toString(dq.getCount())); } if (!dq.isItemQuery() && totalCount != null) { xmlStreamWriter.writeAttribute("totalCount", totalCount.toString()); } addExtendedFields(dq); //addPlaceholderIds(dq); if (MenuStructure.PLACEHOLDER.equals(dq.getMenuStructure().getRole())) { addParentFields(dq); } addSimpleXMLColumnHeadings(dq, xmlStreamWriter); if (dq.getLimit() != 0) { addXMLRows(dq, xmlStreamWriter); } xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); } finally { if (xmlStreamWriter != null) { xmlStreamWriter.close(); } } } catch (Exception ex) { throw new RuntimeException("Could not obtain XML results for menupath: " + dq.getPath() + " in account: " + dq.getAccount().getId(), ex); } }