Example usage for javax.xml.stream XMLOutputFactory setProperty

List of usage examples for javax.xml.stream XMLOutputFactory setProperty

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory setProperty.

Prototype

public abstract void setProperty(java.lang.String name, Object value) throws IllegalArgumentException;

Source Link

Document

Allows the user to set specific features/properties on the underlying implementation.

Usage

From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java

/**
 * This method creates the XMI file. Created content is:<br/>
 * <code>&lt;?xml version="{@link XMIConstants4SchemaGraph2XMI#XML_VERSION}" encoding="{@link XMIConstants4SchemaGraph2XMI#XML_ENCODING}"?&gt;<br/>
 * &lt;!-- content created by {@link SchemaGraph2XMI#createRootElement(XMLStreamWriter, SchemaGraph)} --&gt;
 * </code>//  www  . j a v a2 s. com
 * 
 * @param xmiName
 *            {@link String} the path of the XMI file
 * @param schemaGraph
 *            {@link SchemaGraph} to be converted into an XMI
 * @throws XMLStreamException
 * @throws IOException
 */
private void createXMI(String xmiName, SchemaGraph schemaGraph) throws XMLStreamException, IOException {
    Writer out = null;
    XMLStreamWriter writer = null;
    try {
        // create the XMLStreamWriter which creates the current xmi-file.
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmiName), "UTF-8"));
        XMLOutputFactory factory = XMLOutputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE);
        writer = factory.createXMLStreamWriter(out);

        // write the first line
        writer.writeStartDocument(XMIConstants4SchemaGraph2XMI.XML_ENCODING,
                XMIConstants4SchemaGraph2XMI.XML_VERSION);
        createRootElement(writer, schemaGraph);
        // write the end of the document
        writer.writeEndDocument();

        // close the XMLStreamWriter
        writer.flush();
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // no handling of exceptions, because they are throw as mentioned in
        // the declaration.
        if (writer != null) {
            writer.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.apache.axiom.om.util.StAXUtils.java

private static XMLOutputFactory newXMLOutputFactory(final ClassLoader classLoader,
        final StAXWriterConfiguration configuration) {
    return (XMLOutputFactory) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            ClassLoader savedClassLoader;
            if (classLoader == null) {
                savedClassLoader = null;
            } else {
                savedClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
            }/*ww w  .j a  v a  2 s  .co  m*/
            try {
                XMLOutputFactory factory = XMLOutputFactory.newInstance();
                factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
                Map props = loadFactoryProperties("XMLOutputFactory.properties");
                if (props != null) {
                    for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        factory.setProperty((String) entry.getKey(), entry.getValue());
                    }
                }
                StAXDialect dialect = StAXDialectDetector.getDialect(factory.getClass());
                if (configuration != null) {
                    factory = configuration.configure(factory, dialect);
                }
                return new ImmutableXMLOutputFactory(dialect.normalize(dialect.makeThreadSafe(factory)));
            } finally {
                if (savedClassLoader != null) {
                    Thread.currentThread().setContextClassLoader(savedClassLoader);
                }
            }
        }
    });
}

From source file:org.deegree.geometry.wkbadapter.WKBReaderTest.java

@Test
public void testWKBToGML() throws Exception {
    ICRS crs = CRSManager.lookup("EPSG:4326");

    InputStream is = WKBReaderTest.class.getResourceAsStream(BASE_DIR + "Polygon.wkb");
    byte[] wkb = IOUtils.toByteArray(is);

    Polygon geom = (Polygon) WKBReader.read(wkb, crs);
    assertTrue(geom.getGeometryType() == GeometryType.PRIMITIVE_GEOMETRY);

    StringWriter sw = new StringWriter();
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    outFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

    XMLStreamWriter writer = outFactory.createXMLStreamWriter(sw);
    writer.setDefaultNamespace(CommonNamespaces.GML3_2_NS);
    GMLStreamWriter gmlSw = GMLOutputFactory.createGMLStreamWriter(GMLVersion.GML_32, writer);
    gmlSw.write(geom);//from  w ww.  j  a  v a2 s.co m
    writer.close();

    String s = "<gml:posList>5.148530 59.951879 5.134692 59.736522 5.561175 59.728897 5.577771 59.944188 5.148530 59.951879</gml:posList>";
    assertTrue(sw.toString().contains(s));
}

From source file:org.deegree.protocol.wps.client.wps100.ExecuteResponse100Reader.java

/**
 * <ul>//from  w  w w .  j a  v a  2  s  .co  m
 * <li>Precondition: cursor must point at the <code>START_ELEMENT</code> event (&lt;wps:ComplexData&gt;)</li>
 * <li>Postcondition: cursor points at the corresponding <code>END_ELEMENT</code> event (&lt;/wps:ComplexData&gt;)</li>
 * </ul>
 * 
 * @return
 * @throws XMLStreamException
 * @throws IOException
 */
