Search in sources :

Example 31 with XMLEncoder

use of java.beans.XMLEncoder in project OpenGrok by OpenGrok.

the class IgnoredNamesTest method testEncodeDecode.

/**
 * Make sure that encoding and decoding IgnoredNames object is 1:1 operation.
 * @throws FileNotFoundException
 * @throws IOException
 */
@Test
public void testEncodeDecode() throws FileNotFoundException, IOException {
    IgnoredNames in = new IgnoredNames();
    // Add file and directory to list of ignored items.
    in.add("f:foo.txt");
    in.add("d:bar");
    // Create an exception listener to detect errors while encoding and decoding
    final LinkedList<Exception> exceptions = new LinkedList<Exception>();
    ExceptionListener listener = new ExceptionListener() {

        @Override
        public void exceptionThrown(Exception e) {
            exceptions.addLast(e);
        }
    };
    // Actually create the file and directory for much better test coverage.
    File tmpdir = FileUtilities.createTemporaryDirectory("ignoredNames");
    File foo = new File(tmpdir, "foo.txt");
    foo.createNewFile();
    assertTrue(foo.isFile());
    File bar = new File(tmpdir, "bar");
    bar.mkdir();
    assertTrue(bar.isDirectory());
    // Store the IgnoredNames object as XML file.
    File testXML = new File(tmpdir, "Test.xml");
    XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(testXML)));
    e.setExceptionListener(listener);
    e.writeObject(in);
    e.close();
    // Restore the IgnoredNames object from XML file.
    XMLDecoder d = new XMLDecoder(new FileInputStream(testXML));
    IgnoredNames in2 = (IgnoredNames) d.readObject();
    d.close();
    // Verify that the XML encoding/decoding did not fail.
    if (!exceptions.isEmpty()) {
        AssertionFailedError afe = new AssertionFailedError("Got " + exceptions.size() + " exception(s)");
        // Can only chain one of the exceptions. Take the first one.
        afe.initCause(exceptions.getFirst());
        throw afe;
    }
    // Make sure the complete list of items is equal after decoding.
    // This will is a simple casual test that cannot verify that sub-classes
    // are intact. For that there are the following tests.
    assertTrue(in.getItems().containsAll(in2.getItems()));
    // Use the restored object to test the matching of file and directory.
    assertTrue(in2.ignore("foo.txt"));
    assertTrue(in2.ignore("bar"));
    assertTrue(in2.ignore(foo));
    assertTrue(in2.ignore(bar));
    // Cleanup.
    FileUtilities.removeDirs(tmpdir);
}
Also used : XMLEncoder(java.beans.XMLEncoder) FileOutputStream(java.io.FileOutputStream) XMLDecoder(java.beans.XMLDecoder) ExceptionListener(java.beans.ExceptionListener) AssertionFailedError(junit.framework.AssertionFailedError) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream) CAnalyzerFactoryTest(org.opensolaris.opengrok.analysis.c.CAnalyzerFactoryTest) Test(org.junit.Test)

Example 32 with XMLEncoder

use of java.beans.XMLEncoder in project antlrworks by antlr.

the class XJUpdateManager method writeUpdateXMLFile.

public boolean writeUpdateXMLFile(String version, String appName, String description, String downloadFileName, String downloadFileURL, long downloadFileSize, String outputFile) {
    XMLEncoder encoder;
    try {
        encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(outputFile)));
    } catch (FileNotFoundException e) {
        XJAlert.display(getParentContainer(), "Update Manager", "Cannot write the update xml file because:\n" + e);
        return false;
    }
    Map<String, Serializable> update = new HashMap<String, Serializable>();
    update.put(KEY_VERSION, version);
    update.put(KEY_APP_NAME, appName);
    update.put(KEY_DESCRIPTION, description);
    update.put(KEY_DOWNLOAD_FILE_NAME, downloadFileName);
    update.put(KEY_DOWNLOAD_FILE_URL, downloadFileURL);
    update.put(KEY_DOWNLOAD_SIZE, downloadFileSize);
    encoder.writeObject(update);
    encoder.close();
    return true;
}
Also used : XMLEncoder(java.beans.XMLEncoder) HashMap(java.util.HashMap)

Example 33 with XMLEncoder

use of java.beans.XMLEncoder in project OpenGrok by OpenGrok.

the class FileHistoryCache method writeHistoryToFile.

/**
 * Store history in file on disk.
 * @param dir directory where the file will be saved
 * @param history history to store
 * @param cacheFile the file to store the history to
 */
