Search in sources :

Example 11 with QNameMap

use of com.thoughtworks.xstream.io.xml.QNameMap in project gate-core by GateNLP.

the class PersistenceManager method loadObjectFromUrl.

public static Object loadObjectFromUrl(URL url) throws PersistenceException, IOException, ResourceInstantiationException {
    if (!Gate.isInitialised())
        throw new ResourceInstantiationException("You must call Gate.init() before you can restore resources");
    ProgressListener pListener = (ProgressListener) Gate.getListeners().get("gate.event.ProgressListener");
    StatusListener sListener = (gate.event.StatusListener) Gate.getListeners().get("gate.event.StatusListener");
    if (pListener != null)
        pListener.progressChanged(0);
    startLoadingFrom(url);
    // the actual stream obtained from the URL. We keep a reference to this
    // so we can ensure it gets closed.
    InputStream rawStream = null;
    try {
        long startTime = System.currentTimeMillis();
        // Determine whether the file contains an application serialized in
        // xml
        // format. Otherwise we will assume that it contains native
        // serializations.
        boolean xmlStream = isXmlApplicationFile(url);
        ObjectInputStream ois = null;
        HierarchicalStreamReader reader = null;
        XStream xstream = null;
        // whether serialization is native or xml.
        if (xmlStream) {
            // we don't want to strip the BOM on XML.
            Reader inputReader = new InputStreamReader(rawStream = url.openStream());
            try {
                XMLInputFactory inputFactory = XMLInputFactory.newInstance();
                inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
                XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader);
                reader = new StaxReader(new QNameMap(), xsr);
            } catch (XMLStreamException xse) {
                // make sure the stream is closed, on error
                inputReader.close();
                throw new PersistenceException("Error creating reader", xse);
            }
            xstream = new XStream(new StaxDriver(new XStream11NameCoder())) {

                @Override
                protected boolean useXStream11XmlFriendlyMapper() {
                    return true;
                }
            };
            // make XStream load classes through the GATE ClassLoader
            xstream.setClassLoader(Gate.getClassLoader());
            // make the XML stream appear as a normal ObjectInputStream
            ois = xstream.createObjectInputStream(reader);
        } else {
            // use GateAwareObjectInputStream to load classes through the
            // GATE ClassLoader if they can't be loaded through the one
            // ObjectInputStream would normally use
            ois = new GateAwareObjectInputStream(url.openStream());
        }
        Object res = null;
        try {
            // first read the list of creole URLs.
            @SuppressWarnings("unchecked") Iterator<?> urlIter = ((Collection<?>) getTransientRepresentation(ois.readObject())).iterator();
            // and re-register them
            while (urlIter.hasNext()) {
                Object anUrl = urlIter.next();
                try {
                    if (anUrl instanceof URL)
                        Gate.getCreoleRegister().registerPlugin(new Plugin.Directory((URL) anUrl), false);
                    else if (anUrl instanceof Plugin)
                        Gate.getCreoleRegister().registerPlugin((Plugin) anUrl, false);
                } catch (GateException ge) {
                    System.out.println("We've hit an error!");
                    ge.printStackTrace();
                    ge.printStackTrace(Err.getPrintWriter());
                    Err.prln("Could not reload creole directory " + anUrl);
                }
            }
            // now we can read the saved object in the presence of all
            // the right plugins
            res = ois.readObject();
            // ensure a fresh start
            clearCurrentTransients();
            res = getTransientRepresentation(res);
            long endTime = System.currentTimeMillis();
            if (sListener != null)
                sListener.statusChanged("Loading completed in " + NumberFormat.getInstance().format((double) (endTime - startTime) / 1000) + " seconds");
            return res;
        } catch (ResourceInstantiationException rie) {
            if (sListener != null)
                sListener.statusChanged("Failure during instantiation of resources.");
            throw rie;
        } catch (PersistenceException pe) {
            if (sListener != null)
                sListener.statusChanged("Failure during persistence operations.");
            throw pe;
        } catch (Exception ex) {
            if (sListener != null)
                sListener.statusChanged("Loading failed!");
            throw new PersistenceException(ex);
        } finally {
            // make sure the stream gets closed
            if (ois != null)
                ois.close();
            if (reader != null)
                reader.close();
        }
    } finally {
        if (rawStream != null)
            rawStream.close();
        finishedLoading();
        if (pListener != null)
            pListener.processFinished();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) Reader(java.io.Reader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) BomStrippingInputStreamReader(gate.util.BomStrippingInputStreamReader) StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) URL(java.net.URL) StaxDriver(com.thoughtworks.xstream.io.xml.StaxDriver) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap) StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) BomStrippingInputStreamReader(gate.util.BomStrippingInputStreamReader) InputStreamReader(java.io.InputStreamReader) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) ObjectInputStream(java.io.ObjectInputStream) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) GateException(gate.util.GateException) URISyntaxException(java.net.URISyntaxException) XMLStreamException(javax.xml.stream.XMLStreamException) PersistenceException(gate.persist.PersistenceException) GateRuntimeException(gate.util.GateRuntimeException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GateException(gate.util.GateException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) ProgressListener(gate.event.ProgressListener) XMLStreamException(javax.xml.stream.XMLStreamException) XStream11NameCoder(com.thoughtworks.xstream.io.xml.XStream11NameCoder) PersistenceException(gate.persist.PersistenceException) Collection(java.util.Collection) StatusListener(gate.event.StatusListener) XMLInputFactory(javax.xml.stream.XMLInputFactory) ObjectInputStream(java.io.ObjectInputStream) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) Plugin(gate.creole.Plugin)

