Example usage for javax.xml.stream XMLOutputFactory newInstance

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

Introduction

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

Prototype

public static XMLOutputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

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.
 * //from w w w .ja v  a 2s .c o m
 * @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.protocol.csw.client.getrecords.TestGetRecordsXMLEncoderTest.java

private ByteArrayOutputStream writeGetRecordsAsXml(GetRecords getRecords) throws XMLStreamException,
        FactoryConfigurationError, UnknownCRSException, TransformationException, IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os);

    GetRecordsXMLEncoder.export(getRecords, writer);

    writer.close();/*w  w  w  .ja  va2 s.c o m*/
    os.close();
    return os;
}

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

/**
 * <ul>// w w  w .ja va2  s.c o  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.controller.OGCFrontController.java

@Override
public void init(ServletConfig config) throws ServletException {

    instance = this;

    try {/*from   w ww . ja va2  s  .co  m*/
        super.init(config);
        ctxPath = config.getServletContext().getContextPath();
        LOG.info("--------------------------------------------------------------------------------");
        DeegreeAALogoUtils.logInfo(LOG);
        LOG.info("--------------------------------------------------------------------------------");
        LOG.info("deegree modules");
        LOG.info("--------------------------------------------------------------------------------");
        LOG.info("");
        try {
            modulesInfo = extractModulesInfo(config.getServletContext());
        } catch (Throwable t) {
            LOG.error("Unable to extract deegree module information: " + t.getMessage());
            modulesInfo = emptyList();
        }
        for (ModuleInfo moduleInfo : modulesInfo) {
            LOG.info("- " + moduleInfo.toString());
            if ("deegree-services-commons".equals(moduleInfo.getArtifactId())) {
                version = moduleInfo.getVersion();
            }
        }
        if (version == null) {
            version = "unknown";
        }
        LOG.info("");
        LOG.info("--------------------------------------------------------------------------------");
        LOG.info("System info");
        LOG.info("--------------------------------------------------------------------------------");
        LOG.info("");
        LOG.info("- java version       " + System.getProperty("java.version") + " ("
                + System.getProperty("java.vendor") + ")");
        LOG.info("- operating system   " + System.getProperty("os.name") + " ("
                + System.getProperty("os.version") + ", " + System.getProperty("os.arch") + ")");
        LOG.info("- container          " + config.getServletContext().getServerInfo());
        LOG.info("- webapp path        " + ctxPath);
        LOG.info("- default encoding   " + DEFAULT_ENCODING);
        LOG.info("- system encoding    " + Charset.defaultCharset().displayName());
        LOG.info("- temp directory     " + defaultTMPDir);
        LOG.info("- XMLOutputFactory   " + XMLOutputFactory.newInstance().getClass().getCanonicalName());
        LOG.info("- XMLInputFactory    " + XMLInputFactory.newInstance().getClass().getCanonicalName());
        LOG.info("");

        initWorkspace();

    } catch (NoClassDefFoundError e) {
        LOG.error("Initialization failed!");
        LOG.error("You probably forgot to add a required .jar to the WEB-INF/lib directory.");
        LOG.error("The resource that could not be found was '{}'.", e.getMessage());
        LOG.debug("Stack trace:", e);

        throw new ServletException(e);
    } catch (Exception e) {
        LOG.error("Initialization failed!");
        LOG.error("An unexpected error was caught, stack trace:", e);

        throw new ServletException(e);
    } finally {
        CONTEXT.remove();
    }
}

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   w  w  w. j  a  va  2 s  .com*/
            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.wcs.WCSController.java

private static XMLStreamWriter getXMLStreamWriter(Writer writer) throws XMLStreamException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    return new IndentingXMLStreamWriter(factory.createXMLStreamWriter(writer));
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.DataTableContentProvider.java

private static Document getAsDocument(XMLStreamReader xmlStreamReader) throws XMLStreamException,
        FactoryConfigurationError, ParserConfigurationException, SAXException, IOException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    StreamBufferStore store = new StreamBufferStore();
    XMLStreamWriter xmlWriter = null;
    try {/* w w  w. ja  v a  2s . co m*/
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
        XMLAdapter.writeElement(xmlWriter, xmlStreamReader);
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.close();
            } catch (XMLStreamException e) {
                LOG.error("Unable to close xmlwriter.");
            }
        }
    }
    Document doc = builder.parse(store.getInputStream());
    store.close();
    return doc;
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.DataTableContentProvider.java

private static InputStream getAsInputStream(XMLStreamReader xmlStreamReader) throws XMLStreamException,
        FactoryConfigurationError, ParserConfigurationException, SAXException, IOException {
    StreamBufferStore store = new StreamBufferStore();
    XMLStreamWriter xmlWriter = null;
    try {//from   ww w .  jav  a2s  .  co  m
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
        XMLAdapter.writeElement(xmlWriter, xmlStreamReader);
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.close();
            } catch (XMLStreamException e) {
                LOG.error("Unable to close xmlwriter.");
            }
        }
    }
    return store.getInputStream();
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.Utils.java

public static ProcessletInputs getInputs(String parameterId, String mimeType, String schema,
        InputStream complexInput) throws IOException, XMLStreamException, FactoryConfigurationError {
    List<ProcessletInput> inputs = new ArrayList<ProcessletInput>();
    ProcessletInputs in = new ProcessletInputs(inputs);

    ComplexInputDefinition definition = new ComplexInputDefinition();
    definition.setTitle(getAsLanguageStringType(parameterId));
    definition.setIdentifier(getAsCodeType(parameterId));
    ComplexFormatType format = new ComplexFormatType();

    format.setEncoding("UTF-8");
    format.setMimeType(mimeType);//from  w ww. j a  va 2s .  c o m
    format.setSchema(schema);
    definition.setDefaultFormat(format);
    definition.setMaxOccurs(BigInteger.valueOf(1));
    definition.setMinOccurs(BigInteger.valueOf(0));

    File f = File.createTempFile("tmpStore", "");
    StreamBufferStore store = new StreamBufferStore(1024, f);

    XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(complexInput);
    XMLStreamWriter xmlWriter = null;
    try {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
        if (xmlReader.getEventType() == START_DOCUMENT) {
            xmlReader.nextTag();
        }
        XMLAdapter.writeElement(xmlWriter, xmlReader);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        try {
            xmlWriter.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        IOUtils.closeQuietly(store);
    }

    ComplexInputImpl mapProcesslet = new EmbeddedComplexInput(definition, new LanguageString("title", "ger"),
            new LanguageString("summary", "ger"), format, store);

    inputs.add(mapProcesslet);
    return in;
}

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.ja va 2s  .  c o m
        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);
    }
}