private void writeHistoryToFile(File dir, History history, File cacheFile) throws HistoryException {
    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.log(Level.FINEST, "writing history entries to ''{0}'': {1}", new Object[] { cacheFile, history.getRevisionList() });
    }
    // We have a problem that multiple threads may access the cache layer
    // at the same time. Since I would like to avoid read-locking, I just
    // serialize the write access to the cache file. The generation of the
    // cache file would most likely be executed during index generation, and
    // that happens sequential anyway....
    // Generate the file with a temporary name and move it into place when
    // done, so it is not necessary to protect the readers for partially updated
    // files...
    final File output;
    try {
        output = File.createTempFile("oghist", null, dir);
        try (FileOutputStream out = new FileOutputStream(output);
            XMLEncoder e = new XMLEncoder(new GZIPOutputStream(new BufferedOutputStream(out)))) {
            e.setPersistenceDelegate(File.class, new FilePersistenceDelegate());
            e.writeObject(history);
        }
    } catch (IOException ioe) {
        throw new HistoryException("Failed to write history", ioe);
    }
    synchronized (lock) {
        if (!cacheFile.delete() && cacheFile.exists()) {
            if (!output.delete()) {
                LOGGER.log(Level.WARNING, "Failed to remove temporary history cache file");
            }
            throw new HistoryException(String.format("Cache file '%s' exists, and could not be deleted.", cacheFile));
        }
        if (!output.renameTo(cacheFile)) {
            try {
                Files.delete(output.toPath());
            } catch (IOException e) {
                throw new HistoryException("failed to delete output file", e);
            }
            throw new HistoryException(String.format("Failed to rename cache temporary file '%s' to '%s'", output, cacheFile));
        }
    }
}
Also used : XMLEncoder(java.beans.XMLEncoder) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 34 with XMLEncoder

use of java.beans.XMLEncoder in project OpenGrok by OpenGrok.

the class ConfigurationTest method testTransientKeywordGroups.

/**
 * Verify that encoding of Group class does  not contain transient members.
 * @throws Exception exception
 */
@Test
public void testTransientKeywordGroups() throws Exception {
    Group foo = new Group("foo", "foo.*");
    Group bar = new Group("bar", "bar.*");
    Configuration cfg = new Configuration();
    cfg.addGroup(foo);
    foo.addGroup(bar);
    cfg.addGroup(bar);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (XMLEncoder enc = new XMLEncoder(out)) {
        enc.writeObject(cfg);
    }
    // test.
    try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        // Compliant
        saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        // compliant
        saxParser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
        Handler handler = new Handler();
        saxParser.parse(new BufferedInputStream(in), handler);
    }
}
Also used : XMLEncoder(java.beans.XMLEncoder) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedInputStream(java.io.BufferedInputStream) SAXParser(javax.xml.parsers.SAXParser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 35 with XMLEncoder

use of java.beans.XMLEncoder in project OpenGrok by OpenGrok.

the class ConfigurationTest method serializationOrderTest.

/**
 * Test for a serialization bug in configuration. The problem is that with
 * this scenario the output is written in a way that when deserializing the
 * input later on, we get {@link NullPointerException} trying to use
 * {@link Group#compareTo(Group)}. This exception is caused by wrong order
 * of serialization of
 * {@link Group#getDescendants()}, {@link Group#getParent()} and
 * {@link Project#getGroups()} where the backpointers in a {@link Project}
 * to several {@link Group}s shall be stored in a set while this
 * {@link Group} does not have a name yet (= {@code null}).
 *
 * @throws IOException I/O exception
 * @see ClassUtil#remarkTransientFields(java.lang.Class)
 * ClassUtil#remarkTransientFields() for suggested solution
 */
@Test
public void serializationOrderTest() throws IOException {
    Project project = new Project("project");
    Group apache = new Group("Apache", "test.*");
    Group bsd = new Group("BSD", "test.*");
    Group opensource = new Group("OpenSource", "test.*");
    opensource.addGroup(apache);
    opensource.addGroup(bsd);
    bsd.addProject(project);
    opensource.addProject(project);
    project.getGroups().add(opensource);
    project.getGroups().add(bsd);
    Configuration cfg = new Configuration();
    Configuration oldCfg = cfg;
    cfg.addGroup(apache);
    cfg.addGroup(bsd);
    cfg.addGroup(opensource);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (XMLEncoder enc = new XMLEncoder(out)) {
        enc.writeObject(cfg);
    }
    // Create an exception listener to detect errors while encoding and
    // decoding
    final LinkedList<Exception> exceptions = new LinkedList<>();
    try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        XMLDecoder dec = new XMLDecoder(in, null, exceptions::addLast)) {
        cfg = (Configuration) dec.readObject();
        assertNotNull(cfg);
        // verify that the read didn't fail
        if (!exceptions.isEmpty()) {
            // Can only chain one of the exceptions. Take the first one.
            throw new AssertionError("Got " + exceptions.size() + " exception(s)", exceptions.getFirst());
        }
        assertEquals(oldCfg.getGroups(), cfg.getGroups());
    }
}
Also used : XMLEncoder(java.beans.XMLEncoder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLDecoder(java.beans.XMLDecoder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

XMLEncoder (java.beans.XMLEncoder)109 ByteArrayOutputStream (java.io.ByteArrayOutputStream)48 BufferedOutputStream (java.io.BufferedOutputStream)37 FileOutputStream (java.io.FileOutputStream)36 IOException (java.io.IOException)30 File (java.io.File)24 XMLDecoder (java.beans.XMLDecoder)22 ByteArrayInputStream (java.io.ByteArrayInputStream)22 ExceptionListener (java.beans.ExceptionListener)16 LinkedList (java.util.LinkedList)16 Test (org.junit.jupiter.api.Test)12 FileInputStream (java.io.FileInputStream)9 Test (org.junit.Test)8 Encoder (java.beans.Encoder)6 BufferedInputStream (java.io.BufferedInputStream)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 DefaultPersistenceDelegate (java.beans.DefaultPersistenceDelegate)5 PersistenceDelegate (java.beans.PersistenceDelegate)5 OutputStream (java.io.OutputStream)5 Expression (java.beans.Expression)4