Beispiel #1
0
function doCoordinateXPathReplacer(replacer, requestDoc, savedRequestDoc, responseDoc) {
	logger.debug("CoordinateXPathReplacer: " + replacer.source + " -> " + replacer.destination);
	var requestSelect = xpath.useNamespaces(replacer.sourceNamespaces);
	var responseSelect = xpath.useNamespaces(replacer.destinationNamespaces);
	var requestNodes = requestSelect(replacer.source, requestDoc);
	var savedRequestNodes = requestSelect(replacer.source, savedRequestDoc);
	var responseNodes = responseSelect(replacer.destination, responseDoc);

	if (requestNodes.length > 0 && responseNodes.length > 0) {
		responseNodes.forEach(function(responseNode, i) {
			responseNode.value = "" + (parseFloat(responseNode.value) + parseFloat(requestNodes[0].value) - parseFloat(savedRequestNodes[0].value));
		});
	}
	return responseDoc;
}
Beispiel #2
0
function selectXPath (config, caseTransform, encoding, text) {
    var doc = new DOMParser().parseFromString(text),
        select = xpath.useNamespaces(config.ns || {}),
        selector = caseTransform(config.selector),
        result = xpathSelect(select, selector, doc, encoding),
        nodeValues;

    if (['number', 'boolean'].indexOf(typeof result) >= 0) {
        return result;
    }

    nodeValues = result.map(nodeValue);

    // Return either a string if one match or array if multiple
    // This matches the behavior of node's handling of query parameters,
    // which allows us to maintain the same semantics between deepEquals
    // (all have to match, passing in an array if necessary) and the other
    // predicates (any can match)
    if (nodeValues.length === 0) {
        return undefined;
    }
    else if (nodeValues.length === 1) {
        return nodeValues[0];
    }
    else {
        // array can match in any order
        return nodeValues.sort();
    }
}
.then(function(data) {
    var p = promise.Promise();
    
    var doc = new dom().parseFromString(data);
    var select = xpath.useNamespaces({"t": "http://schemas.microsoft.com/exchange/services/2006/types"});
    var nodes = select("//t:CalendarItem", doc);

    items = nodes.map(function(item) {
				return {
					itemId: select('./t:ItemId', item)[0].getAttribute('Id'),
					changeKey: select('./t:ItemId', item)[0].getAttribute('ChangeKey'),
					type: firstData(select, './t:CalendarItemType', item),
					subject: firstData(select, './t:Subject', item),
					location: firstData(select, './t:Location', item),
					start: firstData(select, './t:Start', item),
					end: firstData(select, './t:End', item),
					allDay: firstData(select, './t:IsAllDayEvent', item) == 'true' ? true : false,
					body: firstData(select, './t:Body', item),
					organizer: person(select, './t:Organizer', item)[0],
					requiredAttendees: person(select, './t:RequiredAttendees/t:Attendee', item),
					optionalAttendees: person(select, './t:OptionalAttendees/t:Attendee', item)
				};
    });
   
    return items;
})
module.exports = function(content) {
	this.cacheable && this.cacheable();

	var content = content.toString('utf8');

	var markup = "";
	markup = "icons['test'] = 'test123'; ";

	// parse content of doc
	var svgDoc = new xmldom.DOMParser().parseFromString(content, "text/xml");
	var svgEl = svgDoc.documentElement;

	// find all the symbols in the svg doc
	var select = xpath.useNamespaces({"svg": "http://www.w3.org/2000/svg"});
	var nodes = select('//svg:symbol', svgDoc);
	for (var i = 0; i < nodes.length; i++) {
		var node = nodes[i];
		var nodeContent = new xmldom.XMLSerializer().serializeToString(node.childNodes);
		nodeContent = '<svg viewBox="'+node.getAttribute('viewBox')+'" xmlns="http://www.w3.org/2000/svg"><g>' + nodeContent.trim() + '</g></svg>';

      // this fails when there is whitespace between elements, need a fix!
		markup = markup + "icons['"+node.getAttribute('id')+"'] = '"+nodeContent+"'; ";
	}

	var functionStart = "module.exports = function(iconId) { var icons = []; ";
	var functionEnd = "return icons[iconId]; }";

	return functionStart + markup + functionEnd;
}
Beispiel #5
0
	query: function query(node, expression, resolver) {
		var XPath = require("xpath");

		var evaluate = !!resolver && (typeof resolver == "object") ? XPath.useNamespaces(resolver) : XPath.select;

		return evaluate(expression, node);
	}
