Search in sources :

Example 1 with XStream11NameCoder

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

the class PersistenceManager method saveObjectToFile.

/**
 * Save the given object to the given file.
 *
 * @param obj The object to persist.
 * @param file The file where to persist to
 * @param usegatehome if true (recommended) use $gatehome$ and $resourceshome$ instead of
 * $relpath$ in any saved path URLs if the location of that URL is inside GATE home or
 * inside the resources home directory (if set).
 * @param warnaboutgatehome if true, issue a warning message when a saved URL uses $gatehome$
 * or $resourceshome$.
 * @throws PersistenceException
 * @throws IOException
 */
public static void saveObjectToFile(Object obj, File file, boolean usegatehome, boolean warnaboutgatehome) throws PersistenceException, IOException {
    ProgressListener pListener = (ProgressListener) Gate.getListeners().get("gate.event.ProgressListener");
    StatusListener sListener = (gate.event.StatusListener) Gate.getListeners().get("gate.event.StatusListener");
    long startTime = System.currentTimeMillis();
    if (pListener != null)
        pListener.progressChanged(0);
    // The object output stream is used for native serialization,
    // but the xstream and filewriter are used for XML serialization.
    ObjectOutputStream oos = null;
    com.thoughtworks.xstream.XStream xstream = null;
    HierarchicalStreamWriter writer = null;
    warnAboutGateHome.get().addFirst(warnaboutgatehome);
    useGateHome.get().addFirst(usegatehome);
    startPersistingTo(file);
    try {
        if (Gate.getUseXMLSerialization()) {
            // Just create the xstream and the filewriter that will later be
            // used to serialize objects.
            xstream = new XStream(new SunUnsafeReflectionProvider(new FieldDictionary(new XStream12FieldKeySorter())), new StaxDriver(new XStream11NameCoder())) {

                @Override
                protected boolean useXStream11XmlFriendlyMapper() {
                    return true;
                }
            };
            FileWriter fileWriter = new FileWriter(file);
            writer = new PrettyPrintWriter(fileWriter, new XmlFriendlyNameCoder("-", "_"));
        } else {
            oos = new ObjectOutputStream(new FileOutputStream(file));
        }
        Object persistentList = getPersistentRepresentation(Gate.getCreoleRegister().getPlugins());
        Object persistentObject = getPersistentRepresentation(obj);
        if (Gate.getUseXMLSerialization()) {
            // We need to put the urls and the application itself together
            // as xstreams can only hold one object.
            GateApplication gateApplication = new GateApplication();
            // gateApplication.workspace = new File("cache");
            gateApplication.urlList = persistentList;
            gateApplication.application = persistentObject;
            // Then do the actual serialization.
            xstream.marshal(gateApplication, writer);
        } else {
            // This is for native serialization.
            oos.writeObject(persistentList);
            // now write the object
            oos.writeObject(persistentObject);
        }
    } finally {
        finishedPersisting();
        if (oos != null) {
            oos.flush();
            oos.close();
        }
        if (writer != null) {
            // Just make sure that all the xml is written, and the file
            // closed.
            writer.flush();
            writer.close();
        }
        long endTime = System.currentTimeMillis();
        if (sListener != null)
            sListener.statusChanged("Storing completed in " + NumberFormat.getInstance().format((double) (endTime - startTime) / 1000) + " seconds");
        if (pListener != null)
            pListener.processFinished();
    }
}
Also used : XStream(com.thoughtworks.xstream.XStream) HierarchicalStreamWriter(com.thoughtworks.xstream.io.HierarchicalStreamWriter) XStream(com.thoughtworks.xstream.XStream) XStream12FieldKeySorter(com.thoughtworks.xstream.converters.reflection.XStream12FieldKeySorter) FileWriter(java.io.FileWriter) XmlFriendlyNameCoder(com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder) ObjectOutputStream(java.io.ObjectOutputStream) StaxDriver(com.thoughtworks.xstream.io.xml.StaxDriver) ProgressListener(gate.event.ProgressListener) FieldDictionary(com.thoughtworks.xstream.converters.reflection.FieldDictionary) XStream11NameCoder(com.thoughtworks.xstream.io.xml.XStream11NameCoder) FileOutputStream(java.io.FileOutputStream) PrettyPrintWriter(com.thoughtworks.xstream.io.xml.PrettyPrintWriter) StatusListener(gate.event.StatusListener) SunUnsafeReflectionProvider(com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider)

Example 2 with XStream11NameCoder

use of com.thoughtworks.xstream.io.xml.XStream11NameCoder 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)

Aggregations

XStream (com.thoughtworks.xstream.XStream)2 StaxDriver (com.thoughtworks.xstream.io.xml.StaxDriver)2 XStream11NameCoder (com.thoughtworks.xstream.io.xml.XStream11NameCoder)2 ProgressListener (gate.event.ProgressListener)2 StatusListener (gate.event.StatusListener)2 FieldDictionary (com.thoughtworks.xstream.converters.reflection.FieldDictionary)1 SunUnsafeReflectionProvider (com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider)1 XStream12FieldKeySorter (com.thoughtworks.xstream.converters.reflection.XStream12FieldKeySorter)1 HierarchicalStreamReader (com.thoughtworks.xstream.io.HierarchicalStreamReader)1 HierarchicalStreamWriter (com.thoughtworks.xstream.io.HierarchicalStreamWriter)1 PrettyPrintWriter (com.thoughtworks.xstream.io.xml.PrettyPrintWriter)1 QNameMap (com.thoughtworks.xstream.io.xml.QNameMap)1 StaxReader (com.thoughtworks.xstream.io.xml.StaxReader)1 XmlFriendlyNameCoder (com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder)1 Plugin (gate.creole.Plugin)1 ResourceInstantiationException (gate.creole.ResourceInstantiationException)1 GateAwareObjectInputStream (gate.persist.GateAwareObjectInputStream)1 PersistenceException (gate.persist.PersistenceException)1 BomStrippingInputStreamReader (gate.util.BomStrippingInputStreamReader)1 GateException (gate.util.GateException)1