List of usage examples for javax.xml.stream XMLStreamWriter writeStartDocument
public void writeStartDocument() throws XMLStreamException;
From source file:org.apache.olingo.commons.core.serialization.AtomSerializer.java
private void entity(final Writer outWriter, final Entity entity) throws XMLStreamException, EdmPrimitiveTypeException { final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(outWriter); if (entity.getType() == null && entity.getProperties().isEmpty()) { writer.writeStartDocument(); writer.setDefaultNamespace(namespaceMetadata); entityRef(writer, entity);// w w w .j a va2 s . co m } else { startDocument(writer, Constants.ATOM_ELEM_ENTRY); entity(writer, entity); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); }
From source file:org.apache.synapse.commons.json.JsonDataSource.java
public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { XMLStreamReader reader = getReader(); xmlWriter.writeStartDocument(); while (reader.hasNext()) { int x = reader.next(); switch (x) { case XMLStreamConstants.START_ELEMENT: xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI()); int namespaceCount = reader.getNamespaceCount(); for (int i = namespaceCount - 1; i >= 0; i--) { xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i)); }/*from w w w. ja va 2 s .co m*/ int attributeCount = reader.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i), reader.getAttributeLocalName(i), reader.getAttributeValue(i)); } break; case XMLStreamConstants.START_DOCUMENT: break; case XMLStreamConstants.CHARACTERS: xmlWriter.writeCharacters(reader.getText()); break; case XMLStreamConstants.CDATA: xmlWriter.writeCData(reader.getText()); break; case XMLStreamConstants.END_ELEMENT: xmlWriter.writeEndElement(); break; case XMLStreamConstants.END_DOCUMENT: xmlWriter.writeEndDocument(); break; case XMLStreamConstants.SPACE: break; case XMLStreamConstants.COMMENT: xmlWriter.writeComment(reader.getText()); break; case XMLStreamConstants.DTD: xmlWriter.writeDTD(reader.getText()); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData()); break; case XMLStreamConstants.ENTITY_REFERENCE: xmlWriter.writeEntityRef(reader.getLocalName()); break; default: throw new OMException(); } } xmlWriter.writeEndDocument(); xmlWriter.flush(); xmlWriter.close(); }
From source file:org.deegree.commons.xml.stax.FilteringXMLStreamWriterTest.java
private void writeDocument(XMLStreamWriter writer) throws XMLStreamException { writer.writeStartDocument(); writer.setPrefix("app", app); writer.setPrefix("nix", nix); writer.setPrefix("alles", alles); writer.writeStartElement(app, "a"); writer.writeNamespace("app", app); writer.writeNamespace("nix", nix); writer.writeNamespace("alles", alles); writer.writeStartElement(app, "b"); writer.writeStartElement(nix, "c"); writer.writeStartElement(app, "d"); writer.writeEndElement();//from w w w .ja v a 2s. c o m writer.writeStartElement(alles, "e"); writer.writeCharacters("sometext"); writer.writeEndElement(); writer.writeStartElement(app, "b"); writer.writeStartElement(nix, "c"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.close(); }
From source file:org.deegree.metadata.MetadataRecordFactory.java
/** * Creates a {@link MetadataRecord} instance out a {@link XMLStreamReader}. The reader must point to the * START_ELEMENT of the record. After reading the record the stream points to the END_ELEMENT of the record. * //w ww . j av a2s . c om * @param xmlStream * xmlStream must point to the START_ELEMENT of the record, must not be <code>null</code> * @return a {@link MetadataRecord} instance, never <code>null</code> */ public static MetadataRecord create(XMLStreamReader xmlStream) { if (!xmlStream.isStartElement()) { throw new XMLParsingException(xmlStream, "XMLStreamReader does not point to a START_ELEMENT."); } String ns = xmlStream.getNamespaceURI(); ByteArrayOutputStream out = new ByteArrayOutputStream(); XMLStreamWriter writer = null; XMLStreamReader recordAsXmlStream; InputStream in = null; try { writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); writer.writeStartDocument(); XMLAdapter.writeElement(writer, xmlStream); writer.writeEndDocument(); writer.close(); in = new ByteArrayInputStream(out.toByteArray()); recordAsXmlStream = XMLInputFactory.newInstance().createXMLStreamReader(in); } catch (XMLStreamException e) { throw new XMLParsingException(xmlStream, e.getMessage()); } catch (FactoryConfigurationError e) { throw new XMLParsingException(xmlStream, e.getMessage()); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (ISO_RECORD_NS.equals(ns)) { return new ISORecord(recordAsXmlStream); } if (RIM_NS.equals(ns)) { throw new UnsupportedOperationException( "Creating ebRIM records from XMLStreamReader is not implemented yet."); } if (DC_RECORD_NS.equals(ns)) { throw new UnsupportedOperationException( "Creating DC records from XMLStreamReader is not implemented yet."); } throw new IllegalArgumentException("Unknown / unsuppported metadata namespace '" + ns + "'."); }
From source file:org.deegree.tools.services.wms.FeatureTypesToLayerTree.java
/** * @param args/*from w w w . ja va 2s .c om*/ */ public static void main(String[] args) { Options options = initOptions(); // for the moment, using the CLI API there is no way to respond to a help argument; see // https://issues.apache.org/jira/browse/CLI-179 if (args.length == 0 || (args.length > 0 && (args[0].contains("help") || args[0].contains("?")))) { CommandUtils.printHelp(options, FeatureTypesToLayerTree.class.getSimpleName(), null, null); } XMLStreamWriter out = null; try { CommandLine line = new PosixParser().parse(options, args); String storeFile = line.getOptionValue("f"); String nm = new File(storeFile).getName(); String storeId = nm.substring(0, nm.length() - 4); FileOutputStream os = new FileOutputStream(line.getOptionValue("o")); XMLOutputFactory fac = XMLOutputFactory.newInstance(); out = new IndentingXMLStreamWriter(fac.createXMLStreamWriter(os)); out.setDefaultNamespace(ns); Workspace ws = new DefaultWorkspace(new File("nix")); ws.initAll(); DefaultResourceIdentifier<FeatureStore> identifier = new DefaultResourceIdentifier<FeatureStore>( FeatureStoreProvider.class, "unknown"); ws.add(new DefaultResourceLocation<FeatureStore>(new File(storeFile), identifier)); ws.prepare(identifier); FeatureStore store = ws.init(identifier, null); AppSchema schema = store.getSchema(); // prepare document out.writeStartDocument(); out.writeStartElement(ns, "deegreeWMS"); out.writeDefaultNamespace(ns); out.writeAttribute("configVersion", "0.5.0"); out.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); out.writeAttribute("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation", "http://www.deegree.org/services/wms http://schemas.deegree.org/wms/0.5.0/wms_configuration.xsd"); out.writeStartElement(ns, "ServiceConfiguration"); HashSet<FeatureType> visited = new HashSet<FeatureType>(); if (schema.getRootFeatureTypes().length == 1) { writeLayer(visited, out, schema.getRootFeatureTypes()[0], storeId); } else { out.writeCharacters("\n"); out.writeStartElement(ns, "UnrequestableLayer"); XMLAdapter.writeElement(out, ns, "Title", "Root Layer"); for (FeatureType ft : schema.getRootFeatureTypes()) { writeLayer(visited, out, ft, storeId); } out.writeEndElement(); out.writeCharacters("\n"); } out.writeEndElement(); out.writeEndElement(); out.writeEndDocument(); } catch (ParseException exp) { System.err.println(Messages.getMessage("TOOL_COMMANDLINE_ERROR", exp.getMessage())); CommandUtils.printHelp(options, FeatureTypesToLayerTree.class.getSimpleName(), null, null); } catch (ResourceInitException e) { LOG.info("The feature store could not be loaded: '{}'", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } catch (FileNotFoundException e) { LOG.info("A file could not be found: '{}'", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } catch (XMLStreamException e) { LOG.info("The XML output could not be written: '{}'", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } catch (FactoryConfigurationError e) { LOG.info("The XML system could not be initialized: '{}'", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } finally { if (out != null) { try { out.close(); } catch (XMLStreamException e) { LOG.trace("Stack trace:", e); } } } }
From source file:org.dita.dost.module.GenMapAndTopicListModule.java
private void writeExportAnchors() throws DITAOTException { if (INDEX_TYPE_ECLIPSEHELP.equals(transtype)) { // Output plugin id final File pluginIdFile = new File(job.tempDir, FILE_NAME_PLUGIN_XML); final DelayConrefUtils delayConrefUtils = new DelayConrefUtils(); delayConrefUtils.writeMapToXML(exportAnchorsFilter.getPluginMap(), pluginIdFile); XMLStreamWriter export = null; try (OutputStream exportStream = new FileOutputStream(new File(job.tempDir, FILE_NAME_EXPORT_XML))) { export = XMLOutputFactory.newInstance().createXMLStreamWriter(exportStream, "UTF-8"); export.writeStartDocument(); export.writeStartElement("stub"); for (final ExportAnchor e : exportAnchorsFilter.getExportAnchors()) { export.writeStartElement("file"); export.writeAttribute("name", tempFileNameScheme.generateTempFileName(toFile(e.file).toURI()).toString()); for (final String t : sort(e.topicids)) { export.writeStartElement("topicid"); export.writeAttribute("name", t); export.writeEndElement(); }// w w w. j a v a 2 s . c o m for (final String i : sort(e.ids)) { export.writeStartElement("id"); export.writeAttribute("name", i); export.writeEndElement(); } for (final String k : sort(e.keys)) { export.writeStartElement("keyref"); export.writeAttribute("name", k); export.writeEndElement(); } export.writeEndElement(); } export.writeEndElement(); export.writeEndDocument(); } catch (final IOException e) { throw new DITAOTException("Failed to write export anchor file: " + e.getMessage(), e); } catch (final XMLStreamException e) { throw new DITAOTException("Failed to serialize export anchor file: " + e.getMessage(), e); } finally { if (export != null) { try { export.close(); } catch (final XMLStreamException e) { logger.error("Failed to close export anchor file: " + e.getMessage(), e); } } } } }
From source file:org.dita.dost.reader.ChunkMapReader.java
/** * Create the new topic stump.// ww w. j ava 2s.com */ private void createTopicStump(final File newFile) { OutputStream newFileWriter = null; try { newFileWriter = new FileOutputStream(newFile); final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8); o.writeStartDocument(); o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + newFile.getParentFile().getAbsolutePath()); o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.getParentFile().toURI().toString()); o.writeStartElement(ELEMENT_NAME_DITA); o.writeEndElement(); o.writeEndDocument(); o.close(); newFileWriter.flush(); } catch (final RuntimeException e) { throw e; } catch (final Exception e) { logger.error(e.getMessage(), e); } finally { try { if (newFileWriter != null) { newFileWriter.close(); } } catch (final Exception e) { logger.error(e.getMessage(), e); } } }
From source file:org.eclipse.gyrex.logback.config.model.LogbackConfig.java
/** * Serializes the Logback configuration to the specified XML writer. * <p>/* w w w . j a v a 2 s . c om*/ * The XML is expected to be readable by Logback. As such, it depends * heavily on Logback and may be bound to different evolution/compatibility * rules. * </p> * * @param writer * the stream writer * @throws XMLStreamException */ @Override public void toXml(final XMLStreamWriter writer) throws XMLStreamException { writer.writeStartDocument(); writer.writeStartElement("configuration"); writer.writeAttribute("scan", "true"); writer.writeAttribute("scanPeriod", "2 minutes"); writeCommonProperties(writer); writeJulLevelChangePropagator(writer); for (final Appender appender : getAppenders().values()) { appender.toXml(writer); } for (final Logger logger : getLoggers().values()) { logger.toXml(writer); } writeRootLogger(writer); writer.writeEndElement(); writer.writeEndDocument(); }
From source file:org.exist.webstart.JnlpWriter.java
/** * Write JNLP xml file to browser.//from w w w. j av a 2s.c om * * @param response Object for writing to end user. * @throws java.io.IOException */ void writeJnlpXML(JnlpJarFiles jnlpFiles, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Writing JNLP file"); // Format URL: "http://host:8080/CONTEXT/webstart/exist.jnlp" final String currentUrl = request.getRequestURL().toString(); // Find BaseUrl http://host:8080/CONTEXT final int webstartPos = currentUrl.indexOf("/webstart"); final String existBaseUrl = currentUrl.substring(0, webstartPos); // Find codeBase for jarfiles http://host:8080/CONTEXT/webstart/ final String codeBase = existBaseUrl + "/webstart/"; // Perfom sanity checks int counter = 0; for (final File jar : jnlpFiles.getAllWebstartJars()) { counter++; // debugging if (jar == null || !jar.exists()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Jar file! (" + counter + ")"); return; } } // Find URL to connect to with client final String startUrl = existBaseUrl.replaceFirst("http:", "xmldb:exist:") .replaceFirst("https:", "xmldb:exist:").replaceAll("-", "%2D") + "/xmlrpc"; // response.setDateHeader("Last-Modified", mainJar.lastModified()); response.setContentType("application/x-java-jnlp-file"); try { final XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(response.getOutputStream()); writer.writeStartDocument(); writer.writeStartElement("jnlp"); writer.writeAttribute("spec", "1.0+"); writer.writeAttribute("codebase", codeBase); writer.writeAttribute("href", "exist.jnlp"); writer.writeStartElement("information"); writer.writeStartElement("title"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("vendor"); writer.writeCharacters("exist-db.org"); writer.writeEndElement(); writer.writeStartElement("homepage"); writer.writeAttribute("href", "http://exist-db.org"); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeCharacters("Integrated command-line and gui client, " + "entirely based on the XML:DB API and provides commands " + "for most database related tasks, like creating and " + "removing collections, user management, batch-loading " + "XML data or querying."); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeAttribute("kind", "short"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("description"); writer.writeAttribute("kind", "tooltip"); writer.writeCharacters("eXist XML-DB client"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_logo.jpg"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_128x128.gif"); writer.writeAttribute("width", "128"); writer.writeAttribute("height", "128"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_64x64.gif"); writer.writeAttribute("width", "64"); writer.writeAttribute("height", "64"); writer.writeEndElement(); writer.writeStartElement("icon"); writer.writeAttribute("href", "jnlp_icon_32x32.gif"); writer.writeAttribute("width", "32"); writer.writeAttribute("height", "32"); writer.writeEndElement(); writer.writeEndElement(); // information writer.writeStartElement("security"); writer.writeEmptyElement("all-permissions"); writer.writeEndElement(); // ---------- writer.writeStartElement("resources"); writer.writeStartElement("property"); writer.writeAttribute("name", "jnlp.packEnabled"); writer.writeAttribute("value", "true"); writer.writeEndElement(); writer.writeStartElement("j2se"); writer.writeAttribute("version", "1.6+"); writer.writeEndElement(); for (final File jar : jnlpFiles.getAllWebstartJars()) { writer.writeStartElement("jar"); writer.writeAttribute("href", jar.getName()); writer.writeAttribute("size", "" + jar.length()); writer.writeEndElement(); } writer.writeEndElement(); // resources writer.writeStartElement("application-desc"); writer.writeAttribute("main-class", "org.exist.client.InteractiveClient"); writer.writeStartElement("argument"); writer.writeCharacters("-ouri=" + startUrl); writer.writeEndElement(); writer.writeStartElement("argument"); writer.writeCharacters("--no-embedded-mode"); writer.writeEndElement(); if (request.isSecure()) { writer.writeStartElement("argument"); writer.writeCharacters("--use-ssl"); writer.writeEndElement(); } writer.writeEndElement(); // application-desc writer.writeEndElement(); // jnlp writer.writeEndDocument(); writer.flush(); writer.close(); } catch (final Throwable ex) { logger.error(ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private void handleBlobList(HttpServletRequest request, HttpServletResponse response, BlobStore blobStore, String containerName) throws IOException, S3Exception { String blobStoreType = getBlobStoreType(blobStore); ListContainerOptions options = new ListContainerOptions(); String encodingType = request.getParameter("encoding-type"); String delimiter = request.getParameter("delimiter"); if (delimiter != null) { options.delimiter(delimiter);// ww w .ja v a2 s . c om } else { options.recursive(); } String prefix = request.getParameter("prefix"); if (prefix != null && !prefix.isEmpty()) { options.prefix(prefix); } String marker = request.getParameter("marker"); if (marker != null) { if (Quirks.OPAQUE_MARKERS.contains(blobStoreType)) { String realMarker = lastKeyToMarker.getIfPresent(Maps.immutableEntry(containerName, marker)); if (realMarker != null) { marker = realMarker; } } options.afterMarker(marker); } int maxKeys = 1000; String maxKeysString = request.getParameter("max-keys"); if (maxKeysString != null) { try { maxKeys = Integer.parseInt(maxKeysString); } catch (NumberFormatException nfe) { throw new S3Exception(S3ErrorCode.INVALID_ARGUMENT, nfe); } if (maxKeys > 1000) { maxKeys = 1000; } } options.maxResults(maxKeys); response.setCharacterEncoding("UTF-8"); PageSet<? extends StorageMetadata> set = blobStore.list(containerName, options); try (Writer writer = response.getWriter()) { response.setStatus(HttpServletResponse.SC_OK); XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer); xml.writeStartDocument(); xml.writeStartElement("ListBucketResult"); xml.writeDefaultNamespace(AWS_XMLNS); writeSimpleElement(xml, "Name", containerName); if (prefix == null) { xml.writeEmptyElement("Prefix"); } else { writeSimpleElement(xml, "Prefix", encodeBlob(encodingType, prefix)); } writeSimpleElement(xml, "MaxKeys", String.valueOf(maxKeys)); if (marker == null) { xml.writeEmptyElement("Marker"); } else { writeSimpleElement(xml, "Marker", encodeBlob(encodingType, marker)); } if (delimiter != null) { writeSimpleElement(xml, "Delimiter", encodeBlob(encodingType, delimiter)); } if (encodingType != null && encodingType.equals("url")) { writeSimpleElement(xml, "EncodingType", encodingType); } String nextMarker = set.getNextMarker(); if (nextMarker != null) { writeSimpleElement(xml, "IsTruncated", "true"); writeSimpleElement(xml, "NextMarker", encodeBlob(encodingType, nextMarker)); if (Quirks.OPAQUE_MARKERS.contains(blobStoreType)) { lastKeyToMarker.put(Maps.immutableEntry(containerName, Iterables.getLast(set).getName()), nextMarker); } } else { writeSimpleElement(xml, "IsTruncated", "false"); } Set<String> commonPrefixes = new TreeSet<>(); for (StorageMetadata metadata : set) { switch (metadata.getType()) { case FOLDER: continue; case RELATIVE_PATH: commonPrefixes.add(metadata.getName()); continue; default: break; } xml.writeStartElement("Contents"); writeSimpleElement(xml, "Key", encodeBlob(encodingType, metadata.getName())); Date lastModified = metadata.getLastModified(); if (lastModified != null) { writeSimpleElement(xml, "LastModified", formatDate(lastModified)); } String eTag = metadata.getETag(); if (eTag != null) { writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag)); } writeSimpleElement(xml, "Size", String.valueOf(metadata.getSize())); writeSimpleElement(xml, "StorageClass", "STANDARD"); writeOwnerStanza(xml); xml.writeEndElement(); } for (String commonPrefix : commonPrefixes) { xml.writeStartElement("CommonPrefixes"); writeSimpleElement(xml, "Prefix", encodeBlob(encodingType, commonPrefix)); xml.writeEndElement(); } xml.writeEndElement(); xml.flush(); } catch (XMLStreamException xse) { throw new IOException(xse); } }