function WadlParser(options) {
    this.options = options;

    this.parser = new xmldom.DOMParser();
    this.select = xpath.useNamespaces({
        'ns': 'http://wadl.dev.java.net/2009/02',
        'xs': 'http://www.w3.org/2001/XMLSchema'
    });
}
Beispiel #7
0
SVGShape.prototype.setNamespace = function(ns) {
	if (!this._namespaced && !!this.spriter.config.svg.namespaceIDs) {
		
		// Ensure the shape has been complemented before
		if (!this.svg.ready) {
			var error				= new Error('Shape namespace cannot be set before complementing');
			error.name				= 'NotPermittedError';
			error.errno				= 1419162245;
			throw error;
		}
		
		var select					= xpath.useNamespaces({'svg': this.DEFAULT_SVG_NAMESPACE, 'xlink': this.XLINK_NAMESPACE});
		
		// Build an ID substitution table (and alter the SVG document's IDs accordingly)
		var subst					= {};
		select('//*[@id]', this.dom).forEach(function(elem) {
			var id					= elem.getAttribute('id'),
			substId					= ns + id;
			subst['#' + id]			= substId;
			elem.setAttribute('id', substId);
		});
	
		// Substitute ID references in <style> elements
		var style					= select('//svg:style', this.dom);
		if (style.length) {
			var cssmin				= require('cssmin');
			select('//svg:style', this.dom).forEach(function(style) {
				style.textContent	= cssmin(this._replaceIdReferences(style.textContent, subst, true));
			}, this);
		}
		
		// Substitute ID references in xlink:href attributes
		select('//@xlink:href', this.dom).forEach(function(xlink){
			var xlinkValue			= xlink.nodeValue;
			if ((xlinkValue.indexOf('data:') !== 0) && (xlinkValue in subst)) {
				xlink.ownerElement.setAttribute('xlink:href', '#' + subst[xlinkValue]);
			}
		});
		
		// Substitute ID references in referencing attributes
		svgReferenceProperties.forEach(function(refProperty){
			select('//@' + refProperty, this.dom).forEach(function(ref) {
				ref.ownerElement.setAttribute(ref.localName, this._replaceIdReferences(ref.nodeValue, subst, false))
			}, this);
		}, this);
		
		// Substitute ID references in aria-labelledby attribute
		if (this.dom.documentElement.hasAttribute('aria-labelledby')) {
			this.dom.documentElement.setAttribute('aria-labelledby', this.dom.documentElement.getAttribute('aria-labelledby').split(' ').map(function(label){
				return (('#' + label) in subst) ? subst['#' + label] : label; 
			}).join(' '));
		}
		
		this._namespaced			= true;
	}
}
function camt05300102(str) {
  var doc = new dom().parseFromString(str),
      select = xpath.useNamespaces({
        a: 'urn:iso:std:iso:20022:tech:xsd:camt.053.001.02'
      }),
      ret = {};
  var statements = select('/a:Document/a:BkToCstmrStmt/a:Stmt', doc);
  ret.statements = statements.map(parseStatement(select));
  return ret;
}
Beispiel #9
0
function OPF(doc) {
  this.doc = doc;
  var _select = xpath.useNamespaces({
    'dc': 'http://purl.org/dc/elements/1.1/',
    '_': 'http://www.idpf.org/2007/opf'
  });

  this.select = function(query, single) {
    return _select(query, this.doc, single || false);
  };
};
Beispiel #10
0
    function resolveSitecorePath(version) {
        var file = grunt.file.read("../../deploy.targets").toLowerCase();
        var doc = new dom().parseFromString(file);

        var select = xpath.useNamespaces({
            "msb": "http://schemas.microsoft.com/developer/msbuild/2003"
        });

        var nodes = select("/msb:project/msb:propertygroup[contains(@condition, '" + version + "')]/msb:sitecorepath/text()", doc);

        return nodes[0].toString();
    };
		client.GetFolder(xml, function(err, result, body) {
			if (err) {
			  return p.reject(err.message);
			}
			
			var doc = new dom().parseFromString(body);
			var select = xpath.useNamespaces({"t": "http://schemas.microsoft.com/exchange/services/2006/types"});
			var nodes = select("//t:FolderId", doc);
			if (nodes.length > 0) {
			   p.resolve(nodes[0].getAttribute('Id'));
			}
			return p;
		});
