Search in sources :

Example 11 with StringValue

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

the class BinaryToStringTest method roundtrip.

@Test
public void roundtrip() throws XPathException {
    final String value = "hello world";
    final String encoding = "UTF-8";
    TestableBinaryToString testable = new TestableBinaryToString(new MockXQueryContext(), null);
    final BinaryValue binary = testable.stringToBinary(value, encoding);
    StringValue result = testable.binaryToString(binary, encoding);
    assertEquals(value, result.getStringValue());
}
Also used : BinaryValue(org.exist.xquery.value.BinaryValue) StringValue(org.exist.xquery.value.StringValue) Test(org.junit.Test)

Example 12 with StringValue

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

the class ResourceFunctionExecutorImpl method convertToType.

// TODO this needs to be abstracted into EXQuery library / or not, see the TODOs below
private <X> TypedValue<X> convertToType(final XQueryContext xqueryContext, final String argumentName, final TypedValue typedValue, final org.exquery.xquery.Type destinationType, final Class<X> underlyingDestinationClass) throws RestXqServiceException {
    // TODO consider changing Types that can be used as <T> to TypedValue to a set of interfaces for XDM types that
    // require absolute minimal implementation, and we provide some default or abstract implementations if possible
    final Item convertedValue;
    try {
        final int existDestinationType = TypeAdapter.toExistType(destinationType);
        final Item value;
        // Consider a factory or java.util.ServiceLoader pattern
        if (typedValue instanceof org.exquery.xdm.type.StringTypedValue) {
            value = new StringValue(((org.exquery.xdm.type.StringTypedValue) typedValue).getValue());
        } else if (typedValue instanceof org.exquery.xdm.type.Base64BinaryTypedValue) {
            value = BinaryValueFromInputStream.getInstance(xqueryContext, new Base64BinaryValueType(), ((org.exquery.xdm.type.Base64BinaryTypedValue) typedValue).getValue());
        } else {
            value = (Item) typedValue.getValue();
        }
        if (existDestinationType == value.getType()) {
            convertedValue = value;
        } else if (value instanceof AtomicValue) {
            convertedValue = value.convertTo(existDestinationType);
        } else {
            LOG.warn("Could not convert parameter '{}' from '{}' to '{}'.", argumentName, typedValue.getType().name(), destinationType.name());
            convertedValue = value;
        }
    } catch (final XPathException xpe) {
        // TODO define an ErrorCode
        throw new RestXqServiceException("TODO need to implement error code for problem with parameter conversion!: " + xpe.getMessage(), xpe);
    }
    return new TypedValue<X>() {

        @Override
        public org.exquery.xquery.Type getType() {
            // return destinationType;
            return TypeAdapter.toExQueryType(convertedValue.getType());
        }

        @Override
        public X getValue() {
            return (X) convertedValue;
        }
    };
}
Also used : RestXqServiceException(org.exquery.restxq.RestXqServiceException) org.exist.xquery(org.exist.xquery) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) AtomicValue(org.exist.xquery.value.AtomicValue) Item(org.exist.xquery.value.Item) StringValue(org.exist.xquery.value.StringValue) TypedValue(org.exquery.xquery.TypedValue)

Example 13 with StringValue

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

the class CookieFunctions method getCookie.

private Sequence getCookie(final HttpRequest request, final String cookieName, final Sequence defaultValues) throws XPathException {
    final Sequence result;
    final String cookieValue = request.getCookieValue(cookieName);
    if (cookieValue == null) {
        if (defaultValues != null) {
            result = defaultValues;
        } else {
            result = Sequence.EMPTY_SEQUENCE;
        }
    } else {
        result = new StringValue(cookieValue);
    }
    return result;
}
Also used : Sequence(org.exist.xquery.value.Sequence) StringValue(org.exist.xquery.value.StringValue)

Example 14 with StringValue

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

the class NativeValueIndex method matchAll.

