use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.
the class GetRunningJobs method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if (!context.getSubject().hasDbaRole()) {
throw (new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to get the list of running jobs"));
}
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
builder.startElement(new QName("jobs", NAMESPACE_URI, PREFIX), null);
final BrokerPool brokerPool = context.getBroker().getBrokerPool();
final ProcessMonitor monitor = brokerPool.getProcessMonitor();
final ProcessMonitor.JobInfo[] jobs = monitor.runningJobs();
for (ProcessMonitor.JobInfo job : jobs) {
final Thread process = job.getThread();
final Date startDate = new Date(job.getStartTime());
builder.startElement(new QName("job", NAMESPACE_URI, PREFIX), null);
builder.addAttribute(new QName("id", null, null), process.getName());
builder.addAttribute(new QName("action", null, null), job.getAction());
builder.addAttribute(new QName("start", null, null), new DateTimeValue(startDate).getStringValue());
builder.addAttribute(new QName("info", null, null), job.getAddInfo().toString());
builder.endElement();
}
builder.endElement();
builder.endDocument();
return (NodeValue) builder.getDocument().getDocumentElement();
} finally {
context.popDocumentContext();
}
}
use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.
the class Directory method eval.
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
if (!context.getSubject().hasDbaRole()) {
XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
logger.error("Invalid user", xPathException);
throw xPathException;
}
final String inputPath = args[0].getStringValue();
final Path directoryPath = FileModuleHelper.getFile(inputPath);
if (logger.isDebugEnabled()) {
logger.debug("Listing matching files in directory: {}", directoryPath.toAbsolutePath().toString());
}
if (!Files.isDirectory(directoryPath)) {
throw new XPathException(this, "'" + inputPath + "' does not point to a valid directory.");
}
// Get list of files, null if baseDir does not point to a directory
context.pushDocumentContext();
try (final Stream<Path> scannedFiles = Files.list(directoryPath)) {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
builder.startElement(new QName("list", null, null), null);
scannedFiles.forEach(entry -> {
if (logger.isDebugEnabled()) {
logger.debug("Found: {}", entry.toAbsolutePath().toString());
}
String entryType = "unknown";
if (Files.isRegularFile(entry)) {
entryType = "file";
} else if (Files.isDirectory(entry)) {
entryType = "directory";
}
builder.startElement(new QName(entryType, NAMESPACE_URI, PREFIX), null);
builder.addAttribute(new QName("name", null, null), FileUtils.fileName(entry));
try {
if (Files.isRegularFile(entry)) {
final Long sizeLong = Files.size(entry);
String sizeString = Long.toString(sizeLong);
String humanSize = getHumanSize(sizeLong, sizeString);
builder.addAttribute(new QName("size", null, null), sizeString);
builder.addAttribute(new QName("human-size", null, null), humanSize);
}
builder.addAttribute(new QName("modified", null, null), new DateTimeValue(new Date(Files.getLastModifiedTime(entry).toMillis())).getStringValue());
builder.addAttribute(new QName("hidden", null, null), new BooleanValue(Files.isHidden(entry)).getStringValue());
builder.addAttribute(new QName("canRead", null, null), new BooleanValue(Files.isReadable(entry)).getStringValue());
builder.addAttribute(new QName("canWrite", null, null), new BooleanValue(Files.isWritable(entry)).getStringValue());
} catch (final IOException | XPathException ioe) {
LOG.warn(ioe);
}
builder.endElement();
});
builder.endElement();
return (NodeValue) builder.getDocument().getDocumentElement();
} catch (final IOException ioe) {
throw new XPathException(this, ioe);
} finally {
context.popDocumentContext();
}
}
use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.
the class Deployment method storeRepoXML.
/**
* Store repo.xml into the db. Adds the time of deployment to the descriptor.
*
* @param repoXML
* @param targetCollection
* @throws XPathException
*/
private void storeRepoXML(final DBBroker broker, final Txn transaction, final DocumentImpl repoXML, final XmldbURI targetCollection, final Optional<RequestedPerms> requestedPerms) throws PackageException, XPathException {
// Store repo.xml
final DateTimeValue time = new DateTimeValue(new Date());
final MemTreeBuilder builder = new MemTreeBuilder();
builder.startDocument();
final UpdatingDocumentReceiver receiver = new UpdatingDocumentReceiver(builder, time.getStringValue());
try {
repoXML.copyTo(broker, receiver);
} catch (final SAXException e) {
throw new PackageException("Error while updating repo.xml in-memory: " + e.getMessage(), e);
}
builder.endDocument();
final DocumentImpl updatedXML = builder.getDocument();
try {
final Collection collection = broker.getOrCreateCollection(transaction, targetCollection);
final XmldbURI name = XmldbURI.createInternal("repo.xml");
final Permission permission = PermissionFactory.getDefaultResourcePermission(broker.getBrokerPool().getSecurityManager());
setPermissions(broker, requestedPerms, false, MimeType.XML_TYPE, permission);
collection.storeDocument(transaction, broker, name, updatedXML, MimeType.XML_TYPE, null, null, permission, null, null);
} catch (final PermissionDeniedException | IOException | SAXException | LockException | EXistException e) {
throw new PackageException("Error while storing updated repo.xml: " + e.getMessage(), e);
}
}
use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.
the class FunDateTime method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null) {
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
}
}
Sequence result;
if (args[0].isEmpty() || args[1].isEmpty()) {
result = Sequence.EMPTY_SEQUENCE;
} else if (args[0].hasMany()) {
throw new XPathException(this, ErrorCodes.XPTY0004, "Expected at most one xs:date", args[0]);
} else if (args[1].hasMany()) {
throw new XPathException(this, ErrorCodes.XPTY0004, "Expected at most one xs:time", args[1]);
} else {
final DateValue dv = (DateValue) args[0].itemAt(0);
final TimeValue tv = (TimeValue) args[1].itemAt(0);
if (!dv.getTimezone().isEmpty()) {
if (!tv.getTimezone().isEmpty()) {
if (!((DayTimeDurationValue) dv.getTimezone().itemAt(0)).compareTo(null, Comparison.EQ, ((DayTimeDurationValue) tv.getTimezone().itemAt(0)))) {
final ValueSequence argsSeq = new ValueSequence();
argsSeq.add(dv);
argsSeq.add(tv);
throw new XPathException(this, ErrorCodes.FORG0008, "Operands have different timezones", argsSeq);
}
}
}
String dtv = ((DateTimeValue) dv.convertTo(Type.DATE_TIME)).getTrimmedCalendar().toXMLFormat();
if (dv.getTimezone().isEmpty()) {
dtv = dtv.substring(0, dtv.length() - 8);
result = new DateTimeValue(dtv + tv.getStringValue());
} else if ("PT0S".equals(((DayTimeDurationValue) dv.getTimezone().itemAt(0)).getStringValue())) {
dtv = dtv.substring(0, dtv.length() - 9);
if (tv.getTimezone().isEmpty()) {
result = new DateTimeValue(dtv + tv.getStringValue() + "Z");
} else {
result = new DateTimeValue(dtv + tv.getStringValue());
}
} else {
if (tv.getTimezone().isEmpty()) {
final String tz = dtv.substring(19);
dtv = dtv.substring(0, dtv.length() - 14);
result = new DateTimeValue(dtv + tv.getStringValue() + tz);
} else {
dtv = dtv.substring(0, dtv.length() - 14);
result = new DateTimeValue(dtv + tv.getStringValue());
}
}
}
if (context.getProfiler().isEnabled()) {
context.getProfiler().end(this, "", result);
}
return result;
}
use of org.exist.xquery.value.DateTimeValue in project exist by eXist-db.
the class RestoreHandler method restoreResourceEntry.
private DeferredPermission restoreResourceEntry(final Attributes atts) throws SAXException {
@Nullable final String skip = atts.getValue("skip");
// Don't process entries which should be skipped
if (skip != null && !"no".equals(skip)) {
return new SkippedEntryDeferredPermission();
}
@Nullable final String name = atts.getValue("name");
if (name == null) {
throw new SAXException("Resource requires a name attribute");
}
final boolean xmlType = Optional.ofNullable(atts.getValue("type")).filter(s -> s.equals("XMLResource")).isPresent();
final String owner = getAttr(atts, "owner", SecurityManager.SYSTEM);
final String group = getAttr(atts, "group", SecurityManager.DBA_GROUP);
final String perms = getAttr(atts, "mode", "644");
final String filename = getAttr(atts, "filename", name);
@Nullable final String mimeTypeStr = atts.getValue("mimetype");
@Nullable final String dateCreatedStr = atts.getValue("created");
@Nullable final String dateModifiedStr = atts.getValue("modified");
@Nullable final String publicId = atts.getValue("publicid");
@Nullable final String systemId = atts.getValue("systemid");
@Nullable final String nameDocType = atts.getValue("namedoctype");
final XmldbURI docName;
if (version >= STRICT_URI_VERSION) {
docName = XmldbURI.create(name);
} else {
try {
docName = URIUtils.encodeXmldbUriFor(name);
} catch (final URISyntaxException e) {
final String msg = "Could not parse document name into a URI: " + e.getMessage();
listener.error(msg);
LOG.error(msg, e);
return new SkippedEntryDeferredPermission();
}
}
final EXistInputSource is;
if (deduplicateBlobs && !xmlType) {
final String blobId = atts.getValue("blob-id");
is = descriptor.getBlobInputSource(blobId);
if (is == null) {
final String msg = "Failed to restore resource '" + name + "'\nfrom BLOB '" + blobId + "'.\nReason: Unable to obtain its EXistInputSource";
listener.warn(msg);
return new SkippedEntryDeferredPermission();
}
} else {
is = descriptor.getInputSource(filename);
if (is == null) {
final String msg = "Failed to restore resource '" + name + "'\nfrom file '" + descriptor.getSymbolicPath(name, false) + "'.\nReason: Unable to obtain its EXistInputSource";
listener.warn(msg);
return new SkippedEntryDeferredPermission();
}
}
MimeType mimeType = null;
if (mimeTypeStr != null) {
mimeType = MimeTable.getInstance().getContentType(mimeTypeStr);
}
if (mimeType == null) {
mimeType = xmlType ? MimeType.XML_TYPE : MimeType.BINARY_TYPE;
}
Date dateCreated = null;
if (dateCreatedStr != null) {
try {
dateCreated = new DateTimeValue(dateCreatedStr).getDate();
} catch (final XPathException xpe) {
listener.warn("Illegal creation date. Ignoring date...");
}
}
Date dateModified = null;
if (dateModifiedStr != null) {
try {
dateModified = new DateTimeValue(dateModifiedStr).getDate();
} catch (final XPathException xpe) {
listener.warn("Illegal modification date. Ignoring date...");
}
}
final DocumentType docType;
if (publicId != null || systemId != null) {
docType = new DocumentTypeImpl(nameDocType, publicId, systemId);
} else {
docType = null;
}
final XmldbURI docUri = currentCollectionUri.append(docName);
try {
try (final Txn transaction = beginTransaction()) {
boolean validated = false;
try {
try (final Collection collection = broker.openCollection(currentCollectionUri, Lock.LockMode.WRITE_LOCK);
final ManagedDocumentLock docLock = broker.getBrokerPool().getLockManager().acquireDocumentWriteLock(docUri)) {
broker.storeDocument(transaction, docName, is, mimeType, dateCreated, dateModified, null, docType, null, collection);
validated = true;
transaction.commit();
// NOTE: early release of Collection lock inline with Asymmetrical Locking scheme
collection.close();
}
} finally {
/*
This allows us to commit the transaction (so the restore doesn't stop)
and still throw an exception to skip over resources that didn't
validate. This preserves eXist-db's previous behaviour
of "best effort attempt" when restoring a backup,
rather than an ACID "all or nothing" approach.
*/
if (!validated) {
// because `validated == false` we know that there have only been reads on the transaction/sub-transaction!
transaction.commit();
}
}
}
final DeferredPermission deferredPermission;
if (name.startsWith(XmldbURI.SYSTEM_COLLECTION)) {
// prevents restore of a backup from changing system collection resource ownership
deferredPermission = new ResourceDeferredPermission(listener, docUri, SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(perms, 8));
} else {
deferredPermission = new ResourceDeferredPermission(listener, docUri, owner, group, Integer.parseInt(perms, 8));
}
listener.restoredResource(name);
return deferredPermission;
} catch (final Exception e) {
final String message = String.format("Failed to restore resource '%s'\nfrom file '%s'.\nReason: %s", name, descriptor.getSymbolicPath(name, false), e.getMessage());
listener.warn(message);
LOG.error(message, e);
return new SkippedEntryDeferredPermission();
} finally {
is.close();
}
}
Aggregations