Beispiel #12
0
            }, [codeMirrorElement.value], function (codeMirrorTextContent) {
                var jobXml = codeMirrorTextContent.value;
                var xpath = require('xpath');
                var dom = require('xmldom').DOMParser;

                var select = xpath.useNamespaces({"p": "urn:proactive:jobdescriptor:3.8"});

                var jobXmlDocument = new dom().parseFromString(jobXml);

                if (typeof xpathCheck === "function") {
                    xpathCheck.call(self, select, jobXmlDocument);
                }
            });
 openinfoman.fetchAllEntities((err, result) => {
   if (err) {
     winston.info.error(err.stack)
   }
   t.ok(result, 'the result should be instanciated')
   const doc = new Dom().parseFromString(result)
   const select = xpath.useNamespaces({'csd': 'urn:ihe:iti:csd:2013'})
   const count = select('count(//csd:CSD/csd:providerDirectory/csd:provider)', doc)
   t.equal(count, 2, 'two provider should exist in the result')
   csdServer.stop(() => {
     t.end()
   })
 })
        MeetupsAPI.Bbb.getDefaultConfigXML(ctx, function(err, result) {
            if(err || result.returncode != 'success') {
                return callback({'code': 503, 'msg': 'Fatal error'});
            }

            defaultConfigXML = result.defaultConfigXML;
            var serializer = new XMLSerializer();
            var doc = new DOMParser().parseFromString(defaultConfigXML);
            var select = xpath.useNamespaces();
            var node;

            //// set layout bbb.layout.name.videochat and others
            node = select('//layout ', doc, true);
            node.setAttribute('defaultLayout', 'bbb.layout.name.videochat');
            node.setAttribute('showLayoutTools', 'false');
            node.setAttribute('confirmLogout', 'false');
            node.setAttribute('showRecordingNotification', 'false');
            //// process modules
            ////// remove desktop sharing
            node = xpath.select1("//modules/module[@name=\'DeskShareModule\']", doc);
            node.setAttribute('showButton', 'false');
            //// remove PhoneModule button
            node = xpath.select1("//modules/module[@name=\'PhoneModule\']", doc);
            node.setAttribute('showButton', 'true');
            node.setAttribute('skipCheck', 'true');
            node.setAttribute('listenOnlyMode', 'false');
            //// remove VideoconfModule button
            node = xpath.select1("//modules/module[@name=\'VideoconfModule\']", doc);
            node.setAttribute('showButton', 'true');
            node.setAttribute('autoStart', 'true');
            node.setAttribute('skipCamSettingsCheck', 'true');
            //// remove layout menu
            node = xpath.select1("//modules/module[@name=\'LayoutModule\']", doc);
            node.setAttribute('enableEdit', 'false');

            var xml = serializer.serializeToString(doc);
            MeetupsAPI.Bbb.joinURL(ctx, profile, xml, function(err, joinInfo) {
                if(err) {
                    res.send(503, 'Fatal error');
                }

                MeetupsAPI.emit(MeetupsConstants.events.JOIN_MEETUP, ctx, groupProfile, function(errs) {

                });

                return callback(null, joinInfo);
            });
        });
Beispiel #15
0
 getUrls: function(xmlDoc,featuretype, baseUrl){
     var doc = new dom().parseFromString(xmlDoc), urlString = '', flagSearch = 0, total=0;
     var select = xpath.useNamespaces({"gmd": "http://www.isotc211.org/2005/gmd",  "gco": 'http://www.isotc211.org/2005/gco' });
     count = select('count(//gmd:URL/text())', doc);
     for (var i = 0, len = count; i < len; i++) {
         urlString = select('//gmd:URL/text()', doc)[i].nodeValue ;
         flagSearch = urlString.search("service=WFS");  //flagSearch is total Number of service=WFS etries found in CSW file
         if (flagSearch > 0){
             total +=1;
             var WFSRecord = new dbPointer({ wfsurl: urlString, featureType: featuretype, cswURL:baseUrl });
             WFSRecord.save();
         }
         flagSearch = 0;
     }
    console.log('Total :'+ total+' For :'+featuretype)
 }
