Package org.exist.xquery

Examples of org.exist.xquery.XQueryContext$CleanupTask


        DBBroker broker = null;
        DocumentImpl resource = null;
        Source source = null;
        XQueryPool xqPool  = null;
        CompiledXQuery compiled = null;
        XQueryContext context = null;

        try {

            //get the xquery
            broker = pool.get(user);

            if(xqueryresource.indexOf(':') > 0) {
                source = SourceFactory.getSource(broker, "", xqueryresource, true);
            } else {
                final XmldbURI pathUri = XmldbURI.create(xqueryresource);
                resource = broker.getXMLResource(pathUri, Lock.READ_LOCK);

                if(resource != null) {
                    source = new DBSource(broker, (BinaryDocument)resource, true);
                }
            }

            if(source != null) {

                //execute the xquery
                final XQuery xquery = broker.getXQueryService();
                xqPool = xquery.getXQueryPool();

                //try and get a pre-compiled query from the pool
                compiled = xqPool.borrowCompiledXQuery(broker, source);

                if(compiled == null) {
                    context = xquery.newContext(AccessContext.REST); //TODO should probably have its own AccessContext.SCHEDULER
                } else {
                    context = compiled.getContext();
                }

                //TODO: don't hardcode this?
                if(resource != null) {
                    context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(resource.getCollection().getURI()).toString());
                    context.setStaticallyKnownDocuments(new XmldbURI[] {
                        resource.getCollection().getURI()
                    });
                }

                if(compiled == null) {

                    try {
                        compiled = xquery.compile(context, source);
                    }
                    catch(final IOException e) {
                        abort("Failed to read query from " + xqueryresource);
                    }
                }

                //declare any parameters as external variables
                if(params != null) {
                    String bindingPrefix = params.getProperty("bindingPrefix");

                    if(bindingPrefix == null) {
                        bindingPrefix = "local";
                    }
                   

                    for(final Entry param : params.entrySet()) {
                        final String key = (String)param.getKey();
                        final String value = (String)param.getValue();
                        context.declareVariable( bindingPrefix + ":" + key, new StringValue(value));
                    }
                }

                xquery.execute(compiled, null);

            } else {
                LOG.warn("XQuery User Job not found: " + xqueryresource + ", job not scheduled");
            }
        } catch(final EXistException ee) {
            abort("Could not get DBBroker!");
        } catch(final PermissionDeniedException pde) {
            abort("Permission denied for the scheduling user: " + user.getName() + "!");
        } catch(final XPathException xpe) {
            abort("XPathException in the Job: " + xpe.getMessage() + "!", unschedule);
        } catch(final MalformedURLException e) {
            abort("Could not load XQuery: " + e.getMessage());
        } catch(final IOException e) {
            abort("Could not load XQuery: " + e.getMessage());
        } finally {

            if(context != null) {
                context.runCleanupTasks();
            }
           
            //return the compiled query to the pool
            if(xqPool != null && source != null && compiled != null) {
                xqPool.returnCompiledXQuery(source, compiled);
View Full Code Here


            final Source source = getQuerySource(broker, scriptURI, script);
            if(source == null) {return;}

            final XQuery xquery = broker.getXQueryService();
            final XQueryContext context = xquery.newContext(AccessContext.XMLDB);

            final CompiledXQuery compiled = xquery.compile(context, source);

//            Sequence result = xquery.execute(compiled, subject.getName());

        final ProcessMonitor pm = db.getProcessMonitor();

            //execute the XQuery
            try {
            final UserDefinedFunction function = context.resolveFunction(functionName, 0);
            if (function != null) {
                  context.getProfiler().traceQueryStart();
                  pm.queryStarted(context.getWatchDog());
                 
                  final FunctionCall call = new FunctionCall(context, function);
                  if (args != null)
                    {call.setArguments(args);}
                  call.analyze(new AnalyzeContextInfo());
              call.eval(NodeSet.EMPTY_SET);
            }
            } catch(final XPathException e) {
              //XXX: log
              e.printStackTrace();
            } finally {
              if (pm != null) {
                context.getProfiler().traceQueryEnd(context);
                pm.queryCompleted(context.getWatchDog());
              }
              compiled.reset();
            context.reset();
            }
           
        } catch (final Exception e) {
          //XXX: log
          e.printStackTrace();
View Full Code Here

        Set<String> extectedError = new HashSet<String>();
        try {
            broker = db.get(db.getSecurityManager().getSystemSubject());
            xquery = broker.getXQueryService();

            final XQueryContext context = new XQueryContext(db, AccessContext.TEST);

            broker.getConfiguration().setProperty(XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true);

            String query = "declare namespace qt='" + QT_NS + "';\n" + "let $testCases := xmldb:document('/db/QT3/" + file + "')\n"
                    + "let $tc := $testCases//qt:test-case[@name eq \"" + tcName + "\"]\n" + "return $tc";

            XQuery xqs = broker.getXQueryService();

            Sequence results = xqs.execute(query, null, AccessContext.TEST);

            Assert.assertFalse("", results.isEmpty());

            ElementImpl TC = (ElementImpl) results.toNodeSet().get(0).getNode();

            Sequence contextSequence = null;

            NodeList expected = null;
            String nodeName = "";

            // compile & evaluate
            String caseScript = null;

            List<String> staticDocs = new ArrayList<String>();
            NodeList childNodes = TC.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node child = childNodes.item(i);
                switch (child.getNodeType()) {
                case Node.ATTRIBUTE_NODE:
                    // String name = ((Attr)child).getName();
                    // if (name.equals("scenario"))
                    // scenario = ((Attr)child).getValue();
                    break;
                case Node.ELEMENT_NODE:
                    nodeName = ((ElementImpl) child).getLocalName();
                    if (nodeName.equals("test")) {
                        ElementImpl el = ((ElementImpl) child);
                        caseScript = el.getNodeValue();

                    } else if (nodeName.equals("environment")) {
                        ElementImpl el = ((ElementImpl) child);

                        String ref = el.getAttribute("ref");
                        if (!(ref == null || "empty".equals(ref) || ref.isEmpty())) {
                            Assert.assertNull(contextSequence);
                            String contextDoc = getEnviroment(file, ref);
                            staticDocs.add(contextDoc);
                        } else {
                            NodeList _childNodes = el.getChildNodes();
                            for (int j = 0; j < _childNodes.getLength(); j++) {
                                Node _child = _childNodes.item(j);
                                switch (_child.getNodeType()) {
                                case Node.ELEMENT_NODE:
                                    nodeName = ((ElementImpl) _child).getLocalName();
                                    if (nodeName.equals("param")) {
                                        el = ((ElementImpl) _child);
                                        Variable var = new VariableImpl(QName.parse(context, el.getAttribute("name")));

                                        String type = el.getAttribute("as");
                                        if ("xs:date".equals(type)) {
                                            var.setStaticType(Type.DATE);

                                            Sequence res = xquery.execute(el.getAttribute("select"), null, AccessContext.TEST);
                                            Assert.assertEquals(1, res.getItemCount());
                                            var.setValue(res);
                                        } else if ("xs:dateTime".equals(type)) {
                                            var.setStaticType(Type.DATE_TIME);

                                            Sequence res = xquery.execute(el.getAttribute("select"), null, AccessContext.TEST);
                                            Assert.assertEquals(1, res.getItemCount());
                                            var.setValue(res);
                                        } else if ("xs:string".equals(type)) {
                                            var.setStaticType(Type.STRING);

                                            Sequence res = xquery.execute(el.getAttribute("select"), null, AccessContext.TEST);
                                            Assert.assertEquals(1, res.getItemCount());
                                            var.setValue(res);
                                        } else {
                                            Assert.fail("unknown type '" + type + "'");
                                        }
                                        context.declareGlobalVariable(var);
                                    }
                                }
                            }
                        }

                    } else if (nodeName.equals("result")) {
                        ElementImpl el = ((ElementImpl) child);

                        possibleErrors(el, extectedError);

                        NodeList anyOf = el.getElementsByTagNameNS(QT_NS, "any-of");
                        for (int j = 0; j < anyOf.getLength(); j++) {
                            el = (ElementImpl) anyOf.item(j);
                            possibleErrors(el, extectedError);
                        }

                        expected = el.getChildNodes();
                    }
                    break;
                default:
                    ;
                }
            }

            if (staticDocs.size() > 0) {
                XmldbURI contextDocs[] = new XmldbURI[staticDocs.size()];
                int i = 0;
                for (String path : staticDocs) {
                    contextDocs[i++] = XmldbURI.createInternal(path);
                }
                context.setStaticallyKnownDocuments(contextDocs);
            }
            final CompiledXQuery compiled = xquery.compile(context, xquery3declaration + caseScript);
            result = xquery.execute(compiled, contextSequence);

            for (int i = 0; i < expected.getLength(); i++) {
View Full Code Here

            Sequence result = null;

            //compile & evaluate
            File caseScript = new File(XQTS_folder+"Queries/XQuery/"+folder, script+".xq");
            try {
                XQueryContext context;

                context = xquery.newContext(AccessContext.TEST);

                //map modules' namespaces to location
                Map<String, String> moduleMap = (Map<String, String>)broker.getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP);
                for (int i = 0; i < modules.getLength(); i++) {
                    ElementImpl module = (ElementImpl)modules.item(i);
                    String id = module.getNodeValue();
                    moduleMap.put(module.getAttribute("namespace"), moduleSources.get(id));
                }
                broker.getConfiguration().setProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP, moduleMap);

                //declare variable
                for (int i = 0; i < inputFiles.getLength(); i++) {
                    ElementImpl inputFile = (ElementImpl)inputFiles.item(i);
                    String id = inputFile.getNodeValue();

                    //use DocUtils
                    //context.declareVariable(
                        //inputFile.getAttribute("variable"),
                        //DocUtils.getDocument(context, sources.get(id))
                    //);

                    //in-memory nodes
                    context.declareVariable(inputFile.getAttribute("variable"), loadVarFromURI(context, sources.get(id)));
                }

                Sequence contextSequence = null;
                //set context item
                if (contextItem != null) {
View Full Code Here

        try {
          broker = getPool().get(user);
            final XQuery xquery = broker.getXQueryService();
            CompiledXQuery query = xquery.getXQueryPool().borrowCompiledXQuery(broker, source);

            XQueryContext context;
            if (query==null) {
               context = xquery.newContext(AccessContext.REST);
               context.setModuleLoadPath(moduleLoadPath);
               try {
                 query = xquery.compile(context, source);
                  
               } catch (final XPathException ex) {
                  throw new EXistException("Cannot compile xquery: "+ ex.getMessage(), ex);
                 
               } catch (final IOException ex) {
                  throw new EXistException("I/O exception while compiling xquery: " + ex.getMessage() ,ex);
               }
              
            } else {
               context = query.getContext();
               context.setModuleLoadPath(moduleLoadPath);
            }

            final Properties outputProperties = new Properties();
            outputProperties.put("base-uri", collectionURI.toString());
           
            context.declareVariable(RequestModule.PREFIX + ":request", new HttpRequestWrapper(request, getFormEncoding(), getContainerEncoding()));
            context.declareVariable(ResponseModule.PREFIX + ":response", new HttpResponseWrapper(response));
            context.declareVariable(SessionModule.PREFIX + ":session", ( session != null ? new HttpSessionWrapper( session ) : null ) );

            final String timeoutOpt = (String) request.getAttribute(ATTR_TIMEOUT);
            if (timeoutOpt != null) {
                try {
                    final long timeout = Long.parseLong(timeoutOpt);
                    context.getWatchDog().setTimeout(timeout);
                } catch (final NumberFormatException e) {
                    throw new EXistException("Bad timeout option: " + timeoutOpt);
                }
            }

            final String maxNodesOpt = (String) request.getAttribute(ATTR_MAX_NODES);
            if (maxNodesOpt != null) {
                try{
                    final int maxNodes = Integer.parseInt(maxNodesOpt);
                    context.getWatchDog().setMaxNodes(maxNodes);
                } catch (final NumberFormatException e) {
                    throw new EXistException("Bad max-nodes option: " + maxNodesOpt);
                }
            }

            DebuggeeFactory.checkForDebugRequest(request, context);

            Sequence resultSequence;
            try {
                resultSequence = xquery.execute(query, null, outputProperties);
               
            } finally {
                context.runCleanupTasks();
                xquery.getXQueryPool().returnCompiledXQuery(source, query);
            }

            final String mediaType = outputProperties.getProperty(OutputKeys.MEDIA_TYPE);
            if (mediaType != null) {
View Full Code Here

        DBBroker broker = null;
        try {
//            xpath = StringValue.expand(xpath);
            LOG.debug("query: " + xpath);
            broker = pool.get(session.getUser());
            final XQueryContext context = new XQueryContext(pool, AccessContext.SOAP);
            context.setXacmlSource(XACMLSource.getInstance(xpath));
           
            session.registerContext(context);
           
            // TODO(pkaminsk2): why replicate XQuery.compile here?
           
            final XQueryLexer lexer = new XQueryLexer(context, new StringReader(xpath));
            final XQueryParser parser = new XQueryParser(lexer);
            final XQueryTreeParser treeParser = new XQueryTreeParser(context);
            parser.xpath();
            if (parser.foundErrors()) {
                LOG.debug(parser.getErrorMessage());
                throw new RemoteException(parser.getErrorMessage());
            }
           
            final AST ast = parser.getAST();
           
            final PathExpr expr = new PathExpr(context);
            treeParser.xpath(ast, expr);
            if (treeParser.foundErrors()) {
                LOG.debug(treeParser.getErrorMessage());
                throw new EXistException(treeParser.getErrorMessage());
            }
            LOG.info("query: " + ExpressionDumper.dump(expr));
            final long start = System.currentTimeMillis();
            expr.analyze(new AnalyzeContextInfo());
            final Sequence seq= expr.eval(null, null);
           
            QueryResponseCollection[] collections = null;
            if (!seq.isEmpty() && Type.subTypeOf(seq.getItemType(), Type.NODE))
                {collections = collectQueryInfo(scanResults(seq));}
            session.addQueryResult(seq);
            resp.setCollections(new QueryResponseCollections(collections));
            resp.setHits(seq.getItemCount());
            resp.setQueryTime(System.currentTimeMillis() - start);
            expr.reset();
            context.reset();
        } catch (final Exception e) {
            LOG.debug(e.getMessage(), e);
            throw new RemoteException("query execution failed: " + e.getMessage());
        } finally {
            pool.release(broker);
View Full Code Here

    public File[] generate(DBBroker broker, Collection collection, String xqueryContent) throws SAXException {
        try {
            DocumentSet docs = collection.allDocs(broker, new DefaultDocumentSet(), true);
            XQuery service = broker.getXQueryService();
            XQueryContext context = service.newContext(AccessContext.TEST);
            context.declareVariable("filename", "");
            context.declareVariable("count", "0");
            context.setStaticallyKnownDocuments(docs);

            String query = IMPORT + xqueryContent;
            System.out.println("query: " + query);

            CompiledXQuery compiled = service.compile(context, query);

            for (int i = 0; i < count; i++) {
                generatedFiles[i] = File.createTempFile(prefix, ".xml");

                context.declareVariable("filename", generatedFiles[i].getName());
                context.declareVariable("count", new Integer(i));
                Sequence results = service.execute(compiled, Sequence.EMPTY_SEQUENCE);

                Serializer serializer = broker.getSerializer();
                serializer.reset();
                Writer out = new OutputStreamWriter(new FileOutputStream(generatedFiles[i]), "UTF-8");
View Full Code Here

          db = BrokerPool.getInstance();
          broker = db.get(db.getSecurityManager().getGuestSubject());
         
          XQuery xquery = broker.getXQueryService();
         
          XQueryContext context = xquery.newContext(AccessContext.TEST);
          //context.setModuleLoadPath();
         
            Source query = new ClassLoaderSource(source);
           
            CompiledXQuery compiledQuery = xquery.compile(context, query);
           
      for(Iterator<UserDefinedFunction> i = context.localFunctions(); i.hasNext(); ) {
        UserDefinedFunction func = i.next();
        FunctionSignature sig = func.getSignature();
       
        for (Annotation ann : sig.getAnnotations()) {
          if ("http://exist-db.org/xquery/xUnit".equals( ann.getName().getNamespaceURI())) {
View Full Code Here

            if (xquery == null) {
                LOG.error("broker unable to retrieve XQueryService");
                return false;
            }

            XQueryContext context = xquery.newContext(AccessContext.REST);

            CompiledXQuery compiled = xquery.compile(context, source);

            Properties outputProperties = new Properties();
View Full Code Here

            assertNotNull(broker);

            XQuery xquery = broker.getXQueryService();
            assertNotNull(xquery);

            XQueryContext context = new XQueryContext(broker.getBrokerPool(), AccessContext.TEST);
            CompiledXQuery compiled = xquery.compile(context, "declare variable $q external; " +
                    "ft:query(//p, util:parse($q)/query)");

            context.declareVariable("q", "<query><term>heiterkeit</term></query>");
            Sequence seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <term>heiterkeit</term><term>blablabla</term>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <term occur='should'>heiterkeit</term><term occur='should'>blablabla</term>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <term occur='must'>heiterkeit</term><term occur='must'>blablabla</term>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(0, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <term occur='must'>heiterkeit</term><term occur='not'>herzen</term>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(0, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <phrase occur='must'>wunderbare heiterkeit</phrase><term occur='must'>herzen</term>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                    "<query>" +
                    "   <phrase slop='5'>heiterkeit seele eingenommen</phrase>" +
                    "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            // phrase with wildcards
            context.declareVariable("q",
                "<query>" +
                "   <phrase slop='5'><term>heiter*</term><term>se?nnnle*</term></phrase>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <wildcard>?eiter*</wildcard>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <fuzzy max-edits='2'>selee</fuzzy>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <bool>" +
                "       <fuzzy occur='must' max-edits='2'>selee</fuzzy>" +
                "       <wildcard occur='should'>bla*</wildcard>" +
                "   </bool>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <regex>heit.*keit</regex>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
            assertEquals(1, seq.getItemCount());

            context.declareVariable("q",
                "<query>" +
                "   <phrase><term>wunderbare</term><regex>heit.*keit</regex></phrase>" +
                "</query>");
            seq = xquery.execute(compiled, null);
            assertNotNull(seq);
View Full Code Here

TOP

Related Classes of org.exist.xquery.XQueryContext$CleanupTask

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.