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);
}
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;
}
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));
}
}
}
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);
}
}
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());
}
}
Aggregations