.then(function(data) {
	var p = promise.Promise();
	    
	var doc = new dom().parseFromString(data);
	var select = xpath.useNamespaces({"t": "http://schemas.microsoft.com/exchange/services/2006/types"});
	var nodes = select("//t:CalendarItem/t:ItemId", doc);
	
	items = nodes.map(function(item) {
	   return {
	     itemId: item.getAttribute('Id'),
	     changeKey: item.getAttribute('ChangeKey')
	  };
	});
	p.resolve(items);

  return p;
})
    openinfoman.loadProviderDirectory(testProviders, (err, orchestrations) => {
      t.error(err, 'should not error')
      t.ok(orchestrations, 'orchestrations should be set')
      t.equals(orchestrations.length, 2, 'there should only be two orchestrations')

      t.ok(orchestrations[1].request.body)

      const doc = new Dom().parseFromString(orchestrations[1].request.body)
      const select = xpath.useNamespaces({'csd': 'urn:ihe:iti:csd:2013'})
      const providers = select('/csd:requestParams/csd:provider/@entityID', doc)
      t.equals(providers[0].value, 'urn:uuid:20258004-a149-4225-975b-5f64b14910dc')
      t.equals(providers[1].value, 'urn:uuid:5e971a37-bed4-4204-b662-ef8b4fcec5f2')

      csdServer.stop(() => {
        t.end()
      })
    })
Beispiel #18
0
function XMLParser(body) {
    if(Buffer.isBuffer(body))
        body = body.toString('utf-8');

    this.data = new xmldom.DOMParser().parseFromString(body);

    // Look if the element has a default namespace
    // we are going to support only schema with one or no namespaces
    var namespace = this.data.documentElement.getAttribute('xmlns');
    if(namespace && namespace.length > 0) {
        this.namespace = 'x:';
        this.select = xpath.useNamespaces({'x': namespace});
    }
    else {
        this.namespace = '';
        this.select = xpath.select
    }
}
Beispiel #19
0
    return this.GetSchema().then(function(schema) {
        var xmlDocument = new domParser().parseFromString(schema);
        var select = xpath.useNamespaces({
            "s": "http://schemas.medicomp.com/V3/UserSettings.xsd"
        });
        var settingNodes = select('//s:Item', xmlDocument);
        var settings = {};

        for (var i = 0; i < settingNodes.length; i++) {
            var id = select("@id", settingNodes[i])[0].value;
            var valueNodes = select("@Value", settingNodes[i]);
            var value = valueNodes.length == 1 ? valueNodes[0].value : '';

            if (!settings[id]) {
                settings[id] = value;
            }
        }

        return settings;
    });
Beispiel #20
0
            function(data, cb) {
                var doc = new DOMParser().parseFromString(data, 'text/xml');

                var select = xpath.select;
                if(input.nsmap) {
                    select = xpath.useNamespaces(input.nsmap);
                }

                // we expect selectors to match only one node
                var node = select(selector, doc);
                if(!!node && node.length > 0) {
                    node[0].value = replace_string;

                    // write the file back out
                    var serializer = new XMLSerializer();
                    var xml = serializer.serializeToString(doc);
                    fs.writeFile(filePath, xml, cb);
                }
                else {
                    cb(null);
                }
            }
