summaryrefslogtreecommitdiff
path: root/qpid/cpp/src/qpid/xml/XmlExchange.cpp
blob: b7ff5d211de5f0a4a83a11b530bbb9c7ec74ace2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

#include "config.h"

#include "qpid/xml/XmlExchange.h"

#include "qpid/broker/DeliverableMessage.h"

#include "qpid/log/Statement.h"
#include "qpid/broker/FedOps.h"
#include "qpid/framing/FieldTable.h"
#include "qpid/framing/FieldValue.h"
#include "qpid/framing/reply_exceptions.h"

#include "qpid/Plugin.h"

#include <xercesc/framework/MemBufInputSource.hpp>

#ifdef XQ_EFFECTIVE_BOOLEAN_VALUE_HPP
#include <xqilla/ast/XQEffectiveBooleanValue.hpp>
#endif

#include <xqilla/ast/XQGlobalVariable.hpp>

#include <xqilla/context/ItemFactory.hpp>
#include <xqilla/xqilla-simple.hpp>

#include <boost/bind.hpp>
#include <functional>
#include <algorithm>
#include <iostream>
#include <sstream>

using namespace qpid::framing;
using namespace qpid::sys;
using qpid::management::Manageable;
namespace _qmf = qmf::org::apache::qpid::broker;

