Search in sources :

Example 6 with BooleanValue

use of org.exist.xquery.value.BooleanValue in project exist by eXist-db.

the class AccountStatusFunction method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final DBBroker broker = getContext().getBroker();
    final Subject currentUser = broker.getCurrentSubject();
    final SecurityManager securityManager = broker.getBrokerPool().getSecurityManager();
    final String username = args[0].getStringValue();
    if (isCalledAs(qnIsAccountEnabled.getLocalPart())) {
        if (!currentUser.hasDbaRole() && !currentUser.getName().equals(username)) {
            throw new XPathException("You must be a DBA or be enquiring about your own account!");
        }
        final Account account = securityManager.getAccount(username);
        return (account == null) ? BooleanValue.FALSE : new BooleanValue(account.isEnabled());
    } else if (isCalledAs(qnSetAccountEnabled.getLocalPart())) {
        if (!currentUser.hasDbaRole()) {
            throw new XPathException("You must be a DBA to change the status of an account!");
        }
        final boolean enable = args[1].effectiveBooleanValue();
        final Account account = securityManager.getAccount(username);
        account.setEnabled(enable);
        try {
            account.save(broker);
            return Sequence.EMPTY_SEQUENCE;
        } catch (final ConfigurationException | PermissionDeniedException ce) {
            throw new XPathException(ce.getMessage(), ce);
        }
    } else {
        throw new XPathException("Unknown function");
    }
}
Also used : Account(org.exist.security.Account) DBBroker(org.exist.storage.DBBroker) SecurityManager(org.exist.security.SecurityManager) XPathException(org.exist.xquery.XPathException) BooleanValue(org.exist.xquery.value.BooleanValue) Subject(org.exist.security.Subject)

Example 7 with BooleanValue

use of org.exist.xquery.value.BooleanValue 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();
    }
}
Also used : Path(java.nio.file.Path) NodeValue(org.exist.xquery.value.NodeValue) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) IOException(java.io.IOException) Date(java.util.Date) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue)

Example 8 with BooleanValue

use of org.exist.xquery.value.BooleanValue in project exist by eXist-db.

the class FunLang method eval.

