use of org.exist.dom.persistent.LockedDocument in project exist by eXist-db.
the class ExistDocument method refreshLock.
public LockToken refreshLock(String token) throws PermissionDeniedException, DocumentAlreadyLockedException, EXistException, DocumentNotLockedException {
if (LOG.isDebugEnabled()) {
LOG.debug("refresh lock {} lock={}", xmldbUri, token);
}
if (token == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("token is null");
}
throw new EXistException("token is null");
}
// Try to get document
try (final DBBroker broker = brokerPool.get(Optional.ofNullable(subject));
final LockedDocument lockedDocument = broker.getXMLResource(xmldbUri, LockMode.WRITE_LOCK)) {
final DocumentImpl document = lockedDocument.getDocument();
if (document == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("No resource found for path: {}", xmldbUri);
}
// return null; // throw exception?
throw new EXistException("No resource found.");
}
// Get current userlock
Account userLock = document.getUserLock();
// Check if Resource is already locked.
if (userLock == null) {
final String msg = "Resource was not locked.";
if (LOG.isDebugEnabled()) {
LOG.debug(msg);
}
throw new DocumentNotLockedException(msg);
}
if (userLock.getName() != null && !userLock.getName().equals(subject.getName()) && !subject.hasDbaRole()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Resource is locked by {}", userLock.getName());
}
throw new PermissionDeniedException(userLock.getName());
}
LockToken lockToken = document.getLockToken();
if (!token.equals(lockToken.getOpaqueLockToken())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Token does not match");
}
throw new PermissionDeniedException(String.format("Token %s does not match %s", token, lockToken.getOpaqueLockToken()));
}
lockToken.setTimeOut(LockToken.LOCK_TIMEOUT_INFINITE);
// Make token persistant
final TransactionManager txnManager = brokerPool.getTransactionManager();
try (final Txn txn = txnManager.beginTransaction()) {
broker.storeXMLResource(txn, document);
txnManager.commit(txn);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Successfully retrieved token");
}
return lockToken;
} catch (EXistException | PermissionDeniedException e) {
LOG.error(e);
throw e;
} finally {
if (LOG.isDebugEnabled()) {
LOG.debug("Finished create lock");
}
}
}
use of org.exist.dom.persistent.LockedDocument in project exist by eXist-db.
the class Source method exec.
@Override
public void exec() {
if (fileURI == null) {
return;
}
InputStream is = null;
try {
if (fileURI.toLowerCase().startsWith("dbgp://")) {
String uri = fileURI.substring(7);
if (uri.toLowerCase().startsWith("file:/")) {
uri = fileURI.substring(5);
is = Files.newInputStream(Paths.get(uri));
} else {
XmldbURI pathUri = XmldbURI.create(URLDecoder.decode(fileURI.substring(15), "UTF-8"));
Database db = getJoint().getContext().getDatabase();
try (final DBBroker broker = db.getBroker();
final LockedDocument resource = broker.getXMLResource(pathUri, LockMode.READ_LOCK)) {
if (resource.getDocument().getResourceType() == DocumentImpl.BINARY_FILE) {
is = broker.getBinaryResource((BinaryDocument) resource.getDocument());
} else {
// TODO: xml source???
return;
}
} catch (EXistException e) {
exception = e;
}
}
} else {
URL url = new URL(fileURI);
URLConnection conn = url.openConnection();
is = conn.getInputStream();
}
UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream();
byte[] buf = new byte[256];
int c;
while ((c = is.read(buf)) > -1) {
// TODO: begin & end line should affect
baos.write(buf, 0, c);
}
source = baos.toByteArray();
success = true;
} catch (PermissionDeniedException | IOException e) {
exception = e;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
if (exception == null) {
exception = e;
}
}
}
}
}
use of org.exist.dom.persistent.LockedDocument in project exist by eXist-db.
the class RestoreHandler method restoreDeletedEntry.
private void restoreDeletedEntry(final Attributes atts) {
final String name = atts.getValue("name");
final String type = atts.getValue("type");
if ("collection".equals(type)) {
try {
try (final Txn transaction = beginTransaction();
final Collection collection = broker.openCollection(currentCollectionUri.append(name), Lock.LockMode.WRITE_LOCK)) {
if (collection != null) {
final boolean triggersEnabled = broker.isTriggersEnabled();
try {
broker.setTriggersEnabled(false);
broker.removeCollection(transaction, collection);
} finally {
// restore triggers enabled setting
broker.setTriggersEnabled(triggersEnabled);
}
}
transaction.commit();
}
} catch (final PermissionDeniedException | IOException | TriggerException | TransactionException e) {
listener.warn("Failed to remove deleted collection: " + name + ": " + e.getMessage());
}
} else if ("resource".equals(type)) {
final XmldbURI docName = XmldbURI.create(name);
try (final Txn transaction = beginTransaction();
final Collection collection = broker.openCollection(currentCollectionUri.append(name), Lock.LockMode.WRITE_LOCK);
final LockedDocument lockedDocument = collection.getDocumentWithLock(broker, docName, Lock.LockMode.WRITE_LOCK)) {
// Check that the document exists
if (lockedDocument != null) {
final boolean triggersEnabled = broker.isTriggersEnabled();
try {
broker.setTriggersEnabled(false);
final boolean xmlType = !(lockedDocument.getDocument() instanceof BinaryDocument);
if (xmlType) {
collection.removeXMLResource(transaction, broker, docName);
} else {
collection.removeBinaryResource(transaction, broker, docName);
}
} finally {
// restore triggers enabled setting
broker.setTriggersEnabled(triggersEnabled);
}
}
transaction.commit();
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
} catch (final PermissionDeniedException | TransactionException | TriggerException | LockException | IOException e) {
listener.warn("Failed to remove deleted resource: " + name + ": " + e.getMessage());
}
}
}
use of org.exist.dom.persistent.LockedDocument in project exist by eXist-db.
the class ConstructedNodesRecoveryTest method testDocumentIsValid.
private void testDocumentIsValid(final DBBroker broker, final TransactionManager transact, final String documentName) throws PermissionDeniedException, IOException, SAXException, LockException, TransactionException {
// create a transaction
try (final Txn transaction = transact.beginTransaction()) {
// get the test collection
final Collection root = broker.getOrCreateCollection(transaction, TestConstants.TEST_COLLECTION_URI);
assertNotNull(root);
broker.saveCollection(transaction, root);
// get the test document
try (final LockedDocument lockedDoc = root.getDocumentWithLock(broker, XmldbURI.create(documentName), LockMode.READ_LOCK)) {
final DocumentImpl doc = lockedDoc.getDocument();
assertNotNull(doc);
assertEquals(testDocument, serialize(broker, doc));
}
transact.commit(transaction);
}
}
use of org.exist.dom.persistent.LockedDocument in project exist by eXist-db.
the class InstallFunction method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
Sequence removed = BooleanValue.FALSE;
boolean force = true;
UserInteractionStrategy interact = new BatchUserInteraction();
String pkgOrPath = args[0].getStringValue();
Optional<ExistRepository> repo = getContext().getRepository();
try {
if (repo.isPresent()) {
Repository parent_repo = repo.get().getParentRepo();
Package pkg;
if (isCalledAs("install")) {
// download .xar from a URI
URI uri = _getURI(pkgOrPath);
pkg = parent_repo.installPackage(uri, force, interact);
repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
} else {
// .xar is stored as a binary resource
try (final LockedDocument lockedDoc = getBinaryDoc(pkgOrPath);
final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
final DocumentImpl doc = lockedDoc.getDocument();
LOG.debug("Installing file: {}", doc.getURI());
pkg = parent_repo.installPackage(new BinaryDocumentXarSource(context.getBroker().getBrokerPool(), transaction, (BinaryDocument) doc), force, interact);
repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
transaction.commit();
}
}
ExistPkgInfo info = (ExistPkgInfo) pkg.getInfo("exist");
if (info != null && !info.getJars().isEmpty())
ClasspathHelper.updateClasspath(context.getBroker().getBrokerPool(), pkg);
// TODO: expath libs do not provide a way to see if there were any XQuery modules installed at all
context.getBroker().getBrokerPool().getXQueryPool().clear();
removed = BooleanValue.TRUE;
} else {
throw new XPathException("expath repository not available");
}
} catch (PackageException | TransactionException ex) {
logger.error(ex.getMessage(), ex);
return removed;
// /TODO: _repo.removePackage seems to throw PackageException
// throw new XPathException("Problem installing package " + pkg + " in expath repository, check that eXist-db has access permissions to expath repository file directory ", ex);
} catch (XPathException xpe) {
logger.error(xpe.getMessage());
return removed;
}
return removed;
}
Aggregations