namespace qpid {
namespace broker {            
    
XQilla XmlBinding::xqilla;

XmlBinding::XmlBinding(const std::string& key, const Queue::shared_ptr queue, const std::string& _fedOrigin, Exchange* parent, 
                                    const ::qpid::framing::FieldTable& _arguments, const std::string& queryText )
    :      Binding(key, queue, parent, _arguments),
           xquery(),
           parse_message_content(true),
           fedOrigin(_fedOrigin)
{ 
    startManagement();

    QPID_LOG(trace, "Creating binding with query: " << queryText );

    try {  
        Query q(xqilla.parse(X(queryText.c_str())));
        xquery = q;
        
        QPID_LOG(trace, "Bound successfully with query: " << queryText );

        parse_message_content = false;

        if (xquery->getQueryBody()->getStaticAnalysis().areContextFlagsUsed()) {
            parse_message_content = true;
        }
        else {
            GlobalVariables &vars = const_cast<GlobalVariables&>(xquery->getVariables());
            for (GlobalVariables::iterator it = vars.begin(); it != vars.end(); ++it) {
                if ((*it)->getStaticAnalysis().areContextFlagsUsed()) {
                    parse_message_content = true;
                    break;
                } 
            }
        }
    }
    catch (XQException& e) {
        throw InternalErrorException(QPID_MSG("Could not parse xquery:"+ queryText));
    }
    catch (...) {
        throw InternalErrorException(QPID_MSG("Unexpected error - Could not parse xquery:"+ queryText));
    }    
}

     
XmlExchange::XmlExchange(const string& _name, Manageable* _parent, Broker* b) : Exchange(_name, _parent, b)
{
    if (mgmtExchange != 0)
        mgmtExchange->set_type (typeName);
}

XmlExchange::XmlExchange(const std::string& _name, bool _durable,
                         const FieldTable& _args, Manageable* _parent, Broker* b) :
    Exchange(_name, _durable, _args, _parent, b)
{
    if (mgmtExchange != 0)
        mgmtExchange->set_type (typeName);
}
    
bool XmlExchange::bind(Queue::shared_ptr queue, const string& bindingKey, const FieldTable* args)
{ 

    // Federation uses bind for unbind and reorigin comands as well as for binds.
    //
    // Both federated and local binds are done in this method.  Other
    // federated requests are done by calling the relevent methods.

    string fedOp;
    string fedTags;
    string fedOrigin;
    
    if (args) 
        fedOp = args->getAsString(qpidFedOp);
    if (! fedOp.empty())  {
        fedTags =  args->getAsString(qpidFedTags);
        fedOrigin = args->getAsString(qpidFedOrigin);
    }

    if (fedOp == fedOpUnbind) {
        return fedUnbind(fedOrigin, fedTags, queue, bindingKey, args);
    }
    else if (fedOp == fedOpReorigin) {
        fedReorigin();
        return true;
    }

    // OK, looks like we're really going to bind
    
    else if (fedOp.empty() || fedOp == fedOpBind) {

        string queryText = args->getAsString("xquery");

        RWlock::ScopedWlock l(lock);   
 
        XmlBinding::vector& bindings(bindingsMap[bindingKey]);
        XmlBinding::vector::ConstPtr p = bindings.snapshot();
       
        if (!p || std::find_if(p->begin(), p->end(), MatchQueueAndOrigin(queue, fedOrigin)) == p->end()) {

            XmlBinding::shared_ptr binding(new XmlBinding (bindingKey, queue, fedOrigin, this, *args, queryText));
            bindings.add(binding);

            if (mgmtExchange != 0) {
                mgmtExchange->inc_bindingCount();
            }
        } else {
            return false;
        }
    }
    else {
        QPID_LOG(warning, "Unknown Federation Op: " << fedOp);
    }
 
    routeIVE();
    propagateFedOp(bindingKey, fedTags, fedOp, fedOrigin, args);

    return true;
}

bool XmlExchange::unbind(Queue::shared_ptr queue, const string& bindingKey, const FieldTable* args)
{
    /*
     *  When called directly, no qpidFedOrigin argument will be
     *  present. When called from federation, it will be present. 
     *
     *  This is a bit of a hack - the binding needs the origin, but
     *  this interface, as originally defined, would not supply one.
     */
    string fedOrigin;
    if (args) fedOrigin = args->getAsString(qpidFedOrigin);

    RWlock::ScopedWlock l(lock);
    if (bindingsMap[bindingKey].remove_if(MatchQueueAndOrigin(queue, fedOrigin))) {
        if (mgmtExchange != 0) {
            mgmtExchange->dec_bindingCount();
        }
        return true;
    } else {
        return false;      
    }
}

bool XmlExchange::matches(Query& query, Deliverable& msg, const qpid::framing::FieldTable* args, bool parse_message_content) 
{
    string msgContent;

    try {
        QPID_LOG(trace, "matches: query is [" << UTF8(query->getQueryText()) << "]");

        boost::scoped_ptr<DynamicContext> context(query->createDynamicContext());
        if (!context.get()) {
            throw InternalErrorException(QPID_MSG("Query context looks munged ..."));
        }

        if (parse_message_content) {

            msg.getMessage().getFrames().getContent(msgContent);

            QPID_LOG(trace, "matches: message content is [" << msgContent << "]");

            XERCES_CPP_NAMESPACE::MemBufInputSource xml((const XMLByte*) msgContent.c_str(), 
                                                        msgContent.length(), "input" );

            // This will parse the document using either Xerces or FastXDM, depending
            // on your XQilla configuration. FastXDM can be as much as 10x faster.

            Sequence seq(context->parseDocument(xml));

            if(!seq.isEmpty() && seq.first()->isNode()) {
                context->setContextItem(seq.first());
                context->setContextPosition(1);
                context->setContextSize(1);
            }
        }

        if (args) {
            FieldTable::ValueMap::const_iterator v = args->begin();
            for(; v != args->end(); ++v) {

                if (v->second->convertsTo<double>()) {
                    QPID_LOG(trace, "XmlExchange, external variable (double): " << v->first << " = " << v->second->get<double>());
                    Item::Ptr value = context->getItemFactory()->createDouble(v->second->get<double>(), context.get());
                    context->setExternalVariable(X(v->first.c_str()), value);
                }              
                else if (v->second->convertsTo<int>()) {
                    QPID_LOG(trace, "XmlExchange, external variable (int):" << v->first << " = " << v->second->getData().getInt());
                    Item::Ptr value = context->getItemFactory()->createInteger(v->second->get<int>(), context.get());
                    context->setExternalVariable(X(v->first.c_str()), value);
                }
                else if (v->second->convertsTo<std::string>()) {
                    QPID_LOG(trace, "XmlExchange, external variable (string):" << v->first << " = " << v->second->getData().getString().c_str());
                    Item::Ptr value = context->getItemFactory()->createString(X(v->second->get<std::string>().c_str()), context.get());
                    context->setExternalVariable(X(v->first.c_str()), value);
                }

            }
        }

        Result result = query->execute(context.get());
#ifdef XQ_EFFECTIVE_BOOLEAN_VALUE_HPP
        Item::Ptr first_ = result->next(context.get());
        Item::Ptr second_ = result->next(context.get());
        return XQEffectiveBooleanValue::get(first_, second_, context.get(), 0);
#else 
        return result->getEffectiveBooleanValue(context.get(), 0);
#endif
    }
    catch (XQException& e) {
        QPID_LOG(warning, "Could not parse XML content (or message headers):" << msgContent);
    }
    catch (...) {
        QPID_LOG(warning, "Unexpected error routing message: " << msgContent);
    }
    return 0;
}

// Future optimization: If any query in a binding for a given routing key requires
// message content, parse the message once, and use that parsed form for all bindings.
//
// Future optimization: XQilla does not currently do document projection for data
// accessed via the context item. If there is a single query for a given routing key,
// and it accesses document data, this could be a big win.
//
// Document projection often is not a win if you have multiple queries on the same data.
// But for very large messages, if all these queries are on the first part of the data,
// it could still be a big win.

void XmlExchange::route(Deliverable& msg, const string& routingKey, const FieldTable* args)
{
    PreRoute pr(msg, this);
    try {
        XmlBinding::vector::ConstPtr p;
        BindingList b(new std::vector<boost::shared_ptr<qpid::broker::Exchange::Binding> >);
        {
            RWlock::ScopedRlock l(lock);
            p = bindingsMap[routingKey].snapshot();
            if (!p.get()) return;
        }

        for (std::vector<XmlBinding::shared_ptr>::const_iterator i = p->begin(); i != p->end(); i++) {
            if (matches((*i)->xquery, msg, args, (*i)->parse_message_content)) { 
                b->push_back(*i);
            }
        }
        doRoute(msg, b);
    } catch (...) {
        QPID_LOG(warning, "XMLExchange " << getName() << ": exception routing message with query " << routingKey);
    }
}


bool XmlExchange::isBound(Queue::shared_ptr queue, const string* const bindingKey, const FieldTable* const) 
{
    RWlock::ScopedRlock l(lock);
    if (bindingKey) {
        XmlBindingsMap::iterator i = bindingsMap.find(*bindingKey);

        if (i == bindingsMap.end())
            return false;
        if (!queue)
            return true;
        XmlBinding::vector::ConstPtr p = i->second.snapshot();
        return p && std::find_if(p->begin(), p->end(), MatchQueue(queue)) != p->end();
    } else if (!queue) {
        //if no queue or routing key is specified, just report whether any bindings exist
        return bindingsMap.size() > 0;
    } else {
        for (XmlBindingsMap::iterator i = bindingsMap.begin(); i != bindingsMap.end(); i++) {
            XmlBinding::vector::ConstPtr p = i->second.snapshot();
            if (p && std::find_if(p->begin(), p->end(), MatchQueue(queue)) != p->end()) return true;
        }
        return false;
    }

}

XmlExchange::~XmlExchange() 
{
    bindingsMap.clear();
}

void XmlExchange::propagateFedOp(const std::string& bindingKey, const std::string& fedTags, const std::string& fedOp, const std::string& fedOrigin, const qpid::framing::FieldTable* args)
{
    FieldTable nonFedArgs;

    if (args) {            
        for (qpid::framing::FieldTable::ValueMap::const_iterator i=args->begin(); i != args->end(); ++i)  {
            const string& name(i->first);
            if (name != qpidFedOp &&
                name != qpidFedTags &&
                name != qpidFedOrigin)  {
                nonFedArgs.insert((*i));
            }
        }
    }

    FieldTable* propArgs  = (nonFedArgs.count() > 0 ? &nonFedArgs : 0);
    Exchange::propagateFedOp(bindingKey, fedTags, fedOp, fedOrigin, propArgs);
}

bool XmlExchange::fedUnbind(const string& fedOrigin, const string& fedTags, Queue::shared_ptr queue, const string& bindingKey, const FieldTable* args)
{
    RWlock::ScopedRlock l(lock);

    if (unbind(queue, bindingKey, args)) {
        propagateFedOp(bindingKey, fedTags, fedOpUnbind, fedOrigin); 
        return true;
    }
    return false;
}

void XmlExchange::fedReorigin()
{
    std::vector<std::string> keys2prop;
    {
        RWlock::ScopedRlock l(lock);   
        for (XmlBindingsMap::iterator i = bindingsMap.begin(); i != bindingsMap.end(); ++i) {
            XmlBinding::vector::ConstPtr p = i->second.snapshot();
            if (std::find_if(p->begin(), p->end(), MatchOrigin(string())) != p->end()) {
                keys2prop.push_back(i->first);
            }
        }
    }   /* lock dropped */
    for (std::vector<std::string>::const_iterator key = keys2prop.begin();
         key != keys2prop.end(); key++) {
        propagateFedOp( *key, string(), fedOpBind, string());
    }
}


XmlExchange::MatchOrigin::MatchOrigin(const string& _origin) : origin(_origin) {}

bool XmlExchange::MatchOrigin::operator()(XmlBinding::shared_ptr b)
{
    return b->fedOrigin == origin;
}


XmlExchange::MatchQueueAndOrigin::MatchQueueAndOrigin(Queue::shared_ptr _queue, const string& _origin) : queue(_queue), origin(_origin) {}

bool XmlExchange::MatchQueueAndOrigin::operator()(XmlBinding::shared_ptr b)
{
    return b->queue == queue and b->fedOrigin == origin;
}


const std::string XmlExchange::typeName("xml");
 
}
}