Example 12 with QNameMap

use of com.thoughtworks.xstream.io.xml.QNameMap in project spring-framework by spring-projects.

the class XStreamMarshallerTests method marshalStaxResultXMLStreamWriterDefaultNamespace.

@Test
void marshalStaxResultXMLStreamWriterDefaultNamespace() throws Exception {
    QNameMap map = new QNameMap();
    map.setDefaultNamespace("https://example.com");
    map.setDefaultPrefix("spr");
    StaxDriver driver = new StaxDriver(map);
    marshaller.setStreamDriver(driver);
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    StringWriter writer = new StringWriter();
    XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
    Result result = StaxUtils.createStaxResult(streamWriter);
    marshaller.marshal(flight, result);
    assertThat(XmlContent.from(writer)).isSimilarTo("<spr:flight xmlns:spr=\"https://example.com\"><spr:flightNumber>42</spr:flightNumber></spr:flight>");
}
Also used : StaxDriver(com.thoughtworks.xstream.io.xml.StaxDriver) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) StringWriter(java.io.StringWriter) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult) Test(org.junit.jupiter.api.Test)

Example 13 with QNameMap

use of com.thoughtworks.xstream.io.xml.QNameMap in project ddf by codice.

the class GmdTransformer method handleTransform.

private Metacard handleTransform(InputStream inputStream, String id) throws CatalogTransformerException {
    String xml;
    XstreamPathValueTracker pathValueTracker;
    try (TemporaryFileBackedOutputStream temporaryFileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        IOUtils.copy(inputStream, temporaryFileBackedOutputStream);
        byteArray = temporaryFileBackedOutputStream.asByteSource();
        try (InputStream xmlSourceInputStream = getSourceInputStream()) {
            xml = IOUtils.toString(xmlSourceInputStream);
        }
        argumentHolder.put(XstreamPathConverter.PATH_KEY, buildPaths());
        XMLStreamReader streamReader = xmlFactory.createXMLStreamReader(new StringReader(xml));
        HierarchicalStreamReader reader = new StaxReader(new QNameMap(), streamReader);
        pathValueTracker = (XstreamPathValueTracker) xstream.unmarshal(reader, null, argumentHolder);
        Metacard metacard = toMetacard(pathValueTracker, id);
        metacard.setAttribute(new AttributeImpl(Core.METADATA, xml));
        return metacard;
    } catch (XStreamException | XMLStreamException | IOException e) {
        throw new CatalogTransformerException(TRANSFORM_EXCEPTION_MSG, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) InputStream(java.io.InputStream) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) XstreamPathValueTracker(org.codice.ddf.spatial.ogc.csw.catalog.converter.XstreamPathValueTracker) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) Metacard(ddf.catalog.data.Metacard) XStreamException(com.thoughtworks.xstream.XStreamException) XMLStreamException(javax.xml.stream.XMLStreamException) StringReader(java.io.StringReader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap)

