use of org.exist.util.serializer.SAXSerializer in project exist by eXist-db.
the class InteractiveClient method writeQueryHistory.
protected void writeQueryHistory() {
try {
console.getHistory().save();
} catch (final IOException e) {
System.err.println("Could not write history File to " + historyFile.toAbsolutePath().toString());
}
final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try (final BufferedWriter writer = Files.newBufferedWriter(queryHistoryFile, StandardCharsets.UTF_8)) {
serializer.setOutput(writer, null);
int p = 0;
if (queryHistory.size() > 20) {
p = queryHistory.size() - 20;
}
final AttributesImpl attrs = new AttributesImpl();
serializer.startDocument();
serializer.startElement(XMLConstants.NULL_NS_URI, "history", "history", attrs);
for (final ListIterator<String> i = queryHistory.listIterator(p); i.hasNext(); ) {
serializer.startElement(XMLConstants.NULL_NS_URI, "query", "query", attrs);
final String next = i.next();
serializer.characters(next.toCharArray(), 0, next.length());
serializer.endElement(XMLConstants.NULL_NS_URI, "query", "query");
}
serializer.endElement(XMLConstants.NULL_NS_URI, "history", "history");
serializer.endDocument();
} catch (final IOException e) {
System.err.println("IO error while writing query history.");
} catch (final SAXException e) {
System.err.println("SAX exception while writing query history.");
} finally {
SerializerPool.getInstance().returnObject(serializer);
}
}
use of org.exist.util.serializer.SAXSerializer in project exist by eXist-db.
the class SystemExport method exportDocument.
private void exportDocument(final BackupHandler bh, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final SAXSerializer serializer, final int docsCount, final int count, final DocumentImpl doc) throws IOException, SAXException, TerminatedException {
if (callback != null) {
callback.startDocument(doc.getFileURI().toString(), count, docsCount);
}
if ((monitor != null) && !monitor.proceed()) {
throw (new TerminatedException("system export terminated by db"));
}
final boolean needsBackup = (prevBackup == null) || (date.getTime() < doc.getLastModified());
if (needsBackup) {
// Note: do not auto-close the output stream or the zip will be closed!
try {
final OutputStream os = output.newEntry(Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
broker.readBinaryResource((BinaryDocument) doc, os);
} else {
final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
try {
// write resource to contentSerializer
contentSerializer.setOutput(writer, defaultOutputProperties);
final Receiver receiver;
if (chainFactory != null) {
chainFactory.getLast().setNextInChain(contentSerializer);
receiver = chainFactory.getFirst();
} else {
receiver = contentSerializer;
}
writeXML(doc, receiver);
} finally {
SerializerPool.getInstance().returnObject(contentSerializer);
writer.flush();
}
}
} catch (final Exception e) {
reportError("A write error occurred while exporting document: '" + doc.getFileURI() + "'. Continuing with next document.", e);
return;
} finally {
output.closeEntry();
}
}
final Permission perms = doc.getPermissions();
// store permissions
final AttributesImpl attr = new AttributesImpl();
attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource");
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString());
attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes"));
Backup.writeUnixStylePermissionAttributes(attr, perms);
try {
final String created = new DateTimeValue(new Date(doc.getCreated())).getStringValue();
final String modified = new DateTimeValue(new Date(doc.getLastModified())).getStringValue();
attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", created);
attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", modified);
} catch (final XPathException e) {
LOG.warn(e.getMessage(), e);
}
attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
String mimeType = "application/xml";
if (doc.getMimeType() != null) {
mimeType = Backup.encode(doc.getMimeType());
}
attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", mimeType);
// output by serializer
// if( ( doc.getResourceType() == DocumentImpl.XML_FILE ) && ( metadata != null ) && ( doc.getDoctype() != null ) ) {
//
// if( doc.getDoctype().getName() != null ) {
// attr.addAttribute( Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", doc.getDoctype().getName() );
// }
//
// if( doc.getDoctype().getPublicId() != null ) {
// attr.addAttribute( Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", doc.getDoctype().getPublicId() );
// }
//
// if( doc.getDoctype().getSystemId() != null ) {
// attr.addAttribute( Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", doc.getDoctype().getSystemId() );
// }
// }
bh.backup(doc, attr);
serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
if (perms instanceof ACLPermission) {
Backup.writeACLPermission(serializer, (ACLPermission) perms);
}
bh.backup(doc, serializer);
serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
}
use of org.exist.util.serializer.SAXSerializer in project exist by eXist-db.
the class SystemExport method exportOrphans.
/**
* Scan all document records in collections.dbx and try to find orphaned documents whose parent collection got destroyed or is damaged.
*
* @param output the backup writer
* @param docs a document set containing all the documents which were exported regularily. the method will ignore those.
* @param errorList a list of {@link org.exist.backup.ErrorReport} objects as returned by methods in {@link ConsistencyCheck}
*/
private void exportOrphans(final BackupWriter output, final DocumentSet docs, final List<ErrorReport> errorList) throws IOException {
output.newCollection("/db/__lost_and_found__");
final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try (final Writer contents = output.newContents()) {
// serializer writes to __contents__.xml
serializer.setOutput(contents, contentsOutputProps);
serializer.startDocument();
serializer.startPrefixMapping("", Namespaces.EXIST_NS);
final AttributesImpl attr = new AttributesImpl();
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", "/db/__lost_and_found__");
attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(currVersion));
attr.addAttribute(Namespaces.EXIST_NS, "owner", "owner", "CDATA", org.exist.security.SecurityManager.DBA_USER);
attr.addAttribute(Namespaces.EXIST_NS, "group", "group", "CDATA", org.exist.security.SecurityManager.DBA_GROUP);
attr.addAttribute(Namespaces.EXIST_NS, "mode", "mode", "CDATA", "0771");
serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
final DocumentCallback docCb = new DocumentCallback(output, serializer, null, null, docs, true);
broker.getResourcesFailsafe(transaction, docCb, directAccess);
serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
serializer.endPrefixMapping("");
serializer.endDocument();
} catch (final Exception e) {
e.printStackTrace();
if (callback != null) {
callback.error(e.getMessage(), e);
}
} finally {
SerializerPool.getInstance().returnObject(serializer);
output.closeCollection();
}
}
use of org.exist.util.serializer.SAXSerializer in project exist by eXist-db.
the class SystemExport method export.
/**
* Export a collection. Write out the collection metadata and save the resources stored in the collection.
*
* @param current the collection
* @param output the output writer
* @param date
* @param prevBackup DOCUMENT ME!
* @param errorList a list of {@link org.exist.backup.ErrorReport} objects as returned by methods in {@link org.exist.backup.ConsistencyCheck}
* @param docs a document set to keep track of all written documents.
* @throws IOException
* @throws SAXException
* @throws TerminatedException DOCUMENT ME!
*/
private void export(final BackupHandler bh, final Collection current, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final List<ErrorReport> errorList, final MutableDocumentSet docs) throws IOException, SAXException, TerminatedException, PermissionDeniedException {
if ((monitor != null) && !monitor.proceed()) {
throw (new TerminatedException("system export terminated by db"));
}
// if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
output.newCollection(Backup.encode(URIUtils.urlDecodeUtf8(current.getURI())));
// }
final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try {
final Writer contents = output.newContents();
// serializer writes to __contents__.xml
serializer.setOutput(contents, contentsOutputProps);
final Permission perm = current.getPermissionsNoLock();
serializer.startDocument();
serializer.startPrefixMapping("", Namespaces.EXIST_NS);
final XmldbURI uri = current.getURI();
final AttributesImpl attr = new AttributesImpl();
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", uri.toString());
attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(currVersion));
Backup.writeUnixStylePermissionAttributes(attr, perm);
try {
attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", new DateTimeValue(new Date(current.getCreated())).getStringValue());
} catch (final XPathException e) {
e.printStackTrace();
}
bh.backup(current, attr);
serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
if (perm instanceof ACLPermission) {
Backup.writeACLPermission(serializer, (ACLPermission) perm);
}
bh.backup(current, serializer);
final int docsCount = current.getDocumentCountNoLock(broker);
int count = 0;
for (final Iterator<DocumentImpl> i = current.iteratorNoLock(broker); i.hasNext(); count++) {
final DocumentImpl doc = i.next();
if (isDamaged(doc, errorList)) {
reportError("Skipping damaged document " + doc.getFileURI(), null);
continue;
}
if (doc.getFileURI().equalsInternal(CONTENTS_URI) || doc.getFileURI().equalsInternal(LOST_URI)) {
// skip __contents__.xml documents
continue;
}
exportDocument(bh, output, date, prevBackup, serializer, docsCount, count, doc);
docs.add(doc, false);
}
for (final Iterator<XmldbURI> i = current.collectionIteratorNoLock(broker); i.hasNext(); ) {
final XmldbURI childUri = i.next();
if (childUri.equalsInternal(TEMP_COLLECTION)) {
continue;
}
if (isDamagedChild(childUri, errorList)) {
reportError("Skipping damaged child collection " + childUri, null);
continue;
}
attr.clear();
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", childUri.toString());
attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(childUri.toString())));
serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
}
if (prevBackup != null) {
// Check which collections and resources have been deleted since
// the
// last backup
final CheckDeletedHandler check = new CheckDeletedHandler(current, serializer);
try {
prevBackup.parse(broker.getBrokerPool().getParserPool(), check);
} catch (final Exception e) {
LOG.error("Caught exception while trying to parse previous backup descriptor: {}", prevBackup.getSymbolicPath(), e);
}
}
// close <collection>
serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
serializer.endPrefixMapping("");
serializer.endDocument();
output.closeContents();
} finally {
SerializerPool.getInstance().returnObject(serializer);
// if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
output.closeCollection();
// }
}
}
use of org.exist.util.serializer.SAXSerializer in project exist by eXist-db.
the class ClientFrame method exportAction.
private void exportAction(final ActionEvent ev) {
if (fileman.getSelectedRowCount() == 0) {
return;
}
final int[] rows = fileman.getSelectedRows();
for (final int row : rows) {
final ResourceDescriptor desc = resources.getRow(fileman.convertRowIndexToModel(row));
if (desc.isCollection()) {
continue;
}
final JFileChooser chooser = new JFileChooser(preferences.get("directory.last", System.getProperty("user.dir")));
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setSelectedFile(Paths.get(desc.getName().getCollectionPath()).toFile());
if (chooser.showDialog(this, "Select file for export") == JFileChooser.APPROVE_OPTION) {
preferences.put("directory.last", chooser.getCurrentDirectory().getAbsolutePath());
final Path file = chooser.getSelectedFile().toPath();
if (Files.exists(file) && JOptionPane.showConfirmDialog(this, "File exists. Overwrite?", "Overwrite?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
final Resource resource;
final SAXSerializer contentSerializer;
try {
final Collection collection = client.getCollection();
resource = collection.getResource(desc.getName().toString());
if (resource instanceof ExtendedResource) {
try (final OutputStream os = new BufferedOutputStream(Files.newOutputStream(file))) {
((ExtendedResource) resource).getContentIntoAStream(os);
}
} else {
contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try (final Writer writer = Files.newBufferedWriter(file, UTF_8)) {
// write resource to contentSerializer
contentSerializer.setOutput(writer, properties);
((EXistResource) resource).setLexicalHandler(contentSerializer);
((XMLResource) resource).getContentAsSAX(contentSerializer);
} finally {
SerializerPool.getInstance().returnObject(contentSerializer);
}
}
// TODO finally close os
} catch (final Exception e) {
System.err.println("An exception occurred" + e.getMessage());
e.printStackTrace();
}
}
}
}
Aggregations