public Sequence eval(Sequence contextSequence, Item contextItem) 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);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    if (contextItem != null) {
        contextSequence = contextItem.toSequence();
    }
    if (getArgumentCount() == 2) {
        contextSequence = getArgument(1).eval(contextSequence);
    }
    if (contextSequence == null) {
        throw new XPathException(this, ErrorCodes.XPDY0002, "Undefined context item");
    }
    Sequence result;
    if (!(Type.subTypeOf(contextSequence.getItemType(), Type.NODE))) {
        throw new XPathException(this, ErrorCodes.XPTY0004, "Context item is not a node");
    } else {
        final String lang = getArgument(0).eval(contextSequence).getStringValue();
        Sequence seq = query.eval(contextSequence);
        if (seq.isEmpty()) {
            result = BooleanValue.FALSE;
        } else if (seq.hasOne()) {
            String langValue = seq.getStringValue();
            boolean include = lang.equalsIgnoreCase(langValue);
            if (!include) {
                final int hyphen = langValue.indexOf('-');
                if (hyphen != Constants.STRING_NOT_FOUND) {
                    langValue = langValue.substring(0, hyphen);
                    include = lang.equalsIgnoreCase(langValue);
                }
            }
            result = new BooleanValue(include);
        } else {
            throw new XPathException(this, ErrorCodes.XPTY0004, "Sequence returned more than one item !");
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : XPathException(org.exist.xquery.XPathException) BooleanValue(org.exist.xquery.value.BooleanValue) Sequence(org.exist.xquery.value.Sequence)

Example 9 with BooleanValue

use of org.exist.xquery.value.BooleanValue in project exist by eXist-db.

the class FunCodepointEqual 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()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else if (args[1].isEmpty()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else {
        result = new BooleanValue(Collations.compare(// TODO : how ugly ! We should be able to use Collations.UNICODE_CODEPOINT_COLLATION_URI here ! -pb
        context.getDefaultCollator(), getArgument(0).eval(contextSequence).getStringValue(), getArgument(1).eval(contextSequence).getStringValue()) == Constants.EQUAL);
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : BooleanValue(org.exist.xquery.value.BooleanValue) Sequence(org.exist.xquery.value.Sequence)

Example 10 with BooleanValue

use of org.exist.xquery.value.BooleanValue in project exist by eXist-db.

the class SetCookie method eval.

@Override
public Sequence eval(final Sequence[] args, @Nonnull final ResponseWrapper response) throws XPathException {
    // get parameters
    final String name = args[0].getStringValue();
    final String value = args[1].getStringValue();
    final int maxAge;
    final Sequence secureSeq, domainSeq, pathSeq;
    if (getArgumentCount() > 2) {
        final Sequence ageSeq = args[2];
        secureSeq = args[3];
        if (!ageSeq.isEmpty()) {
            final Duration duration = ((DurationValue) ageSeq.itemAt(0)).getCanonicalDuration();
            maxAge = (int) (duration.getTimeInMillis(new Date(System.currentTimeMillis())) / 1000L);
        } else {
            maxAge = -1;
        }
        if (getArgumentCount() > 4) {
            domainSeq = args[4];
            pathSeq = args[5];
        } else {
            domainSeq = Sequence.EMPTY_SEQUENCE;
            pathSeq = Sequence.EMPTY_SEQUENCE;
        }
    } else {
        secureSeq = Sequence.EMPTY_SEQUENCE;
        domainSeq = Sequence.EMPTY_SEQUENCE;
        pathSeq = Sequence.EMPTY_SEQUENCE;
        maxAge = -1;
    }
    // set response header
    switch(getArgumentCount()) {
        case 2:
            {
                response.addCookie(name, value);
                break;
            }
        case 4:
            {
                if (secureSeq.isEmpty()) {
                    response.addCookie(name, value, maxAge);
                } else {
                    response.addCookie(name, value, maxAge, ((BooleanValue) secureSeq.itemAt(0)).effectiveBooleanValue());
                }
                break;
            }
        case 6:
            {
                boolean secure = false;
                String domain = null;
                String path = null;
                if (!secureSeq.isEmpty()) {
                    secure = ((BooleanValue) secureSeq.itemAt(0)).effectiveBooleanValue();
                }
                if (!domainSeq.isEmpty()) {
                    domain = domainSeq.itemAt(0).getStringValue();
                }
                if (!pathSeq.isEmpty()) {
                    path = pathSeq.itemAt(0).getStringValue();
                }
                response.addCookie(name, value, maxAge, secure, domain, path);
                break;
            }
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : DurationValue(org.exist.xquery.value.DurationValue) BooleanValue(org.exist.xquery.value.BooleanValue) Duration(javax.xml.datatype.Duration) Sequence(org.exist.xquery.value.Sequence) Date(java.util.Date)

Aggregations

BooleanValue (org.exist.xquery.value.BooleanValue)15 XPathException (org.exist.xquery.XPathException)9 Sequence (org.exist.xquery.value.Sequence)9 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)6 ValueSequence (org.exist.xquery.value.ValueSequence)5 NodeValue (org.exist.xquery.value.NodeValue)4 MalformedURLException (java.net.MalformedURLException)3 UnsynchronizedByteArrayInputStream (org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)3 ValidationReport (org.exist.validation.ValidationReport)3 Base64BinaryValueType (org.exist.xquery.value.Base64BinaryValueType)3 DoubleValue (org.exist.xquery.value.DoubleValue)3 StringValue (org.exist.xquery.value.StringValue)3 IOException (java.io.IOException)2 Date (java.util.Date)2 QName (org.exist.dom.QName)2 NodeImpl (org.exist.dom.memtree.NodeImpl)2 IntegerValue (org.exist.xquery.value.IntegerValue)2 PropertyMapBuilder (com.thaiopensource.util.PropertyMapBuilder)1 SchemaReader (com.thaiopensource.validate.SchemaReader)1 ValidationDriver (com.thaiopensource.validate.ValidationDriver)1