/**
 * Regular expression search.
 *
 * @param docs               DOCUMENT ME!
 * @param contextSet         DOCUMENT ME!
 * @param axis               DOCUMENT ME!
 * @param expr               DOCUMENT ME!
 * @param qnames             DOCUMENT ME!
 * @param type               like type argument for {@link org.exist.storage.RegexMatcher} constructor
 * @param flags              like flags argument for {@link org.exist.storage.RegexMatcher} constructor
 * @param caseSensitiveQuery DOCUMENT ME!
 * @param result             DOCUMENT ME!
 * @param collator           DOCUMENT ME!
 * @param truncation         The type of string truncation to apply
 * @param watchDog  the watchdog
 * @return DOCUMENT ME!
 * @throws TerminatedException DOCUMENT ME!
 * @throws EXistException      DOCUMENT ME!
 */
public NodeSet matchAll(final XQueryWatchDog watchDog, final DocumentSet docs, final NodeSet contextSet, final int axis, final String expr, final List<QName> qnames, final int type, final int flags, final boolean caseSensitiveQuery, final NodeSet result, final Collator collator, final StringTruncationOperator truncation) throws TerminatedException, EXistException {
    // if the match expression starts with a char sequence, we restrict the index scan to entries starting with
    // the same sequence. Otherwise, we have to scan the whole index.
    final StringValue startTerm;
    if (type == DBBroker.MATCH_REGEXP && expr.startsWith("^") && caseSensitiveQuery == caseSensitive) {
        final StringBuilder term = new StringBuilder();
        for (int j = 1; j < expr.length(); j++) {
            if (Character.isLetterOrDigit(expr.charAt(j))) {
                term.append(expr.charAt(j));
            } else {
                break;
            }
        }
        if (term.length() > 0) {
            startTerm = new StringValue(term.toString());
            LOG.debug("Match will begin index scan at '{}'", startTerm);
        } else {
            startTerm = null;
        }
    } else if (collator == null && (type == DBBroker.MATCH_EXACT || type == DBBroker.MATCH_STARTSWITH)) {
        startTerm = new StringValue(expr);
        LOG.debug("Match will begin index scan at '{}'", startTerm);
    } else {
        startTerm = null;
    }
    // Select appropriate matcher/comparator
    final TermMatcher matcher;
    if (collator == null) {
        switch(type) {
            case DBBroker.MATCH_EXACT:
                matcher = new ExactMatcher(expr);
                break;
            case DBBroker.MATCH_CONTAINS:
                matcher = new ContainsMatcher(expr);
                break;
            case DBBroker.MATCH_STARTSWITH:
                matcher = new StartsWithMatcher(expr);
                break;
            case DBBroker.MATCH_ENDSWITH:
                matcher = new EndsWithMatcher(expr);
                break;
            default:
                matcher = new RegexMatcher(expr, flags);
        }
    } else {
        matcher = new CollatorMatcher(expr, truncation, collator);
    }
    final MatcherCallback cb = new MatcherCallback(docs, contextSet, result, matcher, axis == NodeSet.ANCESTOR);
    for (final Iterator<Collection> iter = docs.getCollectionIterator(); iter.hasNext(); ) {
        final int collectionId = iter.next().getId();
        watchDog.proceed(null);
        if (qnames == null) {
            try (final ManagedLock<ReentrantLock> bfileLock = lockManager.acquireBtreeReadLock(dbValues.getLockName())) {
                final Value searchKey;
                if (startTerm != null) {
                    // Compute a key for the start term in the collection
                    searchKey = new SimpleValue(collectionId, startTerm);
                } else {
                    // Compute a key for an arbitrary string in the collection
                    searchKey = new SimplePrefixValue(collectionId, Type.STRING);
                }
                final IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, searchKey);
                dbValues.query(query, cb);
            } catch (final IOException | BTreeException e) {
                LOG.error(e.getMessage(), e);
            } catch (final LockException e) {
                LOG.warn("Failed to acquire lock for '{}'", FileUtils.fileName(dbValues.getFile()), e);
            }
        } else {
            for (final QName qname : qnames) {
                try (final ManagedLock<ReentrantLock> bfileLock = lockManager.acquireBtreeReadLock(dbValues.getLockName())) {
                    final Value searchKey;
                    if (startTerm != null) {
                        searchKey = new QNameValue(collectionId, qname, startTerm, broker.getBrokerPool().getSymbols());
                    } else {
                        LOG.debug("Searching with QName prefix");
                        searchKey = new QNamePrefixValue(collectionId, qname, Type.STRING, broker.getBrokerPool().getSymbols());
                    }
                    final IndexQuery query = new IndexQuery(IndexQuery.TRUNC_RIGHT, searchKey);
                    dbValues.query(query, cb);
                } catch (final IOException | BTreeException e) {
                    LOG.error(e.getMessage(), e);
                } catch (final LockException e) {
                    LOG.warn("Failed to acquire lock for '{}'", FileUtils.fileName(dbValues.getFile()), e);
                }
            }
        }
    }
    return result;
}
Also used : BTreeException(org.exist.storage.btree.BTreeException) StringValue(org.exist.xquery.value.StringValue) ReentrantLock(java.util.concurrent.locks.ReentrantLock) IndexQuery(org.exist.storage.btree.IndexQuery) QName(org.exist.dom.QName) IOException(java.io.IOException) AtomicValue(org.exist.xquery.value.AtomicValue) StringValue(org.exist.xquery.value.StringValue) Value(org.exist.storage.btree.Value) Collection(org.exist.collections.Collection)