private ExecutionOutput parseComplexOutput(CodeType id) throws XMLStreamException {

    ComplexFormat attribs = parseComplexAttributes();

    StreamBufferStore tmpSink = new StreamBufferStore();
    try {
        if (attribs.getMimeType().startsWith("text/xml")
                || attribs.getMimeType().startsWith("application/xml")) {
            XMLOutputFactory fac = XMLOutputFactory.newInstance();
            fac.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
            XMLStreamWriter xmlWriter = fac.createXMLStreamWriter(tmpSink, "UTF-8");

            XMLStreamUtils.nextElement(reader);

            xmlWriter.writeStartDocument("UTF-8", "1.0");
            if (reader.getEventType() == START_ELEMENT) {
                XMLAdapter.writeElement(xmlWriter, reader);
                XMLStreamUtils.nextElement(reader);
            } else {
                LOG.debug("Response document contains empty complex data output '" + id + "'");
            }
            xmlWriter.writeEndDocument();
            xmlWriter.close();

        } else {
            if ("base64".equals(attribs.getEncoding())) {
                String base64String = reader.getElementText();
                byte[] bytes = Base64.decodeBase64(base64String);
                tmpSink.write(bytes);
            } else {
                LOG.warn("The encoding of binary data (found at response location " + reader.getLocation()
                        + ") is not base64. Currently only for this format the decoding can be performed. Skipping the data.");
            }
        }
        tmpSink.close();
    } catch (IOException e) {
        LOG.error(e.getMessage());
    }
    return new ComplexOutput(id, tmpSink, attribs.getMimeType(), attribs.getEncoding(), attribs.getEncoding());
}

From source file:org.deegree.services.wcs.WCSController.java

