use of org.exist.EXistException in project exist by eXist-db.
the class RpcConnection method upload.
public String upload(final byte[] chunk, final int length, @Nullable String fileName, final boolean compressed) throws EXistException, IOException {
final OpenOption[] openOptions;
final Path tempFile;
if (fileName == null || fileName.length() == 0) {
// no fileName, so new file
openOptions = new OpenOption[] { CREATE, TRUNCATE_EXISTING, WRITE };
// create temporary file
tempFile = TemporaryFileManager.getInstance().getTemporaryFile();
final int handle = factory.resultSets.add(new SerializedResult(tempFile));
fileName = Integer.toString(handle);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Appending to file {}", fileName);
}
// fileName was specified so this is an append
openOptions = new OpenOption[] { CREATE, APPEND, WRITE };
try {
final int handle = Integer.parseInt(fileName);
final SerializedResult sr = factory.resultSets.getSerializedResult(handle);
if (sr == null) {
throw new EXistException("Invalid handle specified");
}
// This will keep the serialized result in the cache
sr.touch();
tempFile = sr.result;
} catch (final NumberFormatException nfe) {
throw new EXistException("Syntactically invalid handle specified");
}
}
try (final OutputStream os = new BufferedOutputStream(Files.newOutputStream(tempFile, openOptions))) {
if (compressed) {
final int uncompressedLen = Compressor.uncompress(chunk, os);
if (uncompressedLen != length) {
throw new IOException("Expected " + length + " bytes of uncompressed data, but actually " + uncompressedLen);
}
} else {
os.write(chunk, 0, length);
}
}
return fileName;
}
use of org.exist.EXistException in project exist by eXist-db.
the class RpcConnection method beginProtected.
protected LockedDocumentMap beginProtected(final DBBroker broker, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
final String protectColl = (String) parameters.get(RpcAPI.PROTECTED_MODE);
if (protectColl == null) {
return null;
}
int retries = BEGIN_PROTECTED_MAX_LOCKING_RETRIES == -1 ? -1 : BEGIN_PROTECTED_MAX_LOCKING_RETRIES - 2;
do {
MutableDocumentSet docs = null;
final LockedDocumentMap lockedDocuments = new LockedDocumentMap();
final LockMode documentLockMode = LockMode.WRITE_LOCK;
final LockMode collectionLockMode = broker.getBrokerPool().getLockManager().relativeCollectionLockMode(LockMode.READ_LOCK, documentLockMode);
try (final Collection coll = broker.openCollection(XmldbURI.createInternal(protectColl), collectionLockMode)) {
docs = new DefaultDocumentSet();
coll.allDocs(broker, docs, true, lockedDocuments, documentLockMode);
return lockedDocuments;
} catch (final LockException e) {
LOG.warn("Deadlock detected. Starting over again. Docs: {}; locked: {}. Cause: {}", docs.getDocumentCount(), lockedDocuments.size(), e.getMessage());
lockedDocuments.unlock();
}
retries--;
} while (retries >= -1);
throw new EXistException("Unable to beginProtected after " + BEGIN_PROTECTED_MAX_LOCKING_RETRIES + " retries");
}
use of org.exist.EXistException in project exist by eXist-db.
the class RpcConnection method retrieveAllAsString.
private String retrieveAllAsString(final int resultId, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
return withDb((broker, transaction) -> {
final QueryResult qr = factory.resultSets.getResult(resultId);
if (qr == null) {
throw new EXistException("result set unknown or timed out");
}
qr.touch();
final SAXSerializer handler = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
try (final StringWriter writer = new StringWriter()) {
handler.setOutput(writer, toProperties(parameters));
// serialize results
handler.startDocument();
handler.startPrefixMapping("exist", Namespaces.EXIST_NS);
handler.startPrefixMapping("xs", Namespaces.SCHEMA_NS);
final AttributesImpl attribs = new AttributesImpl();
attribs.addAttribute("", "hitCount", "hitCount", "CDATA", Integer.toString(qr.result.getItemCount()));
handler.startElement(Namespaces.EXIST_NS, "result", "exist:result", attribs);
Item current;
char[] value;
try {
for (final SequenceIterator i = qr.result.iterate(); i.hasNext(); ) {
current = i.nextItem();
if (Type.subTypeOf(current.getType(), Type.NODE)) {
current.toSAX(broker, handler, null);
} else {
final AttributesImpl typeAttr = new AttributesImpl();
typeAttr.addAttribute("", "type", "type", "CDATA", Type.getTypeName(current.getType()));
handler.startElement(Namespaces.EXIST_NS, "value", "exist:value", typeAttr);
value = current.toString().toCharArray();
handler.characters(value, 0, value.length);
handler.endElement(Namespaces.EXIST_NS, "value", "exist:value");
}
}
} catch (final XPathException e) {
throw new EXistException(e);
}
handler.endElement(Namespaces.EXIST_NS, "result", "exist:result");
handler.endPrefixMapping("xs");
handler.endPrefixMapping("exist");
handler.endDocument();
return writer.toString();
} finally {
SerializerPool.getInstance().returnObject(handler);
}
});
}
use of org.exist.EXistException in project exist by eXist-db.
the class RpcConnection method updateAccount.
/**
* Added by {Marco.Tampucci, Massimo.Martinelli} @isti.cnr.it
*
* modified by Chris Tomlinson based on above updateAccount - it appears
* that this code can rely on the SecurityManager to enforce policy about
* whether user is or is not permitted to update the Account with name.
*
* This is called via RemoteUserManagementService.removeGroup(Account,
* String)
*
* @param name username to update
* @param groups a list of groups
* @param rgroup the user will be removed from this group
* @return true, if the action succeeded
*/
public boolean updateAccount(final String name, final List<String> groups, final String rgroup) {
try {
return withDb((broker, transaction) -> {
final SecurityManager manager = broker.getBrokerPool().getSecurityManager();
final Account u = manager.getAccount(name);
for (final String g : groups) {
if (g.equals(rgroup)) {
u.remGroup(g);
}
}
return manager.updateAccount(u);
});
} catch (final EXistException | PermissionDeniedException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("removeGroup encountered error", ex);
}
return false;
}
}
use of org.exist.EXistException in project exist by eXist-db.
the class TriggerSystemTask method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
final String className = args[0].getStringValue();
final Properties properties = new Properties();
if (args[1].hasOne()) {
parseParameters(((NodeValue) args[1].itemAt(0)).getNode(), properties);
}
try {
final Class<?> clazz = Class.forName(className);
final Object taskObject = clazz.newInstance();
if (!(taskObject instanceof SystemTask)) {
final XPathException xPathException = new XPathException(this, className + " is not an instance of org.exist.storage.SystemTask");
logger.error("Java classname is not a SystemTask", xPathException);
throw xPathException;
}
final SystemTask task = (SystemTask) taskObject;
task.configure(context.getBroker().getConfiguration(), properties);
LOG.info("Triggering SystemTask: {}", className);
context.getBroker().getBrokerPool().triggerSystemTask(task);
} catch (final ClassNotFoundException e) {
final String message = "system task class '" + className + "' not found";
logger.error(message, e);
throw new XPathException(this, message);
} catch (final InstantiationException e) {
final String message = "system task '" + className + "' can not be instantiated";
logger.error(message, e);
throw new XPathException(this, message);
} catch (final IllegalAccessException e) {
final String message = "system task '" + className + "' can not be accessed";
logger.error(message, e);
throw new XPathException(this, message);
} catch (final EXistException e) {
final String message = "system task " + className + " reported an error during initialization: ";
logger.error(message, e);
throw new XPathException(this, message + e.getMessage(), e);
}
return Sequence.EMPTY_SEQUENCE;
}
Aggregations