Example usage for javax.xml.stream XMLStreamWriter close

List of usage examples for javax.xml.stream XMLStreamWriter close

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Close this writer and free any resources associated with the writer.

Usage

From source file:org.deegree.console.featurestore.MappingWizardSQL.java

public String generateConfig() {

    try {//from   w ww.  java2 s .  co m
        ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext();
        DeegreeWorkspace ws = ((WorkspaceBean) ctx.getApplicationMap().get("workspace")).getActiveWorkspace();

        CRSRef storageCrs = CRSManager.getCRSRef(this.storageCrs);
        boolean createBlobMapping = storageMode.equals("hybrid") || storageMode.equals("blob");
        boolean createRelationalMapping = storageMode.equals("hybrid") || storageMode.equals("relational");
        GeometryStorageParams geometryParams = new GeometryStorageParams(storageCrs, storageSrid, DIM_2);
        AppSchemaMapper mapper = new AppSchemaMapper(appSchema, createBlobMapping, createRelationalMapping,
                geometryParams, Math.min(tableNameLength, columnNameLength), true, false);
        mappedSchema = mapper.getMappedSchema();
        SQLFeatureStoreConfigWriter configWriter = new SQLFeatureStoreConfigWriter(mappedSchema);
        File tmpConfigFile = File.createTempFile("fsconfig", ".xml");
        FileOutputStream fos = new FileOutputStream(tmpConfigFile);
        XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(fos);
        xmlWriter = new IndentingXMLStreamWriter(xmlWriter);

        List<String> schemaUrls = new ArrayList<String>(selectedAppSchemaFiles.length);
        for (String schemaFile : selectedAppSchemaFiles) {
            schemaUrls.add(".." + File.separator + ".." + File.separator + "appschemas" + schemaFile);
        }
        configWriter.writeConfig(xmlWriter, jdbcId, schemaUrls);
        xmlWriter.close();
        IOUtils.closeQuietly(fos);
        System.out.println("Wrote to file " + tmpConfigFile);

        // let the resource manager do the dirty work

        ConfigManager mgr = (ConfigManager) ctx.getSessionMap().get("configManager");

        // let the resource manager do the dirty work
        try {
            FeatureStoreManager fsMgr = ws.getSubsystemManager(FeatureStoreManager.class);
            this.resourceState = fsMgr.createResource(getFeatureStoreId(), new FileInputStream(tmpConfigFile));
            Config c = new Config(this.resourceState, mgr, fsMgr, "/console/featurestore/sql/wizard4", false);
            return c.edit();
        } catch (Throwable t) {
            LOG.error(t.getMessage(), t);
            FacesMessage fm = new FacesMessage(SEVERITY_ERROR, "Unable to create config: " + t.getMessage(),
                    null);
            FacesContext.getCurrentInstance().addMessage(null, fm);
            return null;
        }
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        String msg = "Error generating feature store configuration.";
        FacesMessage fm = new FacesMessage(SEVERITY_ERROR, msg, t.getMessage());
        FacesContext.getCurrentInstance().addMessage(null, fm);
        return "/console/featurestore/sql/wizard3";
    }
}

From source file:org.deegree.filter.xml.Filter200XMLEncoderParameterizedTest.java

@Test
public void testExport() throws Exception {
    Filter filter = parseFilter(filterUnderTest);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLStreamWriter out = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(out);
    Filter200XMLEncoder.export(filter, writer);
    out.close();

    assertThat("Failed test: " + testName, the(bos.toString()), isSimilarTo(the(filterUnderTest)));
}

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);//  ww w.  j av a  2s.  c om
    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.metadata.iso.ISORecordTest.java

private byte[] writeOut(OMElement filterEl, List<XPath> paths) throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(bos);
    if (paths != null) {
        writer = new FilteringXMLStreamWriter(writer, paths);
    }// ww w . ja  v a2 s .  c o  m
    filterEl.serialize(writer);
    writer.close();
    return bos.toByteArray();
}

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 2 s .co  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();
    os.close();/* www  .ja  va2s.  c o m*/
    return os;
}

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

/**
 * <ul>//ww w  .  j  a  v a  2s.c om
 * <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.wps.execute.ExecuteRequestXMLAdapter.java

/**
 * Parses and validates the given <code>wps:ComplexData</code> element as an {@link EmbeddedComplexInput} object.
 * <p>/*from w w  w . j a  v  a  2s. c  o m*/
 * The following "semantical" properties are validated by this method:
 * <ul>
 * <li>The specified UOM (unit-of-measure) must be supported according to the given {@link LiteralInputDefinition}.
 * If it is not specified (uom attribute is missing), the UOM from the definition is assumed.</li>
 * <li>If the dataType attribute is present, it must have the same value as specified by the
 * {@link LiteralInputDefinition}.</li>
 * </ul>
 * </p>
 * 
 * @param definition
 *            input parameter definition (from process description)
 * @param complexDataElement
 *            <code>wps:ComplexData</code> element to be parsed
 * @param title
 *            title for the input parameter (may be null)
 * @param summary
 *            abstract (narrative description) for the input parameter (may be null)
 * @param eCustomizer
 * @return corresponding {@link BoundingBoxInput} object
 * @throws OWSException
 *             if the element is not valid
 */
private EmbeddedComplexInput parseComplexData(ComplexInputDefinition definition, OMElement complexDataElement,
        LanguageString title, LanguageString summary, ExceptionCustomizer eCustomizer) throws OWSException {

    ComplexFormatType format = new ComplexFormatType();
    // "mimeType" attribute (optional)
    format.setMimeType(complexDataElement.getAttributeValue(new QName("mimeType")));
    // "encoding" attribute (optional)
    format.setEncoding(complexDataElement.getAttributeValue(new QName("encoding")));
    // "schema" attribute (optional)
    format.setSchema(complexDataElement.getAttributeValue(new QName("schema")));

    format = validateAndAugmentFormat(format, definition, eCustomizer);

    StreamBufferStore store = storageManager.newInputSink();
    LOG.debug("Storing embedded ComplexInput as XML");
    XMLStreamReader xmlReader = complexDataElement.getXMLStreamReaderWithoutCaching();
    XMLStreamWriter xmlWriter = null;
    try {
        xmlWriter = xmlOutputFactory.createXMLStreamWriter(store);
        XMLStreamUtils.skipStartDocument(xmlReader);
        XMLAdapter.writeElement(xmlWriter, xmlReader);
    } catch (Throwable t) {
        String msg = "Unable to extract embedded complex input: " + t.getMessage();
        throw new OWSException(msg, OWSException.NO_APPLICABLE_CODE);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        try {
            xmlWriter.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        IOUtils.closeQuietly(store);
    }

    return new EmbeddedComplexInput(definition, title, summary, format, store);
}

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 {//from   www. 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  w  w w . j a va2  s . c  o 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();
}