private void doGetCapabilities(GetCapabilities request, HttpServletRequest requestWrapper,
        HttpResponseBuffer response) throws IOException, XMLStreamException, OWSException {

    Set<Sections> sections = getSections(request);

    Version negotiateVersion = negotiateVersion(request);
    // if update sequence is given and matches the given update sequence an error should occur
    // http://cite.opengeospatial.org/OGCTestData/wcs/1.0.0/specs/03-065r6.html#7.2.1_Key-value_pair_encoding
    if (negotiateVersion.equals(VERSION_100)) {
        String updateSeq = request.getUpdateSequence();
        int requestedUS = UPDATE_SEQUENCE - 1;
        try {//from  www .ja  v a2 s .  c  om
            requestedUS = Integer.parseInt(updateSeq);
        } catch (NumberFormatException e) {
            // nothing to do, just ignore it.
        }
        if (requestedUS == UPDATE_SEQUENCE) {
            throw new OWSException("Update sequence may not be equal than server's current update sequence.",
                    WCSConstants.ExeptionCode_1_0_0.CurrentUpdateSequence.name());
        } else if (requestedUS > UPDATE_SEQUENCE) {
            throw new OWSException("Update sequence may not be higher than server's current update sequence.",
                    WCSConstants.ExeptionCode_1_0_0.InvalidUpdateSequence.name());
        }
    }

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(IS_REPAIRING_NAMESPACES, true);

    response.setContentType("text/xml");
    XMLStreamWriter xmlWriter = getXMLStreamWriter(response.getWriter());
    if (negotiateVersion.equals(VERSION_100)) {
        Capabilities100XMLAdapter.export(xmlWriter, request, identification, provider, allowedOperations,
                sections, wcsService.getAllCoverages(), mainMetadataConf, mainControllerConf, xmlWriter,
                UPDATE_SEQUENCE);
    } else {
        // the 1.1.0
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
}

From source file:org.deegree.services.wpvs.controller.WPVSController.java

@SuppressWarnings("unchecked")
private void sendCapabilities(Map<String, String> map, HttpServletRequest request, HttpResponseBuffer response)
        throws IOException {

    GetCapabilities req = GetCapabilitiesKVPParser.parse(map);

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    factory.setProperty(IS_REPAIRING_NAMESPACES, true);
    try {/*from   w  w  w  . jav  a2 s .c  om*/
        XMLStreamWriter xsw = factory.createXMLStreamWriter(response.getOutputStream(), "UTF-8");
        IndentingXMLStreamWriter xmlWriter = new IndentingXMLStreamWriter(xsw);
        List<Operation> operations = new ArrayList<Operation>();
        List<DCP> dcps = Collections.singletonList(new DCP(new URL(OGCFrontController.getHttpGetURL()), null));
        List<Domain> params = Collections.emptyList();
        List<Domain> constraints = Collections.emptyList();
        for (String operation : allowedOperations) {
            operations.add(new Operation(operation, dcps, params, constraints, EMPTY_LIST));
        }
        OperationsMetadata operationsMd = new OperationsMetadata(operations, params, constraints, null);
        new CapabilitiesXMLAdapter().export040(xmlWriter, req, identification, provider, operationsMd,
                service.getServiceConfiguration());
        xmlWriter.writeEndDocument();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }
}

From source file:org.emonocot.job.io.StaxEventItemWriter.java

/**
 * Helper method for opening output source at given file position.
 * @param position Set the position//from   ww w  .  j av a 2s  . co m
 * @param restarted Is this execution being restarted
 */
private void open(final long position, final boolean restarted) {

    File file;
    FileOutputStream os = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.springframework.org/browse/BATCH-761.
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }

    try {
        if (transactional) {
            bufferedWriter = new TransactionAwareBufferedWriter(new OutputStreamWriter(os, encoding),
                    new Runnable() {
                        public void run() {
                            closeStream();
                        }
                    });
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = outputFactory.createXMLEventWriter(bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    }

}

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  a  v  a2s. 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.ExportingInputStream.java

private void exporterMain() {
    XMLStreamWriter wrt = null;//from   w w w  .  j  a  va  2  s . c  om
    OutputStream out = null;
    try {
        XMLOutputFactory ofactory = XMLOutputFactory.newInstance();
        ofactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

        try {
            out = exportOutput;
            if (zipOutput) {
                out = new GZIPOutputStream(out);
            }
            wrt = new IndentingXMLStreamWriter(ofactory.createXMLStreamWriter(out, "UTF-8"));
            //wrt = ofactory.createXMLStreamWriter(out, "UTF-8");
        } catch (XMLStreamException e) {
            LOG.error("Failed to create the XML stream writer to output the export file to.", e);
            return;
        }

        exportPrologue(wrt);

        for (Synchronizer<?, ?> exp : synchronizers) {
            exportSingle(wrt, exp);
        }

        exportEpilogue(wrt);

        wrt.flush();
    } catch (Exception e) {
        LOG.error("Error while exporting.", e);
        unexpectedExporterException = e;
    } finally {
        if (wrt != null) {
            try {
                wrt.close();
            } catch (XMLStreamException e) {
                LOG.warn("Failed to close the exporter XML stream.", e);
            }
        }
        safeClose(out);
    }
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriter.java

/**
 * Helper method for opening output source at given file position
 *///w w  w.  jav a2 s .c  o m
private void open(long position) {

    File file;
    FileOutputStream os = null;
    FileChannel fileChannel = null;

    try {
        file = resource.getFile();
        FileUtils.setUpOutputFile(file, restarted, false, overwriteOutput);
        Assert.state(resource.exists(), "Output resource must exist");
        os = new FileOutputStream(file, true);
        fileChannel = os.getChannel();
        channel = os.getChannel();
        setPosition(position);
    } catch (IOException ioe) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                ioe);
    }

    XMLOutputFactory outputFactory = createXmlOutputFactory();

    if (outputFactory.isPropertySupported("com.ctc.wstx.automaticEndElements")) {
        // If the current XMLOutputFactory implementation is supplied by
        // Woodstox >= 3.2.9 we want to disable its
        // automatic end element feature (see:
        // http://jira.codehaus.org/browse/WSTX-165) per
        // http://jira.spring.io/browse/BATCH-761).
        outputFactory.setProperty("com.ctc.wstx.automaticEndElements", Boolean.FALSE);
    }
    if (outputFactory.isPropertySupported("com.ctc.wstx.outputValidateStructure")) {
        // On restart we don't write the root element so we have to disable
        // structural validation (see:
        // http://jira.spring.io/browse/BATCH-1681).
        outputFactory.setProperty("com.ctc.wstx.outputValidateStructure", Boolean.FALSE);
    }

    try {
        final FileChannel channel = fileChannel;
        if (transactional) {
            TransactionAwareBufferedWriter writer = new TransactionAwareBufferedWriter(channel, new Runnable() {
                @Override
                public void run() {
                    closeStream();
                }
            });

            writer.setEncoding(encoding);
            writer.setForceSync(forceSync);
            bufferedWriter = writer;
        } else {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
        delegateEventWriter = createXmlEventWriter(outputFactory, bufferedWriter);
        eventWriter = new NoStartEndDocumentStreamWriter(delegateEventWriter);
        initNamespaceContext(delegateEventWriter);
        if (!restarted) {
            startDocument(delegateEventWriter);
            if (forceSync) {
                channel.force(false);
            }
        }
    } catch (XMLStreamException xse) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]",
                xse);
    } catch (UnsupportedEncodingException e) {
        throw new DataAccessResourceFailureException(
                "Unable to write to file resource: [" + resource + "] with encoding=[" + encoding + "]", e);
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Unable to write to file resource: [" + resource + "]", e);
    }
}