use of org.xmldb.api.modules.XMLResource 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();
}
}
}
}
use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.
the class XMLDBXQueryTask method execute.
@Override
public void execute() throws BuildException {
if (uri == null) {
throw new BuildException("you have to specify an XMLDB collection URI");
}
if (text != null) {
final PropertyHelper helper = PropertyHelper.getPropertyHelper(getProject());
query = helper.replaceProperties(null, text, null);
}
if (queryFile == null && query == null && queryUri == null) {
throw new BuildException("you have to specify a query either as attribute, text, URI or in a file");
}
registerDatabase();
try {
log("Get base collection: " + uri, Project.MSG_DEBUG);
final Collection base = DatabaseManager.getCollection(uri, user, password);
if (base == null) {
final String msg = "Collection " + uri + " could not be found.";
if (failonerror) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
} else {
final EXistXQueryService service = (EXistXQueryService) base.getService("XQueryService", "1.0");
// set pretty-printing on
service.setProperty(OutputKeys.INDENT, "yes");
service.setProperty(OutputKeys.ENCODING, "UTF-8");
for (final Variable var : variables) {
System.out.println("Name: " + var.name);
System.out.println("Value: " + var.value);
service.declareVariable(var.name, var.value);
}
final Source source;
if (queryUri != null) {
log("XQuery url " + queryUri, Project.MSG_DEBUG);
if (queryUri.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
final Resource resource = base.getResource(queryUri);
source = new BinarySource((byte[]) resource.getContent(), true);
} else {
source = new URLSource(new URL(queryUri));
}
} else if (queryFile != null) {
log("XQuery file " + queryFile.getAbsolutePath(), Project.MSG_DEBUG);
source = new FileSource(queryFile.toPath(), true);
} else {
log("XQuery string: " + query, Project.MSG_DEBUG);
source = new StringSource(query);
}
final ResourceSet results = service.execute(source);
log("Found " + results.getSize() + " results", Project.MSG_INFO);
if ((destDir != null) && (results != null)) {
log("write results to directory " + destDir.getAbsolutePath(), Project.MSG_INFO);
final ResourceIterator iter = results.getIterator();
log("Writing results to directory " + destDir.getAbsolutePath(), Project.MSG_DEBUG);
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
log("Writing resource " + res.getId(), Project.MSG_DEBUG);
writeResource(res, destDir);
}
} else if (outputproperty != null) {
final ResourceIterator iter = results.getIterator();
String result = null;
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
result = res.getContent().toString();
}
getProject().setNewProperty(outputproperty, result);
}
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught while executing query: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
} catch (final IOException e) {
final String msg = "XMLDB exception caught while writing destination file: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
}
use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.
the class Backup method backup.
private void backup(final Set<String> seenBlobIds, final Collection current, final BackupWriter output, final BackupDialog dialog) throws XMLDBException, IOException, SAXException {
if (current == null) {
return;
}
current.setProperty(OutputKeys.ENCODING, defaultOutputProperties.getProperty(OutputKeys.ENCODING));
current.setProperty(OutputKeys.INDENT, defaultOutputProperties.getProperty(OutputKeys.INDENT));
current.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, defaultOutputProperties.getProperty(EXistOutputKeys.EXPAND_XINCLUDES));
current.setProperty(EXistOutputKeys.PROCESS_XSL_PI, defaultOutputProperties.getProperty(EXistOutputKeys.PROCESS_XSL_PI));
// get collections and documents
final String[] collections = current.listChildCollections();
final String[] resources = current.listResources();
// do not sort: order is important because permissions need to be read in the same order below
// Arrays.sort( resources );
final UserManagementService mgtService = (UserManagementService) current.getService("UserManagementService", "1.0");
final Permission[] perms = mgtService.listResourcePermissions();
final Permission currentPerms = mgtService.getPermissions(current);
if (dialog != null) {
dialog.setCollection(current.getName());
dialog.setResourceCount(resources.length);
}
final Writer contents = output.newContents();
// serializer writes to __contents__.xml
final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try {
serializer.setOutput(contents, contentsOutputProps);
serializer.startDocument();
serializer.startPrefixMapping("", Namespaces.EXIST_NS);
// write <collection> element
final EXistCollection cur = (EXistCollection) current;
final AttributesImpl attr = new AttributesImpl();
// The name should have come from an XmldbURI.toString() call
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", current.getName());
writeUnixStylePermissionAttributes(attr, currentPerms);
attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(cur.getCreationTime()));
attr.addAttribute(Namespaces.EXIST_NS, "deduplicate-blobs", "deduplicate-blobs", "CDATA", Boolean.toString(deduplicateBlobs));
attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(BACKUP_FORMAT_VERSION));
serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
if (currentPerms instanceof ACLPermission) {
writeACLPermission(serializer, (ACLPermission) currentPerms);
}
// scan through resources
for (int i = 0; i < resources.length; i++) {
try {
if ("__contents__.xml".equals(resources[i])) {
// Skipping resources[i]
continue;
}
final Resource resource = current.getResource(resources[i]);
if (dialog != null) {
dialog.setResource(resources[i]);
dialog.setProgress(i);
}
// Avoid NPE
if (resource == null) {
final String msg = "Resource " + resources[i] + " could not be found.";
if (dialog != null) {
Object[] options = { "Ignore", "Abort" };
int n = JOptionPane.showOptionDialog(null, msg, "Backup Error", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
if (n == JOptionPane.YES_OPTION) {
// ignore one
continue;
}
// Abort
dialog.dispose();
JOptionPane.showMessageDialog(null, "Backup aborted.", "Abort", JOptionPane.WARNING_MESSAGE);
}
throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, msg);
}
final String name = resources[i];
String filename = encode(URIUtils.urlDecodeUtf8(resources[i]));
if (".".equals(name.trim())) {
filename = EXIST_GENERATED_FILENAME_DOT_FILENAME + i;
} else if ("..".equals(name.trim())) {
filename = EXIST_GENERATED_FILENAME_DOTDOT_FILENAME + i;
}
final OutputStream os;
if (resource instanceof ExtendedResource) {
if (deduplicateBlobs && resource instanceof EXistBinaryResource) {
// only add distinct blobs to the Blob Store once!
final String blobId = ((EXistBinaryResource) resource).getBlobId().toString();
if (!seenBlobIds.contains(blobId)) {
os = output.newBlobEntry(blobId);
((ExtendedResource) resource).getContentIntoAStream(os);
output.closeEntry();
seenBlobIds.add(blobId);
}
} else {
os = output.newEntry(filename);
((ExtendedResource) resource).getContentIntoAStream(os);
output.closeEntry();
}
} else {
os = output.newEntry(filename);
final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
// write resource to contentSerializer
final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try {
contentSerializer.setOutput(writer, defaultOutputProperties);
((EXistResource) resource).setLexicalHandler(contentSerializer);
((XMLResource) resource).getContentAsSAX(contentSerializer);
} finally {
SerializerPool.getInstance().returnObject(contentSerializer);
}
writer.flush();
output.closeEntry();
}
final EXistResource ris = (EXistResource) resource;
// store permissions
attr.clear();
attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", resource.getResourceType());
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", name);
writeUnixStylePermissionAttributes(attr, perms[i]);
Date date = ris.getCreationTime();
if (date != null) {
attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(date));
}
date = ris.getLastModificationTime();
if (date != null) {
attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", "" + new DateTimeValue(date));
}
attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", filename);
attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", encode(((EXistResource) resource).getMimeType()));
if (!"BinaryResource".equals(resource.getResourceType())) {
if (ris.getDocType() != null) {
if (ris.getDocType().getName() != null) {
attr.addAttribute(Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", ris.getDocType().getName());
}
if (ris.getDocType().getPublicId() != null) {
attr.addAttribute(Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", ris.getDocType().getPublicId());
}
if (ris.getDocType().getSystemId() != null) {
attr.addAttribute(Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", ris.getDocType().getSystemId());
}
}
} else {
attr.addAttribute(Namespaces.EXIST_NS, "blob-id", "blob-id", "CDATA", ((EXistBinaryResource) ris).getBlobId().toString());
}
serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
if (perms[i] instanceof ACLPermission) {
writeACLPermission(serializer, (ACLPermission) perms[i]);
}
serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
} catch (final XMLDBException e) {
System.err.println("Failed to backup resource " + resources[i] + " from collection " + current.getName());
throw e;
}
}
// write sub-collections
for (final String collection : collections) {
if (current.getName().equals(XmldbURI.SYSTEM_COLLECTION) && "temp".equals(collection)) {
continue;
}
attr.clear();
attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", collection);
attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", encode(URIUtils.urlDecodeUtf8(collection)));
serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
}
// close <collection>
serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
serializer.endPrefixMapping("");
serializer.endDocument();
output.closeContents();
} finally {
SerializerPool.getInstance().returnObject(serializer);
}
// descend into sub-collections
for (final String collection : collections) {
final Collection child = current.getChildCollection(collection);
if (child.getName().equals(XmldbURI.TEMP_COLLECTION)) {
continue;
}
output.newCollection(encode(URIUtils.urlDecodeUtf8(collection)));
backup(seenBlobIds, child, output, dialog);
output.closeCollection();
}
}
use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.
the class XMLDBXPathTask method execute.
@Override
public void execute() throws BuildException {
if (uri == null) {
throw new BuildException("you have to specify an XMLDB collection URI");
}
if (text != null) {
final PropertyHelper helper = PropertyHelper.getPropertyHelper(getProject());
query = helper.replaceProperties(null, text, null);
}
if (query == null) {
throw new BuildException("you have to specify a query");
}
log("XPath is: " + query, org.apache.tools.ant.Project.MSG_DEBUG);
registerDatabase();
try {
log("Get base collection: " + uri, Project.MSG_DEBUG);
final Collection base = DatabaseManager.getCollection(uri, user, password);
if (base == null) {
final String msg = "Collection " + uri + " could not be found.";
if (failonerror) {
throw new BuildException(msg);
} else {
log(msg, Project.MSG_ERR);
}
} else {
final XPathQueryService service = (XPathQueryService) base.getService("XPathQueryService", "1.0");
// set pretty-printing on
service.setProperty(OutputKeys.INDENT, "yes");
service.setProperty(OutputKeys.ENCODING, "UTF-8");
if (namespace != null) {
log("Using namespace: " + namespace, Project.MSG_DEBUG);
service.setNamespace("ns", namespace);
}
final ResourceSet results;
if (resource != null) {
log("Query resource: " + resource, Project.MSG_DEBUG);
results = service.queryResource(resource, query);
} else {
log("Query collection", Project.MSG_DEBUG);
results = service.query(query);
}
log("Found " + results.getSize() + " results", Project.MSG_INFO);
if ((destDir != null) && (results != null)) {
log("write results to directory " + destDir.getAbsolutePath(), Project.MSG_INFO);
final ResourceIterator iter = results.getIterator();
log("Writing results to directory " + destDir.getAbsolutePath(), Project.MSG_DEBUG);
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
log("Writing resource " + res.getId(), Project.MSG_DEBUG);
writeResource(res, destDir);
}
} else if (outputproperty != null) {
if (count) {
getProject().setNewProperty(outputproperty, String.valueOf(results.getSize()));
} else {
final ResourceIterator iter = results.getIterator();
final StringBuilder result = new StringBuilder();
while (iter.hasMoreResources()) {
final XMLResource res = (XMLResource) iter.nextResource();
result.append(res.getContent().toString());
result.append("\n");
}
getProject().setNewProperty(outputproperty, result.toString());
}
}
}
} catch (final XMLDBException e) {
final String msg = "XMLDB exception caught while executing query: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
} catch (final IOException e) {
final String msg = "XMLDB exception caught while writing destination file: " + e.getMessage();
if (failonerror) {
throw new BuildException(msg, e);
} else {
log(msg, e, Project.MSG_ERR);
}
}
}
use of org.xmldb.api.modules.XMLResource in project exist by eXist-db.
the class DOMTestJUnit method domUpdate.
/**
* test Update of an existing document through DOM
*/
@Test
public void domUpdate() throws XMLDBException {
XMLResource index = (XMLResource) rootColl.getResource(name);
String content = (String) index.getContent();
Document doc = null;
Element root = null;
NodeList nl = null;
Node n = index.getContentAsDOM();
if (n instanceof Document) {
doc = (Document) n;
root = doc.getDocumentElement();
} else if (n instanceof Element) {
doc = n.getOwnerDocument();
root = (Element) n;
} else {
fail("RemoteXMLResource unable to return a Document either an Element");
}
nl = doc.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
nl.item(i).getNodeName();
}
Element schemaNode = doc.createElement("schema");
schemaNode.setAttribute("targetNamespace", "targetNamespace");
schemaNode.setAttribute("resourceName", "filename");
root.appendChild(schemaNode);
index.setContentAsDOM(doc);
rootColl.storeResource(index);
index = (XMLResource) rootColl.getResource(name);
content = (String) index.getContent();
n = index.getContentAsDOM();
if (n instanceof Document) {
doc = (Document) n;
root = doc.getDocumentElement();
} else if (n instanceof Element) {
doc = n.getOwnerDocument();
root = (Element) n;
}
nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
nl.item(i).getNodeName();
}
}
Aggregations