Beispiel #21
0
request( options, function ( error, response, body ){
	var indeks = [], nilai = [], poin = [], persen = [], temporary = {}, getAll = [];
	var documents = parse5.parse(body);
    var xhtml = xmlser.serializeToString(documents);
    var doc = new dom().parseFromString(xhtml);
    var select = xpath.useNamespaces({"x": "http://www.w3.org/1999/xhtml"});
    var nodes = select('//x:li[@class="rpItem"]', doc);
    console.log('------------------------------------');

    for ( var c in nodes ) {

    	temporary = {
    		indeks 	: nodes[c].childNodes[0].firstChild.data,
    		nilai 	: nodes[c].childNodes[1].nextSibling.firstChild.data,
    		poin 	: nodes[c].childNodes[2].nextSibling.nextSibling.firstChild.data,
    		persen 	: nodes[c].childNodes[3].nextSibling.nextSibling.nextSibling.firstChild.data,
    	}

    	getAll.push(temporary)
    }

    console.log(getAll);
});
Beispiel #22
0
 t.test('has valid links', function(t) {
   var baseURL = server.getBaseURL();
   var select = xpath.useNamespaces({"atom": "http://www.w3.org/2005/Atom"});
   var parser = new xmldom.DOMParser();
   var doc = parser.parseFromString(atomBody, "text/xml");
   async.eachSeries(["atom:feed/atom:link[not(@rel)]/@href",
                     "atom:feed/atom:link[@rel='alternate']/@href",
                     "atom:feed/atom:link[@rel='self']/@href",
                     "atom:feed/atom:link[@rel='first']/@href",
                     "atom:feed/atom:link[@rel='last']/@href"
   ], function(expression, done) {
     var results = select(expression, doc);
     t.equal(1, results.length);
     var href = results[0].nodeValue;
     var patched_href = href.replace(new RegExp("^https://oversight.garden"),
                                     baseURL);
     request(patched_href, function(error, response, body) {
       t.ifError(error);
       t.equal(200, response.statusCode);
       done();
     });
   }, t.end);
 });
Beispiel #23
0
 request.get(url, function(error, response, body) {
   var ret = [];
   var doc = new dom({
     locator: {},
     errorHandler: {
       warning: function(w){}
     }
   }).parseFromString(body);
   var select = xpath.useNamespaces({'html': 'http://www.w3.org/1999/xhtml'});
   var nodes = select("//html:a[@class='buttonDownload']", doc);
   nodes.forEach(function(n) {
     var root = n.parentNode.parentNode.parentNode;
     var subUrl = n.getAttribute('href');
     var desc = n.textContent;
     var info = select(".//html:td[@class='NewsTitle']", root)[0];
     var team = info.textContent.split(',')[0].replace('Version ', '');
     var language = _.trim(select(".//*[@class='language']", root)[0].textContent);
     var completed = _.trim(select('.//html:b', n.parentNode.parentNode)[0].textContent);
     // FIXME: Create valid sub info
     ret.push({
       engine: 'Addic7ed',
       name: team + ': ' + desc + '('+completed+')',
       team: team,
       language: language,
       download: function() {
         // Stream file
         return request({
           url: 'http://www.addic7ed.com'+subUrl,
           headers: {
             'Referer': 'http://www.addic7ed.com/'
           }
         });
       }
     });
   });
   deferred.resolve(ret);
 });
Beispiel #24
0
 queries.forEach(function (query) {
     var select = options.namespaces ? xpath.useNamespaces(options.namespaces) : xpath.select;
     var nodes = select(query, doc);
     nodes.forEach(function (node) {
         var value = getValue(node);
         grunt.verbose.writeln('setting value of "' + query + '" to "' + value + '"');
         if (valueType === 'element') {
             node.textContent = '';
             while (node.firstChild) {
                 node.removeChild(node.firstChild);
             }
             node.appendChild(domParser.parseFromString(value));
         }
         else if (valueType === 'remove') {
             var parentNode = node.parentNode;
             parentNode.removeChild(node);
         }
         else if (node.nodeType === ATTRIBUTE_NODE) {
             node.value = value;
         } else {
             node.textContent = value;
         }
     });
 });
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * **************************************************#
 */
var fs = require('fs'),
    path = require('path'),
    xpath   = require('xpath'),
    xml2js = require('xml2js'),
    dom     = require('xmldom').DOMParser,
    xmlbuilder = require('xmlbuilder'),
    async = require('async'),
    request = require('request');

var dataDir = path.join(__dirname, "data");
var select = xpath.useNamespaces({"gmd": "http://www.isotc211.org/2005/gmd", "gco":"http://www.isotc211.org/2005/gco"});
var cmd = process.argv[2];
if (!cmd) {
    console.log("Usage etl_baw_test_data.js <insert|update|delete>");
    process.exit(1);
}


var files = fs.readdirSync(dataDir);
console.log(files);