Example 15 with StringValue

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

the class FunTokenize method eval.

@Override
public Sequence eval(final Sequence contextSequence, final 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());
        }
    }
    final Sequence result;
    final Sequence stringArg = getArgument(0).eval(contextSequence, contextItem);
    if (stringArg.isEmpty()) {
        result = Sequence.EMPTY_SEQUENCE;
    } else {
        String string = stringArg.getStringValue();
        if (string.isEmpty()) {
            result = Sequence.EMPTY_SEQUENCE;
        } else {
            final int flags;
            if (getSignature().getArgumentCount() == 3) {
                flags = parseFlags(this, getArgument(2).eval(contextSequence, contextItem).getStringValue());
            } else {
                flags = 0;
            }
            final String pattern;
            if (getArgumentCount() == 1) {
                pattern = " ";
                string = FunNormalizeSpace.normalize(string);
            } else {
                if (hasLiteral(flags)) {
                    // no need to change anything
                    pattern = getArgument(1).eval(contextSequence, contextItem).getStringValue();
                } else {
                    final boolean ignoreWhitespace = hasIgnoreWhitespace(flags);
                    final boolean caseBlind = hasCaseInsensitive(flags);
                    pattern = translateRegexp(this, getArgument(1).eval(contextSequence, contextItem).getStringValue(), ignoreWhitespace, caseBlind);
                }
            }
            try {
                if (pat == null || (!pattern.equals(pat.pattern())) || flags != pat.flags()) {
                    pat = PatternFactory.getInstance().getPattern(pattern, flags);
                }
                if (pat.matcher("").matches()) {
                    throw new XPathException(this, ErrorCodes.FORX0003, "regular expression could match empty string");
                }
                final String[] tokens = pat.split(string, -1);
                result = new ValueSequence();
                for (final String token : tokens) {
                    result.add(new StringValue(token));
                }
            } catch (final PatternSyntaxException e) {
                throw new XPathException(this, ErrorCodes.FORX0001, "Invalid regular expression: " + e.getMessage(), new StringValue(pattern), e);
            }
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : XPathException(org.exist.xquery.XPathException) ValueSequence(org.exist.xquery.value.ValueSequence) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) StringValue(org.exist.xquery.value.StringValue) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

StringValue (org.exist.xquery.value.StringValue)96 Sequence (org.exist.xquery.value.Sequence)49 XPathException (org.exist.xquery.XPathException)40 ValueSequence (org.exist.xquery.value.ValueSequence)27 IOException (java.io.IOException)11 PermissionDeniedException (org.exist.security.PermissionDeniedException)10 Item (org.exist.xquery.value.Item)10 XQueryContext (org.exist.xquery.XQueryContext)8 Txn (org.exist.storage.txn.Txn)7 AnyURIValue (org.exist.xquery.value.AnyURIValue)7 QName (org.exist.dom.QName)6 LockException (org.exist.util.LockException)6 NodeValue (org.exist.xquery.value.NodeValue)6 Path (java.nio.file.Path)5 EXistException (org.exist.EXistException)5 TriggerException (org.exist.collections.triggers.TriggerException)5 DocumentImpl (org.exist.dom.persistent.DocumentImpl)5 StoredNode (org.exist.dom.persistent.StoredNode)5 NotificationService (org.exist.storage.NotificationService)5 MimeType (org.exist.util.MimeType)5