Example 14 with QNameMap

use of com.thoughtworks.xstream.io.xml.QNameMap in project ddf by codice.

the class XstreamPathConverterTest method setup.

@Before
public void setup() {
    QNameMap qmap = new QNameMap();
    qmap.setDefaultNamespace(GML_NAMESPACE);
    qmap.setDefaultPrefix("");
    StaxDriver staxDriver = new StaxDriver(qmap);
    xstream = new XStream(staxDriver);
    xstream.setClassLoader(this.getClass().getClassLoader());
    xstream.allowTypesByWildcard(new String[] { "ddf.**", "org.codice.**" });
    XstreamPathConverter converter = new XstreamPathConverter();
    xstream.registerConverter(converter);
    xstream.alias("Polygon", XstreamPathValueTracker.class);
    xstream.alias("element", XstreamPathValueTracker.class);
    argumentHolder = xstream.newDataHolder();
    Set<Path> paths = new LinkedHashSet<>();
    paths.addAll(Arrays.asList(POLYGON_POS_PATH, BAD_PATH, POLYGON_GML_ID_PATH, LINEAR_RING_ALL_PATH, POC_PATH));
    argumentHolder.put(XstreamPathConverter.PATH_KEY, paths);
}
Also used : Path(com.thoughtworks.xstream.io.path.Path) LinkedHashSet(java.util.LinkedHashSet) StaxDriver(com.thoughtworks.xstream.io.xml.StaxDriver) XStream(com.thoughtworks.xstream.XStream) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap) Before(org.junit.Before)

Example 15 with QNameMap

use of com.thoughtworks.xstream.io.xml.QNameMap in project ddf by codice.

the class XstreamPathConverterTest method testAllNestedPath.

@Test
public void testAllNestedPath() throws XMLStreamException {
    XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(GML_XML));
    HierarchicalStreamReader reader = new StaxReader(new QNameMap(), streamReader);
    XstreamPathValueTracker pathValueTracker = (XstreamPathValueTracker) xstream.unmarshal(reader, null, argumentHolder);
    assertThat(pathValueTracker.getAllValues(LINEAR_RING_ALL_PATH), hasItem("-180.000000 90.000000"));
}
Also used : StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) StringReader(java.io.StringReader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap) Test(org.junit.Test)

Aggregations

QNameMap (com.thoughtworks.xstream.io.xml.QNameMap)17 StaxReader (com.thoughtworks.xstream.io.xml.StaxReader)13 XMLStreamReader (javax.xml.stream.XMLStreamReader)13 HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)12 StringReader (java.io.StringReader)10 Test (org.junit.Test)8 StaxDriver (com.thoughtworks.xstream.io.xml.StaxDriver)4 XStream (com.thoughtworks.xstream.XStream)3 Path (com.thoughtworks.xstream.io.path.Path)3 InputStream (java.io.InputStream)3 LinkedHashSet (java.util.LinkedHashSet)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 XStreamException (com.thoughtworks.xstream.XStreamException)2 IOException (java.io.IOException)2 InputStreamReader (java.io.InputStreamReader)2 XMLInputFactory (javax.xml.stream.XMLInputFactory)2 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)2 Before (org.junit.Before)2 StaxWriter (com.thoughtworks.xstream.io.xml.StaxWriter)1 XStream11NameCoder (com.thoughtworks.xstream.io.xml.XStream11NameCoder)1