async.eachSeries(files, function(file, callback) {
    console.log("Work on " + file);
    var data = fs.readFileSync(path.join(dataDir, file), { encoding : 'UTF-8' });
    var data = data.replace(/<\?xml version="1\.0" encoding="UTF-8"\?>/g, '');
    var doc = new dom().parseFromString(data);
Beispiel #26
0
		this.files.forEach(function (f) {
		
			// Accept only a single src file per dest
			if (f.src.length > 1) {
				throw new Error('Only a single src file per dest is supported. ' + f.src.length + ' given.');
			}
			
			// Make sure the source file exists
			if (!grunt.file.exists(f.src[0])) {
				throw new Error('Source file "' + f.src[0] + '" not found.');
			}
			
			
			
			var doc = domParser.parseFromString(grunt.file.read(f.src[0])),
				select = options.namespaces ?
					xpath.useNamespaces(options.namespaces) :
					xpath.select,
					
				wrappedSelect = function (query, context) {
					return select(query, context || doc);
				},
				
				// Bind file-level "globals" to handlerFns
				readFn = handleReadQuery.bind(null, wrappedSelect),
				deletionFn = handleDeletionQuery.bind(null, wrappedSelect),
				updateFn = handleUpdateQuery.bind(null, wrappedSelect),
				insertionFn = handleInsertionQuery.bind(null, wrappedSelect, doc, options.namespaces || {});
			
			
			// Treat .updates as an alias for .replacements.
			// If "xpath" is given directly inside of the options object,
			// treat it as the config for a single update action.
			options.replacements = options.replacements || options.updates || 
				(options.xpath ? [options] : []);
			
			
			// Actions is a customizable array of reads, insertions, deletions and updates,
			// but in any order.
			// The type of action is denoted by the first char of the "type" option string (CI)
			// That way, "i", "INS", "inSert", and even "idiotic c0de" all denote an Insertion.
			//
			// C or I: Insert
			// R: Read
			// U: Update (assumed default)
			// D: Delete
			[].concat(
				toArray(options.reads).map(function (e) { e.type = 'R'; return e; }),
				toArray(options.deletions).map(function (e) { e.type = 'D'; return e; }),
				toArray(options.insertions).map(function (e) { e.type = 'I'; return e; }),
				toArray(options.replacements),
				toArray(options.actions)
			).
				forEach(function (action) {
					var type = (action.type || '').toUpperCase().charAt(0);
					
					switch (type) {
						case 'R': // READ
							toArray(action.xpath).
								filter(function (xpath, i) {
									// Allow only one xpath per read action so as not to overcomplicate returns
									if (i === 0) { return true; }
									grunt.log.warn('Discarding secondary xpath "' + xpath + '" in read action');
									return false;
								}).
								forEach(readFn.bind(null, !!action.returnArray, action.saveAs, action.callback));
								break;
						case 'D': // DELETE
							toArray(action.xpath).
								forEach(deletionFn);
							break;
						case 'I': // INSERT-UPDATE
						case 'C': // or CREATE
							toArray(action.xpath).
								forEach(insertionFn.bind(null, action.value, action.node));
							break;
						default: // UPDATE
							toArray(action.xpath).
								forEach(updateFn.bind(null, action.value));
					}
				});
			
			
			// Write the destination file.
			grunt.file.write(f.dest, xmlSerializer.serializeToString(doc));
			
			// Print a success message.
			grunt.log.writeln('File ' + f.dest.cyan + ' created.');
		});
Beispiel #27
0
    openinfoman.fetchAllEntities((err, csdDoc, orchs) => {
      if (orchs) {
        orchestrations = orchestrations.concat(orchs)
      }
      if (err) {
        return reportFailure(err, req)
      }
      if (!csdDoc) {
        return reportFailure(new Error('No CSD document returned'), req)
      }
      winston.info('Done fetching providers.')

      // extract each CSD entity for processing
      const doc = new Dom().parseFromString(csdDoc)
      const select = xpath.useNamespaces({'csd': 'urn:ihe:iti:csd:2013'})
      let entities = select('/csd:CSD/csd:providerDirectory/csd:provider', doc)
      entities = entities.map((entity) => entity.toString())
      winston.info(`Converting ${entities.length} CSD entities to RapidPro contacts...`)
      let contacts = entities.map((entity) => {
        try {
          return adapter.convertCSDToContact(entity)
        } catch (err) {
          winston.warn(`${err.message}, skipping contact`)
          return null
        }
      }).filter((c) => {
        return c !== null
      })
      winston.info('Done converting to contacts.')

      new Promise((resolve, reject) => {
        if (config.rapidpro.groupname) {
          winston.info('Fetching group uuid for RapidPro...')
          rapidpro.getGroupUUID(config.rapidpro.groupname, (err, groupUUID, orchs) => {
            if (orchs) {
              orchestrations = orchestrations.concat(orchs)
            }
            if (err) {
              reject(err)
            }
            winston.info(`Done fetching group uuid - ${groupUUID}`)
            resolve(groupUUID)
          })
        } else {
          resolve(null)
        }
      }).then((groupUUID) => {
        // add group to contacts
        if (groupUUID) {
          winston.info('Adding group to each contact...')
          contacts = contacts.map((c) => {
            c.group_uuids = [groupUUID]
            return c
          })
          winston.info('Done adding group to contacts.')
        }

        // Add all contacts to RapidPro
        let errCount = 0
        winston.info(`Adding/Updating ${contacts.length} contacts to in RapidPro...`)
        const promises = []
        contacts.forEach((contact) => {
          promises.push(new Promise((resolve, reject) => {
            rapidpro.addContact(contact, (err, contact, orchs) => {
              if (orchs) {
                orchestrations = orchestrations.concat(orchs)
              }
              if (err) {
                winston.error(err)
                errCount++
              }
              resolve()
            })
          }))
        })

        Promise.all(promises).then(() => {
          winston.info(`Done adding/updating ${contacts.length} contacts to RapidPro, there were ${errCount} errors.`)
          winston.info('Fetching RapidPro contacts and converting them to CSD entities...')
          adapter.getRapidProContactsAsCSDEntities(groupUUID, (err, contacts, orchs) => {
            if (orchs) {
              orchestrations = orchestrations.concat(orchs)
            }
            if (err) {
              return reportFailure(err, req)
            }
            winston.info(`Done fetching and converting ${contacts.length} contacts.`)

            winston.info('Loading provider directory with contacts...')
            openinfoman.loadProviderDirectory(contacts, (err, orchs) => {
              if (orchs) {
                orchestrations = orchestrations.concat(orchs)
              }
              if (err) {
                return reportFailure(err, req)
              }
              winston.info('Done loading provider directory.')

              res.writeHead(200, { 'Content-Type': 'application/json+openhim' })
              res.end(JSON.stringify({
                'x-mediator-urn': mediatorConfig.urn,
                status: 'Successful',
                request: {
                  method: req.method,
                  headers: req.headers,
                  timestamp: req.timestamp,
                  path: req.path
                },
                response: {
                  status: 200,
                  timestamp: new Date()
                },
                orchestrations: orchestrations
              }))
            })
          })
        })
      }, (err) => {
        return reportFailure(err, req)
      })
    })
Beispiel #28
0
		function (data, next) {
			var doc = new dom().parseFromString(data);
	   	var select = xpath.useNamespaces(namespaces);
	    var nodes = select('/report/QueryResult/ResultXml/rowset:rowset/rowset:Row', doc);
	    parser.parseString("<items>" + nodes.join("") + "</items>", next);
		},
Beispiel #29
0
function entryCount (body) {
    var doc = new DOMParser().parseFromString(body),
        select = xpath.useNamespaces({ atom: 'http://www.w3.org/2005/Atom' });
    return select('count(//atom:entry)', doc);
}
Beispiel #30
0
import fs from 'fs';
import Stream from 'stream';
import unzip from 'unzipper';
import xpath from 'xpath';
import XMLDOM from 'xmldom';

const ns = { a: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main' };
const select = xpath.useNamespaces(ns);

function extractFiles(path, sheet) {
  const files = {
    strings: {},
    sheet: {},
    'xl/sharedStrings.xml': 'strings',
    [`xl/worksheets/sheet${sheet}.xml`]: 'sheet'
  };

  const stream = path instanceof Stream ? path : fs.createReadStream(path);

  return new Promise((resolve, reject) => {
    const filePromises = [];

    stream
      .pipe(unzip.Parse())
      .on('error', reject)
      .on('close', () => {
        Promise.all(filePromises).then(() => resolve(files));
      })
      // For some reason `end` event is not emitted.
      // .on('end', () => {
      //   Promise.all(filePromises).then(() => resolve(files));