function _Import(dirPath,file, callback) { logfct('Importing file ' + file); var ConfigPath = getConfigPath(dirPath); var pemPath = getPemPath(dirPath); //debugger; // Is it a .pem file? var keyCertValues = keyFiles.readFromFile(file); var keyPresent = !!keyCertValues.key; var certPresent = !!keyCertValues.cert; var publishSettings = null; var publishSettingsFilePath = path.join(dirPath, 'publishSettings.xml'); settingspath = publishSettingsFilePath; if (keyPresent + certPresent === 1) { // Exactly one of them present. Tell the user about the error. // Do not try this file as xml or pfx callback(1,'File ' + file + ' needs to contain both private key and cert, but only ' + (keyCertValues.key ? 'key' : 'certificate') + ' was found.'); } else if (keyCertValues.key && keyCertValues.cert) { // Both key and cert are present. keyFiles.writeToFile(pemPath, keyCertValues); logfct('Key and cert have been written to ' + pemPath); } else { // Try to open as publishsettings or pfx. logfct(file + ' does not appear to be a PEM file. Reading as publish settings file.'); var parser = new xml2js.Parser(xml2js.defaults["0.1"]); parser.on('end', function (settings) { publishSettings = settings; }); var readBuffer = fs.readFileSync(file); try { parser.parseString(readBuffer); } catch (err) { if (err.toString().indexOf('Non-whitespace before first tag') === -1) { // This looks like an xml parsing error, not PFX. callback(1,err); } logfct('Unable to read file as xml publish settings file. Assuming it is pfx'); publishSettings = null; } //logfct(publishSettings); if (publishSettings) { processSettings(file, publishSettings); } else { convertPfx(readBuffer); } } return callback(0,'success'); function processSettings(file, settings) { if (!settings.PublishProfile || !settings.PublishProfile['@'] || (!settings.PublishProfile['@'].ManagementCertificate && settings.PublishProfile['@'].SchemaVersion !== '2.0')) { throw new Error('Invalid publishSettings file. Use "azure account download" to download publishing credentials.'); } var attribs = settings.PublishProfile['@']; var subs = settings.PublishProfile.Subscription; if (typeof subs === 'undefined' || subs === undefined) { subs = []; } else if (typeof (subs[0]) === 'undefined') { subs = [subs]; } if (subs.length === 0) { logfct('Importing profile with no subscriptions'); } else { for (var index in subs) { logfct('Found subscription:' + subs[index]['@'].Name); logfct(' Id: ' + subs[index]['@'].Id); } } if (attribs.Url) { var endpointInfo = utils.validateEndpoint(attribs.Url); var config = readConfig(dirPath); config.endpoint = endpointInfo; writeConfig(config); logfct('Setting service endpoint to:'+ config.endpoint); } if (attribs.ManagementCertificate) { logfct('Parsing management certificate'); var pfx = new Buffer(attribs.ManagementCertificate, 'base64'); convertPfx(pfx); } logfct('Storing account information at '+ publishSettingsFilePath); utils.writeFileSyncMode(publishSettingsFilePath, readBuffer); // folder already created by convertPfx() if (subs.length !== 0) { logfct('Setting default subscription to: '+ subs[0]['@'].Name); setSubscription(subs[0]['@'].Id); } logfct('Account publish settings imported successfully'); } function convertPfx(pfx) { var pem = pfx2pem(pfx); utils.writeFileSyncMode(pemPath, pem.toString(), 'utf8'); logfct('Converted PFX data to ' + pemPath); } function readSubscriptions () { if (!utils.pathExistsSync(publishSettingsFilePath)) { throw new Error('No publish settings file found. Please use "azure account import" first.'); } var parser = new xml2js.Parser(xml2js.defaults["0.1"]); var publishSettings = null; parser.on('end', function (settings) { publishSettings = settings; }); var readBuffer = fs.readFileSync(publishSettingsFilePath); try { parser.parseString(readBuffer); } catch (err) { if (err.toString().indexOf('Non-whitespace before first tag') === -1) { // This looks like an xml parsing error, not PFX. callback(1,err); } logfct('Unable to read file as xml publish settings file.'); publishSettings = null; } if (publishSettings) { var subs = publishSettings.PublishProfile.Subscription; if (typeof subs === 'undefined' || subs === undefined) { subs = []; } else if (typeof (subs[0]) === 'undefined') { subs = [subs]; } if (subs.length === 0) { logfct('No subscriptions.'); } else { var subscriptions = []; for (var s in subs) { subscriptions[s] = subs[s]['@']; } return subscriptions; } } else { throw new Error('Invalid publish settings file.'); } } function setSubscription (id) { var subscriptions = readSubscriptions(); var subscription = subscriptions.filter(function (subscription) { return subscription.Id === id; })[0]; if (!subscription) { throw new Error('Invalid subscription ' + id); } else { var config = readConfig(dirPath); if (subscription.ServiceManagementUrl && subscription.ServiceManagementUrl !== config.endpoint) { var endpointInfo = utils.validateEndpoint(subscription.ServiceManagementUrl); config.endpoint = endpointInfo; logfct('Setting service endpoint to:'+ config.endpoint); } if (subscription.ManagementCertificate) { logfct('Parsing management certificate'); var pfx = new Buffer(subscription.ManagementCertificate, 'base64'); convertPfx(pfx); } config.subscription = id; writeConfig(config); } } function writeConfig(cfg) { if (!utils.pathExistsSync(dirPath)) { logfct('Creating folder '+ dirPath); fs.mkdirSync(dirPath, 502); //0766 } logfct('Writing config '+ ConfigPath); fs.writeFileSync(ConfigPath, JSON.stringify(cfg)); } };
function parseData(xml) { if (!xml) { setTimeout(function () { process.exit(0); }, 5000); return; } var options = { explicitArray: false, mergeAttrs: true }; var parser = new xml2js.Parser(options); parser.parseString(xml, function (err, result) { if (err) { adapter.log.error(err); } else { adapter.log.info('got weather data from yr.no'); var forecastArr = result.weatherdata.forecast.tabular.time; var tableDay = '<table style="border-collapse: collapse; padding: 0; margin: 0"><tr class="yr-day">'; var tableHead = '</tr><tr class="yr-time">'; var tableMiddle = '</tr><tr class="yr-img">'; var tableBottom = '</tr><tr class="yr-temp">'; var dateObj = new Date(); var dayEnd = dateObj.getFullYear() + '-' + ('0' + (dateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + dateObj.getDate()).slice(-2) + 'T24:00:00'; var daySwitch = false; var day = -1; // Start from today var days = []; for (var i = 0; i < 12 && i < forecastArr.length; i++) { var period = forecastArr[i]; if (!period.period || period.period == '0') day++; // We want to process only today, tomorrow and the day after tomorrow if (day == 3) break; period.symbol.url = 'http://symbol.yr.no/grafikk/sym/b38/' + period.symbol.var + '.png'; period.symbol.name = _(period.symbol.name); period.windDirection.code = _(period.windDirection.code); if (i < 8) { switch (i) { case 0: tableHead += '<td>' + _('Now') + '</td>'; break; default: if (period.from > dayEnd) { if (!daySwitch) { daySwitch = true; tableDay += '<td colspan="' + i + '">' + _('Today') + '</td><td colspan="4">' + _('Tomorrow') + '</td>'; if (i < 3) tableDay += '<td colspan="' + (4 - i) + '">' + _('After tomorrow') + '</td>'; tableHead += '<td>' + parseInt(period.from.substring(11, 13), 10).toString() + '-' + parseInt(period.to.substring(11, 13), 10).toString() + '</td>'; } else { tableHead += '<td>' + parseInt(period.from.substring(11, 13), 10).toString() + '-' + parseInt(period.to.substring(11, 13), 10).toString() + '</td>'; } } else { tableHead += '<td>' + parseInt(period.from.substring(11, 13), 10).toString() + '-' + parseInt(period.to.substring(11, 13), 10).toString() + '</td>'; } } tableMiddle += '<td><img style="position:relative;margin:0;padding:0;left:0;top:0;width:38px;height:38px;" src="' + period.symbol.url + '" alt="' + period.symbol.name + '" title="' + period.symbol.name + '"><br/>'; tableBottom += '<td><span class="">' + period.temperature.value + '°C</span></td>'; } if (day == -1 && !i) day = 0; if (!days[day]) { days[day] = { date: new Date(period.from), icon: period.symbol.url, text: period.symbol.name, temperature_min: parseFloat(period.temperature.value), temperature_max: parseFloat(period.temperature.value), precipitation_level: parseFloat(period.precipitation.value), precipitation_chance: null, wind_direction: period.windDirection.code, wind_speed: parseFloat(period.windSpeed.mps) * 3.6, pressure: parseFloat(period.pressure.value), count: 1 }; } else { // Summarize // Take icon for day always from 12:00 to 18:00 if possible if (i == 2) { days[day].icon = period.symbol.url; days[day].text = period.symbol.name; days[day].wind_direction = period.windDirection.code; } if (period.temperature.value < days[day].temperature_min) days[day].temperature_min = parseFloat(period.temperature.value); if (period.temperature.value > days[day].temperature_max) days[day].temperature_max = parseFloat(period.temperature.value); days[day].precipitation_level += parseFloat(period.precipitation.value); days[day].wind_speed += parseFloat(period.windSpeed.mps) * 3.6; days[day].pressure += parseFloat(period.pressure.value); days[day].count++; } // Set actual temperature if (!day && !i) { days[day].temperature_actual = parseInt(period.temperature.value, 10); } } var style = '<style type="text/css">tr.yr-day td {font-family: sans-serif; font-size: 9px; padding:0; margin: 0;}\ntr.yr-time td {text-align: center; font-family: sans-serif; font-size: 10px; padding:0; margin: 0;}\ntr.yr-temp td {text-align: center; font-family: sans-serif; font-size: 12px; padding: 0; margin: 0;}\ntr.yr-img td {text-align: center; padding: 0; margin: 0;}</style>'; var table = style + tableDay + tableHead + tableMiddle + tableBottom + '</tr></table>'; //console.log(JSON.stringify(result, null, " ")); for (day = 0; day < days.length; day++) { // Take the average if (days[day].count > 1) { days[day].precipitation_level /= days[day].count; days[day].wind_speed /= days[day].count; days[day].pressure /= days[day].count; } days[day].temperature_min = Math.round(days[day].temperature_min); days[day].temperature_max = Math.round(days[day].temperature_max); days[day].precipitation_level = Math.round(days[day].precipitation_level); days[day].wind_speed = Math.round(days[day].wind_speed * 10) / 10; days[day].pressure = Math.round(days[day].pressure); days[day].date = adapter.formatDate(days[day].date); delete days[day].count; for (var name in days[day]) { adapter.setState('forecast.day' + day + '.' + name, {val: days[day][name], ack: true}); } } adapter.log.debug('data successfully parsed. setting states'); adapter.setState('forecast.html', {val: table, ack: true}); adapter.setState('forecast.object', {val: days, ack: true}, function () { setTimeout(function () { process.exit(0); }, 5000); }); } }); }
Config.prototype.load = function(file, data) { data = typeof data === "object" ? data : {}; // Load config data var json, doc; if (typeof file == "object") { // read object if (file.documentElement || file.ownerDocument) { // read xml-document doc = file; } else { // read json and merge with options json = merge(file, options); } } if (!json && !doc) { // Try to read file var contents = fs.readFileSync(file, 'utf8'); if (contents) { if (typeof data === 'object') { // Process template contents = _.template(contents, data); } if (path.extname(file) === '.json') { // Parse json try { json = JSON.parse(contents); } catch(e) { // No valid json input logger.error("No valid json input: " + file); } } else if (path.extname(file) === '.xml') { // Parse xml try { doc = new xmldom.DOMParser().parseFromString(contents); } catch(e) { // No valid xml input logger.error("No valid xml input: " + file); } } else { // No valid input at all logger.error("No valid input: " + file); return; } } } if (json) { // Set json result this.json = normalize(json); this.domjs = js2domjs(json); } else if (doc && contents) { // Parse xml // Get json json = dom2js(doc.documentElement); this.json = normalize(json); // Get domjs var domjs; var parser = new xml2js.Parser({attrkey: "@", charkey: "#"}); parser.parseString(contents, function (err, result) { if (!err) { domjs = result["widget"]; } }); if (domjs) { this.domjs = domjs; } } return this.json; };
fs.readFile(kul_fname, function(err, data) { parser.parseString(data); });
parser.addListener('end', function(result) { //var json_content = []; var json_content = []; //var ret = json_wrap(result.kul_pkg.widget); //fs.writeFileSync(json_fname, JSON.stringify(ret)); if(result.kul_pkg.blockid != undefined) { for(var loop = 0; loop < result.kul_pkg.blockid.length; ++loop) { var pkgid_obj = result.kul_pkg.blockid[loop]; var pkg_name = pkgid_obj.$.name; var pkg_kulfile = pkgid_obj.location[0]; pkg_kulfile = "y:/" + unit_name + "/kul/" + pkg_kulfile; json_content.push({"name" : pkg_name, "kul_filepath" : pkg_kulfile, "is_block" : true, "id" : ""}); } } for(var loop = 0; loop < result.kul_pkg.pkgid.length; ++loop) { var pkgid_obj = result.kul_pkg.pkgid[loop]; var pkg_name = pkgid_obj.$.name; var pkg_kulfile = pkgid_obj.location[0]; pkg_kulfile = "y:/" + unit_name + "/kul/" + pkg_kulfile; var parser_sub = new xml2js.Parser(); parser_sub.addListener('end', function(result_sub){ //fs.writeFileSync("y:\\abc.json", JSON.stringify(result_sub)); if(result_sub.kul_pkg.widget != undefined) { var js_filepath = result_sub.kul_pkg.widget[0].$.name + ".js"; var id = ""; //console.log(js_filepath); for(var loop_sub = 0; loop_sub < result_sub.kul_pkg.widget[0].property.length; ++loop_sub) { if(result_sub.kul_pkg.widget[0].property[loop_sub].$.name == "javascript") { js_filepath = result_sub.kul_pkg.widget[0].property[loop_sub]._; //console.log(js_filepath); } if(result_sub.kul_pkg.widget[0].property[loop_sub].$.name == "id") { id = result_sub.kul_pkg.widget[0].property[loop_sub]._; //console.log(js_filepath); } } js_filepath = "y:/" + unit_name + "/js/" + js_filepath; json_content.push({"name" : pkg_name, "kul_filepath" : pkg_kulfile, "js_filepath" : js_filepath, "is_block" : false, "id" : id}); } if(loop +1 == result.kul_pkg.pkgid.length) { //console.log(JSON.stringify(json_content)); //fs.writeFileSync(json_fname, JSON.stringify(json_content)); data.parameters = json_content; websocket.send(data); } }); //fs.readFile(block_fpath, function(err, data){ // parser_sub.parseString(data); //}); //console.log(pkg_kulfile); if(fs.existsSync(pkg_kulfile)) { parser_sub.parseString(fs.readFileSync(pkg_kulfile)); } } });
}, function(err,resp,body) { if (err) return cbk(err); var parser = new xml2js.Parser(); parser.parseString(body, function (err, result) { if (err) return cbk(err); // Transform geonames' structure into something that looks like Google's JSON outpu // https://developers.google.com/maps/documentation/geocoding/#JSON var googlejson = { "status":"OK", "results":[ { "address_components":[], "formatted_address":"", "geometry":{ "location":{ "lat":lat, "lng":lng } } } ] }; if (result.geonames.address) { var a = result.geonames.address[0]; if (a.streetNumber && typeof a.streetNumber[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.streetNumber[0], "short_name":a.streetNumber[0], "types":["street_number"] }); if (a.street && typeof a.street[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.street[0], "short_name":a.street[0], "types":["route"] }); if (a.placename && typeof a.placename[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.placename[0], "short_name":a.placename[0], "types":["locality", "political"] }); if (a.adminName1 && typeof a.adminName1[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.adminName1[0], "short_name":a.adminCode1[0], "types":[ "administrative_area_level_1", "political" ] }); if (a.adminName2 && typeof a.adminName2[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.adminName2[0], "short_name":a.adminCode2[0], "types":[ "administrative_area_level_2", "political" ] }); if (a.countryCode && typeof a.countryCode[0]=="string") googlejson.results[0].address_components.push({ "long_name":a.countryCode[0]=="US"?"United States":"", "short_name":a.countryCode[0], "types":[ "country" ] }); if (a.lat && typeof a.lat[0]=="string") googlejson.results[0].geometry.location = { "lat":parseFloat(a.lat[0]), "lng":parseFloat(a.lng[0]) } } if (result.geonames.geoname) { // http://www.geonames.org/export/codes.html // https://developers.google.com/maps/documentation/geocoding/#Types var fcode2google = { "ADM1":[ "administrative_area_level_1", "political" ], "ADM2":[ "administrative_area_level_2", "political" ], "ADM3":[ "administrative_area_level_3", "political" ], "ADMD":[ "political"], "PPL" :[ "locality"] }; result.geonames.geoname.forEach(function(geoname) { // Push only recognized types to results if (geoname.fcode[0]=="PCLI") { googlejson.results[0].address_components.push({ "long_name":geoname.name[0], "short_name":geoname.countryCode[0], "types":[ "country", "political"] }); } else if (fcode2google[geoname.fcode[0]]) { googlejson.results[0].address_components.push({ "long_name":geoname.toponymName[0], "short_name":geoname.name[0], "types":fcode2google[geoname.fcode[0]] }); } }); } // Make a formatted address as well as we can var shortNames = {}; googlejson.results[0].address_components.forEach(function(c) { if (c.types[0]=="country") return shortNames.country = c.long_name || c.short_name; shortNames[c.types[0]] = c.short_name; }); var formatted = []; if (shortNames.street_number || shortNames.route) { formatted.push((shortNames.street_number?shortNames.street_number+" ":"")+shortNames.route); } if (shortNames.locality) { formatted.push(shortNames.locality); } if (shortNames.administrative_area_level_1) { formatted.push(shortNames.administrative_area_level_1); } if (shortNames.country) { formatted.push(shortNames.country); } googlejson.results[0].formatted_address = formatted.join(", "); cbk(null, googlejson); }); });
fs.readFile(unit_entry_filename, function(err, data) { parser.parseString(data); });
function(data, next){ console.log('Parsing XML.'); parser.parseString(data, next); },
fs.readFile(__dirname + '/city.xml', function(err, data) { parser.parseString(data, function (err, result) { city_list = result['CityDetails']['CityDetail']; }); });
}).on('end',function() { var parser = new xml2js.Parser(); parser.parseString(xml); cb(null,parser.resultObject); });
try { parser.parseString(content, function(err, data) { if (err) { logger.error('device/' + self.deviceID, { event: 'xml2js.Parser', content: content, diagnostic: err.message }); return; } if ((!data['e:propertyset']) || (!util.isArray(data['e:propertyset']['e:property'])) || (!util.isArray(data['e:propertyset']['e:property'][0].LastChange))) return; parser.parseString(data['e:propertyset']['e:property'][0].LastChange[0], function(err, event) { var mode, status; if (err) { logger.error('device/' + self.deviceID, { event : 'xml2js.Parser' , diagnostic : 'parseString' , content : data['e:propertyset']['e:property'][0].LastChange[0] , exception : err }); return; } status = { PLAYING : 'playing' , PAUSED_PLAYBACK : 'paused' , TRANSITIONING : 'busy' , STOPPED : 'idle' }[event.Event.InstanceID[0].TransportState[0].$.val] || 'idle'; mode = { NORMAL : 'normal' , REPEAT_ALL : 'repeat' , SHUFFLE : 'shuffle' , SHUFFLE_NOREPEAT : 'shuffle1' }[event.Event.InstanceID[0].CurrentPlayMode[0].$.val] || 'normal'; if ((self.info.mode != mode) || (self.status !== status)) { self.info.mode = mode; self.status = status; self.changed(); self.refresh(self); } parser.parseString(event.Event.InstanceID[0].CurrentTrackMetaData[0].$.val, function(err, didl) { var track; if (err) { logger.error('device/' + self.deviceID, { event : 'xml2js.Parser' , diagnostic : 'parseString' , content : event.Event.InstanceID[0].CurrentTrackMetaData[0].$.val , exception : err }); return; } track = self.sonos.parseDIDL(didl); if ((self.info.track.title !== track.title) || (self.info.track.artist !== track.artist) || (self.info.track.album !== track.album) || (self.info.track.albumArtURI !== track.albumArtURI)) { delete(track.albumArtURL); self.info.track = track; self.changed(); } }); }); }); } catch(ex) { logger.error('device/' + self.deviceID, { event: 'notify', diagnostic: ex.message }); }
export default function handleBreakoutJoinURL({ payload }) { const REDIS_CONFIG = Meteor.settings.redis; const CLIENT_HTML = 'HTML5'; const { noRedirectJoinURL, } = payload; check(noRedirectJoinURL, String); const urlParams = getUrlParams(noRedirectJoinURL); const selector = { externalMeetingId: urlParams.meetingID, }; let breakout = Breakouts.findOne(selector); const res = Meteor.http.call('get', noRedirectJoinURL); xmlParser.parseString(res.content, (err, parsedXML) => { if (err) { return Logger.error(`An Error occured when parsing xml response for: ${noRedirectJoinURL}`); } breakout = Breakouts.findOne(selector); const { response } = parsedXML; const users = breakout.users; const user = { userId: payload.userId, urlParams: { meetingId: response.meeting_id[0], userId: response.user_id[0], authToken: response.auth_token[0], }, }; const userExists = users.find(u => user.userId === u.userId); if (userExists) { return; } const modifier = { $push: { users: user, }, }; const cb = (err, numChanged) => { if (err) { return Logger.error(`Adding breakout to collection: ${err}`); } const { insertedId, } = numChanged; if (insertedId) { return Logger.info(`Added breakout id=${urlParams.meetingID}`); } return Logger.info(`Upserted breakout id=${urlParams.meetingID}`); }; return Breakouts.upsert(selector, modifier, cb); }); }
function parseXML(xml, fn){ var parser = new xml2js.Parser({ trim:true, explicitArray:false, explicitRoot:false }); parser.parseString(xml, fn||function(err, result){}); }
parsers['application/xml'] = function(data, callback){ var xml_parser = new xml2js.Parser({ explicitRoot: true, explicitArray: false }); xml_parser.parseString(data, function(err, result){ callback(err, err ? data : result); // return original if err failed }); };
var policyEditor2 = function() { console.log('Policy editor 2 constructor'); //Load the xml parser var xmlParser = new xml2js.Parser(xml2js.defaults['0.2']); //init list of available policy files; this list should be updated every time a funcion //is called since some policy files may be added or deleted (app policies or session decision policies) var policyFiles = new Array(); policyFiles.push({'path': manufacturerPolicyFile, 'desc': 'Manufacturer policy', 'content': null}); policyFiles.push({'path': userPolicyFile, 'desc': 'User policy', 'content': null}); policyFiles.push({'path': decisionPolicyFile, 'desc': 'Permanent decision', 'content': null}); function updateFileList() { } function addType(policySet) { if(policySet['policy']) { for(var i in policySet['policy']) { policySet['policy'][i]['$']['type'] = 'policy'; } } if(policySet['policy-set']) { for(var i in policySet['policy-set']) { policySet['policy-set'][i]['$']['type'] = 'policy-set'; policySet['policy-set'][i] = addType(policySet['policy-set'][i]); } } return policySet; } function readFileContent(fileId) { var result = null; var xmlPolicy = fs.readFileSync(policyFiles[fileId].path); //TODO: it is not clear why parseString ends in a sync way... xmlParser.parseString(xmlPolicy, function(err, data) { result = data['policy-set']; }); //Adds type (policy or policy-set result['$']['type'] = 'policy-set'; result = addType(result); policyFiles[fileId].content = result; } function getPolicyById(policySet, policyId) { //TODO: if the attribute id of the policy/policy-set is not defined, the function will crash //console.log('getPolicyById - policySet is '+JSON.stringify(policySet)); if(policyId == null || policySet['$']['id'] == policyId) { return policySet; } if(policySet['policy']) { for(var j in policySet['policy']) { if(policySet['policy'][j]['$']['id'] == policyId) { return policySet['policy'][j]; } } } if(policySet['policy-set']) { for(var j in policySet['policy-set']) { if(policySet['policy-set'][j]['$']['id'] == policyId) { return policySet['policy-set'][j]; } var tmp = getPolicyById(policySet['policy-set'][j], policyId); if(tmp != null) { return tmp; } } } return null; } function getIdList(policySet, policyType) { var result = new Array(); if(policyType == 'policy' && policySet['policy']) { for(var j in policySet['policy']) { result.push(policySet['policy'][j]['$']['id']); } } if(policySet['policy-set']) { for(var j in policySet['policy-set']) { if(policyType == 'policy-set') { result.push(policySet['policy-set'][j]['$']['id']); } result = result.concat(getIdList(['policy-set'][j], policyType)); } } return result; } function getNewId(fileId, policyType) { //TODO: padding is fixed; what if index exceeds? var padding = 6; var ids = getIdList(policyFiles[fileId].content, policyType); ids.sort(); var nextId = parseInt(ids[ids.length-1].slice(1))+1; var result = ('00000000'+nextId).substr(-padding); if(policyType == 'policy') { result = 'p'+result; } else { result = 's'+result; } return result; } function removePolicyById(policySet, policyId) { //console.log('removePolicyById - id is '+policyId+', set is '+JSON.stringify(policySet)); if(policySet['policy']) { for(var j in policySet['policy']) { if(policySet['policy'][j]['$']['id'] == policyId) { policySet['policy'].splice(j, 1); return true; } } } if(policySet['policy-set']) { for(var j in policySet['policy-set']) { if(policySet['policy-set'][j]['$']['id'] == policyId) { policySet['policy-set'].splice(j, 1); return true; } if(removePolicyById(policySet['policy-set'][j], policyId)) { return true; } } } return false; } function removeType(policySet) { var result = policySet; delete result['$']['type']; if(result['policy']) { for(var i in result['policy']) { delete result['policy'][i]['$']['type']; } } if(result['policy-set']) { for(var i in result['policy-set']) { removeType(result['policy-set'][i]); } } return result; } function removeSub(subject, attribute) { for(var i in subject[0]['subject-match']) { if(subject[0]['subject-match'][i]['$']['attr'] == attribute) { delete subject[0]['subject-match'][i]; return; } } } function addSub(subject, attribute, match) { var tmp = {'$':{}}; tmp['$']['attr'] = attribute; tmp['$']['match'] = match; subject[0]['subject-match'].push(tmp); } this.getPolicyFiles = function() { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to decide which files can be accessed var result = new Array(); for(var i=0; i<policyFiles.length; i++) { if(policyFiles[i] != null) { //console.log('Policy '+i+' is '+policyFiles[i].desc+' ('+policyFiles[i].path+')'); result.push({'id': i, 'desc': policyFiles[i].desc}); } } return result; } this.getPolicy = function(fileId, policyId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } if (policyFiles[fileId].content == null) { readFileContent(fileId); } return getPolicyById(policyFiles[fileId].content, policyId); } this.getPolicyIds = function(fileId, policyId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } if (policyFiles[fileId].content == null) { readFileContent(fileId); } var policySet = getPolicyById(policyFiles[fileId].content, policyId); var result = new Array(); if(policySet['policy']) { for(var i in policySet['policy']) { result.push(policySet['policy'][i]['$']['id']); } } if(policySet['policy-set']) { for(var i in policySet['policy-set']) { result.push(policySet['policy-set'][i]['$']['id']); } } return result; } this.getTarget = function(fileId, policyId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } if(policyId == null) { return null; } else { var policy = getPolicyById(policyFiles[fileId].content, policyId); if(policy == null || policy['target'] == null) { return null; } return(policy['target']); } } this.getRules = function(fileId, policyId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } if(policyId == null) { return null; } else { var policy = getPolicyById(policyFiles[fileId].content, policyId); if(policy == null || policy['rule'] == null) { return null; } return(policy['rule']); } } this.addPolicy = function(fileId, policyId, newPolicyType, newPolicyPoition, newPolicyDescription) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } var policySet = getPolicyById(policyFiles[fileId].content, policyId); if(policySet['$']['type'] != 'policy-set') { return null; } if(newPolicyType != 'policy' && newPolicyType != 'policy-set') { return null; } var newId = getNewId(fileId, newPolicyType); var newPolicy = {'$':{'combine': 'first-matching-target', 'description': newPolicyDescription, 'id': newId, 'type': newPolicyType}}; if(newPolicyType == 'policy') { newPolicy['target'] = [{}]; newPolicy['rule'] = [{'$':{'effect':'deny'}}]; newPolicy['DataHandlingPreferences'] = [{'$':{'PolicyId':'#DHP_allow_all'},'AuthorizationsSet':[{'AuthzUseForPurpose':[{'Purpose':[{}]}]}]}]; newPolicy['ProvisionalActions'] = [{'ProvisionalAction':[{'AttributeValue':['#DHP_allow_all','http://webinos.org']},{'AttributeValue':['#DHP_allow_all','http://www.w3.org']},{'AttributeValue':['#DHP_allow_all','http://wacapps.net']}]}]; } if(newPolicyType == 'policy-set') { newPolicy['policy'] = []; } if(!policySet['policy']) { policySet['policy'] = new Array(); } //TODO: At the moment the new policy is added at the beginning of existing policies... policySet['policy'].unshift(newPolicy); return newId; } this.addSubject = function(fileId, policyId, attribute, match) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } var policy = getPolicyById(policyFiles[fileId].content, policyId); if(policy == null) { return null; } if(policy['target'][0]['subject'] == null) { policy['target'][0] = {'subject':[{'subject-match':[]}]}; } else { removeSub(policy['target'][0]['subject'], attribute); } addSub(policy['target'][0]['subject'], attribute, match); } this.removeSubject = function() { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } var policy = getPolicyById(policyFiles[fileId].content, policyId); if(policy == null) { return null; } } this.addRule = function(fileId, policyId, effect, feature, params) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } //Check if effect is valid value (deny is included in default rule) if(effect != 'permit' && effect != 'prompt-oneshot' && effect != 'prompt-session' && effect != 'prompt-blanket' /*&& effect != 'deny'*/) { return null; } var policy = getPolicyById(policyFiles[fileId].content, policyId); if(policy == null) { return null; } if(policy['$']['type'] != 'policy') { return null; } //TODO: at the moment params are not taken in account //TODO: at the moment only api features are supported - add services //TODO: Check if the feature is already present and remove it for(var i in policy['rule']) { } //TODO where should the new feature be added? Problems of subfeatures and parameters... //Add feature for(var i in policy['rule']) { if(policy['rule'][i]['$']['effect'] == effect) { policy['rule'][i]['condition'][0]['resource-match'].push({'$':{'attr':'api-feature','match':feature}}); return; } } policy['rule'].unshift({'$':{'effect': effect},'condition':[{'$':{'combine':'or'},'resource-match':[{'$':{'attr':'api-feature','match':feature}}]}]}); } this.removePolicy = function(fileId, policyId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } if(policyId == null) { return; } removePolicyById(policyFiles[fileId].content, policyId); } this.save = function(fileId) { updateFileList(); //TODO - VERY IMPORTANT: this function should check policies to verify if selected policy can be accessed //Check if fileId has valid value if(fileId >= policyFiles.length || policyFiles[fileId] == null) { return null; } var policy2save = removeType(JSON.parse(JSON.stringify(policyFiles[fileId].content))); var data = convert2xml('policy-set', policy2save); fs.writeFileSync(policyFiles[fileId].path, data); } };
// Jul/19/2012 // --------------------------------------------------------------- var request = require('request'); var xml2js = require('xml2js'); var text_manipulate = require('/var/www/data_base/common/node_common/text_manipulate'); var xml_manipulate = require('/var/www/data_base/common/node_common/xml_manipulate'); var http_manipulate = require('/var/www/data_base/common/node_common/http_manipulate'); // --------------------------------------------------------------- console.log ("*** 開始 ***"); var id_in = process.argv[2]; var population_in = process.argv[3]; console.log (id_in + "\t" + population_in); var parser = new xml2js.Parser(); var url_src = 'http://host_dbase:8888/xindice/db/cities/cities'; request.get ({uri:url_src, json: true },function (error, response, body) { parser.parseString(body); }); parser.on ('end', function (dict_aa) { dict_aa=text_manipulate.dict_update_proc(dict_aa,id_in,population_in); var out_str = xml_manipulate.dict_to_xml_proc(dict_aa); http_manipulate.put_proc('host_dbase',8888,'/xindice/db/cities/cities',out_str); text_manipulate.dict_display_proc (dict_aa); console.log ("*** 終了 ***")
}, function(err, xml) { if (err) return callback(err); return parser.parseString(xml, function(err, data) { return callback(null, data.GetSessionTokenResult.Credentials); }); });
request.get ({uri:url_src, json: true },function (error, response, body) { parser.parseString(body); });
"makeRes": function makeRes(data) { /* ============================================================================== */ /* = PAGE : Content Usage Rights Info 생성 page = */ /* = -------------------------------------------------------------------------- = */ /* = PallyCon Cloud 서버에서 License를 생성할 때, 필요한 콘텐츠 사용 권한 정보 = */ /* = 를 생성하는 페이지입니다. = */ /* = = */ /* = ※ 중요 = */ /* = Content Usage Rights Info를 생성하는 부분에 업체 정책에 반영됩니다. = */ /* = 상용시에는 반드시 입력해 주셔야 합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = PAGE : Content Usage Rights Info issuance page = */ /* = -------------------------------------------------------------------------- = */ /* = This page generates content usage rights info which will be used by = */ /* = PallyCon Cloud server for license issuance. = */ /* = = */ /* = ※ Note = */ /* = Need to apply your logic to generate Content Usage Rights Info = */ /* = for production service. = */ /* = -------------------------------------------------------------------------- = */ /* = Copyright (c) 2015 INKA Entworks Inc. All Rights Reserverd. = */ /* ============================================================================== */ /* ============================================================================== */ /* = 1. 데이터 설정 = */ /* = -------------------------------------------------------------------------- = */ /* = 1-1. ERROR_CODE/MESSAGE 설정 = */ /* = - ERROR_CODE: 4자리의 숫자로만 구성됩니다. INKA에서 이미 설정된 값을 사용 = */ /* = 합니다. 업체에서 사용되는 에러코드는 정책 반영하는 부분에 = */ /* = 설명되어 있으니 참고 부탁드립니다. = */ /* = ** 0000 은 성공입니다. 다른 값은 에러로 인식됩니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 1-1. ERROR_CODE/MESSAGE setting = */ /* = - ERROR_CODE: 4 digit value. Pre-defined by INKA. = */ /* = The error codes for your service can be set when setting = */ /* = your business rules. = */ /* = ** 0000 means success. Other codes mean failure. = */ /* = -------------------------------------------------------------------------- = */ var ERROR_CODE = "0000"; var MESSAGE = ""; /* = -------------------------------------------------------------------------- = */ /* = 1-2. Content Usage Rights Info, sNonce 설정 = */ /* = - sLIMIT, sPD_START, sPD_END, sPD_COUNT: Content Usage Rights Info 입니다 = */ /* = 업체에서 생성해야 할 값입니다. BM 적용 전에는 = */ /* = CONFIG.php의 값을 사용합니다. = */ /* = - sNonce: PallyCon Cloud Server에서 요청할 때 전달하는 값으로 페이지에서 = */ /* = 응답데이터를 PallyCon Cloud Server로 전달하면, 그 값이 유효한지 = */ /* = 판단합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 1-2. Content Usage Rights Info, sNonce settings = */ /* = - sLIMIT, sPD_START, sPD_END, sPD_COUNT: Content Usage Rights Info = */ /* = These values should be set by service provider. = */ /* = The default test values will be set by CONFIG.php = */ /* = - sNonce: A value which will be used for authentication of response. = */ /* = It will be passed in a request from PallyCon Cloud server = */ /* = and checked by PallyCon Cloud server in a response data. = */ /* = -------------------------------------------------------------------------- = */ var sLIMIT = ""; var sPD_START = ""; var sPD_END = ""; var sPD_COUNT = ""; var sNonce = ""; /* = -------------------------------------------------------------------------- = */ /* = 1-3. sResponse: PallyCon Cloud Server로 전달하는 응답값입니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 1-3. sResponse: response data to PallyCon Cloud Server = */ /* = -------------------------------------------------------------------------- = */ var sResponse = ""; /* = -------------------------------------------------------------------------- = */ /* = 1. 데이터 설정 END / End of data setting = */ /* ============================================================================== */ /* ============================================================================== */ /* = 2. REQUEST DATA 파싱 / Parsing request data = */ /* = -------------------------------------------------------------------------- = */ /* = 2-1. REQUEST DATA에서 data의 값을 추출합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 2-1. Get data from REQUEST = */ /* = -------------------------------------------------------------------------- = */ var sData = ""; if (data) { sData = data; console.log("[Encrypted String]: " + sData); } /* = -------------------------------------------------------------------------- = */ /* = 2-2. 추출에 실패할 경우 에러코드와 메시지를 설정합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 2-2. Set error code and message if failed to parse data = */ /* = -------------------------------------------------------------------------- = */ else { ERROR_CODE = "2201"; MESSAGE = "NO DATA"; console.log("[ERROR]: " + ERROR_CODE + "\n[MESSAGE]: " + MESSAGE); } /* = -------------------------------------------------------------------------- = */ /* = 2. REQUEST DATA 파싱 END / End of parsing request data = */ /* ============================================================================== */ /* ============================================================================== */ /* = 3. REQUEST DATA 복호화 / Decrypt request data = */ /* = -------------------------------------------------------------------------- = */ /* = -------------------------------------------------------------------------- = */ /* = 3-1. ERROR_CODE 값이 성공이면 복호화를 시작합니다. = */ /* = 복호화에 실패할 경우 에러코드와 메시지를 설정합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 3-1. Starting decryption if ERROR_CODE is 'success'. = */ /* = Set error code and message if failed to decrypt. = */ /* = -------------------------------------------------------------------------- = */ var sDecrypted = ""; if (ERROR_CODE == "0000") { sDecrypted = makeDrm.decrypt(sData); if (sDecrypted) { console.log("[Decrypted String]: " + sDecrypted); } else { ERROR_CODE = "2202"; MESSAGE = "Fail to Decrypt the data"; console.log("[ERROR]: " + ERROR_CODE + "\n[MESSAGE]: " + MESSAGE); } } /* = -------------------------------------------------------------------------- = */ /* = 3. REQUEST DATA 복호화 END / End of decrypting request data = */ /* ============================================================================== */ /* ============================================================================== */ /* = 4. XML 파싱 / XML Parsing = */ /* = -------------------------------------------------------------------------- = */ /* = -------------------------------------------------------------------------- = */ /* = 4-1. ERROR_CODE 값이 성공이면 XML을 파싱합니다. = */ /* = XML 파싱에 실패할 경우 에러코드와 메시지를 설정합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = 4-1. Starts XML parsing if ERROR_CODE is 'success'. = */ /* = Set error code and message if failed to parse XML. = */ /* = -------------------------------------------------------------------------- = */ var sJsonResult; if (ERROR_CODE == "0000") { if(makeDrm.getAPIType() == "XML") { xmlparser.parseString(sDecrypted, function(err, result) { console.log('XML Value] :' + result); if (err) { ERROR_CODE = "2203"; MESSAGE = "Fail to Parse XML"; console.log("[ERROR]: " + ERROR_CODE + "[MESSAGE]: " + MESSAGE); } else { console.log('[XML-JSON Result] ' + JSON.stringify(result)); sJsonResult = result; sNonce = sJsonResult.RES.NONCE; } }); } else { // JSON type sJsonResult = JSON.parse(sDecrypted); sNonce = sJsonResult.nonce; } } /* = -------------------------------------------------------------------------- = */ /* = 4. XML 파싱 END / End of XML parsing = */ /* ============================================================================== */ /* ============================================================================== */ /* = 5. Content Usage Rightes Info 생성 / Content Usage Right Info generation = */ /* = = */ /* = ※ 중요 : 업체의 정책을 반영하는 곳입니다. = */ /* = ※ Note : Need to apply your CID generation rule here = */ /* = = */ /* = -------------------------------------------------------------------------- = */ /* = 5-1. ERROR_CODE 값이 성공이면 Content Usage Rights Info 생성을 시작합니다 = */ /* = -------------------------------------------------------------------------- = */ /* = 5-1. Starts generating Content ID if ERROR_CODE is 'success'. = */ /* = -------------------------------------------------------------------------- = */ if (ERROR_CODE == "0000") { /*- * * [업체 청책 반영] * * 업체의 정책에 맞게 Content Usage Rights Info를 생성하는 로직을 이곳에 구현합니다. * Content Usage Rights Info를 생성하는데 활용할 값은 다음과 같습니다. * * - sUserID * - sCID * - sPDID * - sDeviceModel * - sOID * * ** BM 적용 전에는 위 값들을 CONFIG.php에서 정의된 값들로 설정됩니다. * * ERROR_CODE는 성공일 경우 "0000"을 유지 시켜줍니다. * * * [Applying Content Usage Rights rule] * * Your Usage Rule generation logic can be applied here. * The below parameters can be used for the logic. * * - sUserID * - sCID * - sPDID * - sDeviceModel * - sOID * * ** The default test values are defined in CONFIG.php. * * ERROR_CODE "0000" means success. * */ var sUserID, sCID, sDeviceID, sDeviceModel, sDeviceType, sOID, sDrmType; if(makeDrm.getAPIType() == "XML") { sUserID = sJsonResult.RES.USERID.toString(); // 클라이언트에서 추출한 사용자 아이디 sCID = sJsonResult.RES.CID.toString(); // 클라이언트에서 추출한 콘텐츠의 Content ID sDeviceID = sJsonResult.RES.DEVICEID.toString(); // 클라이언트에서 추출한 기기 아이디 sDeviceModel = sJsonResult.RES.DEVICEMODEL.toString(); // 클라이언트에서 추출한 기기 모델 sOID = sJsonResult.RES.OID.toString(); // 클라이언트에서 추출한 콘텐츠 구매 정보 (Order ID) } else { // JSON type sUserID = sJsonResult.user_id; // 클라이언트에서 추출한 사용자 아이디 sCID = sJsonResult.cid; // 클라이언트에서 추출한 콘텐츠의 Content ID sDeviceID = sJsonResult.device_id; // 클라이언트에서 추출한 기기 아이디 sDeviceType = sJsonResult.device_type; // 클라이언트 기기 유형 sOID = sJsonResult.oid; // 클라이언트에서 추출한 콘텐츠 구매 정보 (Order ID) sDrmType = sJsonResult.drm_type; } // User ID 체크 로직 ('valid-user'로 하드코딩..) if (sUserID == "valid-user") { ERROR_CODE = "0000"; // 테스트용 기본 라이선스 데이터 (Unlimited license) sLIMIT = "N"; sPD_START = ""; sPD_END = ""; sPD_COUNT = 0; } else { ERROR_CODE = "4321"; MESSAGE = "Not a valid user ID: " + sUserID; console.log("[ERROR]: " + ERROR_CODE + "\n[MESSAGE]: " + MESSAGE); } } /* = -------------------------------------------------------------------------- = */ /* = 5. Content Usage Rightes Info 생성 END / End of generation = */ /* ============================================================================== */ if(makeDrm.getAPIType() == "XML") { /* ============================================================================== */ /* = 6. 응답 데이타 생성 [XML] / Generating response data [XML] = */ /* = -------------------------------------------------------------------------- = */ /* = Content Usage Info 생성 성공 여부에 따른 XML 값을 생성하여 전달합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = Creates and responds XML data with Content Usage Info generation result = */ /* = -------------------------------------------------------------------------- = */ sResponse = "<?xml version='1.0' encoding='utf-8'?><RES>"; sResponse += "<ERROR>" + ERROR_CODE + "</ERROR>"; /* = -------------------------------------------------------------------------- = */ /* = 6-1. ERROR_CODE 값이 성공이 아닐 경우 MESSAGE를 Content Usage Rights = */ /* = Info대신 추가 = */ /* = -------------------------------------------------------------------------- = */ /* = 6-1. Adds error message if ERROR_CODE is not 'success' = */ /* = -------------------------------------------------------------------------- = */ if (ERROR_CODE != "0000") { sResponse += "<ERRMSG>" + MESSAGE + "</ERRMSG>"; } /* = -------------------------------------------------------------------------- = */ /* = 6-2. ERROR_CODE 값이 성공일 경우 Content Usage Rights Info 값을 추가 = */ /* = -------------------------------------------------------------------------- = */ /* = 6-2. Adds Content Usage Rights Info if ERROR_CODE is 'success' = */ /* = -------------------------------------------------------------------------- = */ else { sResponse += "<LIMIT>" + sLIMIT + "</LIMIT>"; sResponse += "<PD_COUNT>" + sPD_COUNT + "</PD_COUNT>"; sResponse += "<PD_START>" + sPD_START + "</PD_START>"; sResponse += "<PD_END>" + sPD_END + "</PD_END>"; } sResponse += "<NONCE>" + sNonce + "</NONCE>"; sResponse += "</RES>"; console.log("[Result XML]: " + sResponse); /* = -------------------------------------------------------------------------- = */ /* = 6. 응답 데이타 생성 [XML] END / End of response data generation [XML] = */ /* ============================================================================== */ } else { var jsonResponse = { "error_code": ERROR_CODE, "error_message": MESSAGE, "playback_policy": { "limit": false, "persistent": true, "duration": 0, "expire_date": "" }, "nonce": sNonce }; sResponse = JSON.stringify(jsonResponse); console.log("[Result JSON]: " + sResponse); } /* ============================================================================== */ /* = 7. 응답 데이타 암호화 / Encryption of response data = */ /* = -------------------------------------------------------------------------- = */ /* = XML 값을 생성하여 반환합니다. = */ /* = -------------------------------------------------------------------------- = */ /* = Encrypts XML data to respond = */ /* = -------------------------------------------------------------------------- = */ var sEncrypted = makeDrm.encrypt(sResponse); console.log("[Encrypted DATA]: " + sEncrypted); return sEncrypted; /* = -------------------------------------------------------------------------- = */ /* = 7. 응답 데이타 암호화 END / End of response data encryption = */ /* ============================================================================== */ }
SAML.prototype.validateResponse = function (samlResponse, callback) { var self = this; var xml = new Buffer(samlResponse, 'base64').toString(); var samlAssertion = null; // Verify signature on the response if (self.options.cert && !self.validateSignature(xml, self.options.cert)) { return callback(new Error('Invalid signature'), null, false); } var xmlDomDoc = new xmldom.DOMParser().parseFromString(xml); //Check Status code in the SAML Response var statusObj = self.checkSAMLStatus(xmlDomDoc); if(statusObj.StatusCodeValue != "urn:oasis:names:tc:SAML:2.0:status:Success") return callback(new Error('SAML Error Response:\nStatusCodeValue = '+ statusObj.StatusCodeValue + '\nStatusMessage = ' + statusObj.StatusMessage + '\nStatusDetail = ' + statusObj.StatusDetail + '\n'), null, false); // Decrypt and Retrieve SAML Assertion if (self.options.encryptedSAML && self.options.privateCert) { samlAssertion = self.decryptSAMLAssertion(xmlDomDoc, self.options.privateCert); if (!samlAssertion){ return callback(new Error('Decryption Failed'), null, false); } else //trim the unwanted characters after closing </saml:Assertion> { var nIndex = samlAssertion.indexOf("</saml:Assertion>"); var validStringLen = nIndex + 17; samlAssertion = samlAssertion.slice(0, validStringLen); } // console.log(samlAssertion); // Verify signature on the decrypted assertion if (self.options.cert && !self.validateSignature(samlAssertion, self.options.cert)) { return callback(new Error('Invalid signature'), null, false); } } else //Retrieve SAML Assertion { samlAssertionNode = xmlCrypto.xpath(xmlDomDoc, "//*[local-name(.)='Assertion']")[0]; if (samlAssertionNode) { samlAssertion = samlAssertionNode.toString(); } else { return callback(new Error('Missing Assertion'), null, false); } } var parser = new xml2js.Parser({explicitRoot:true}); parser.parseString(samlAssertion, function (err, doc) { var assertion = self.getElement(doc, 'Assertion'); if (assertion) { /* if (!assertion) { return callback(new Error('Missing SAML assertion'), null, false); } */ profile = {}; var issuer = self.getElement(assertion, 'Issuer'); if (issuer) { profile.issuer = issuer[0]; } var subject = self.getElement(assertion, 'Subject'); if (subject) { var nameID = self.getElement(subject[0], 'NameID'); if (nameID) { profile.nameID = nameID[0]["_"]; if (nameID[0]['$'].Format) { profile.nameIDFormat = nameID[0]['$'].Format; } } } var attributeStatement = self.getElement(assertion, 'AttributeStatement'); if (!attributeStatement) { return callback(new Error('Missing AttributeStatement'), null, false); } var attributes = self.getElement(attributeStatement[0], 'Attribute'); if (attributes) { attributes.forEach(function (attribute) { var value = self.getElement(attribute, 'AttributeValue'); if (typeof value[0] === 'string') { profile[attribute['$'].Name] = value[0]; } else { profile[attribute['$'].Name] = value[0]['_']; } }); } if (!profile.mail && profile['urn:oid:0.9.2342.19200300.100.1.3']) { // See http://www.incommonfederation.org/attributesummary.html for definition of attribute OIDs profile.mail = profile['urn:oid:0.9.2342.19200300.100.1.3']; } if (!profile.email && profile.mail) { profile.email = profile.mail; } callback(null, profile, false); } else { var logoutResponse = self.getElement(doc, 'LogoutResponse'); if (logoutResponse){ callback(null, null, true); } else { return callback(new Error('Unknown SAML response message'), null, false); } } }); };
exports.GetKulBindingInfo = function(data){ var kul_fname = data.parameters.kul_fname; function is_binding(prop_name) { if(prop_name == 'simple_bind' || prop_name == 'valid_bind' || prop_name == 'list_bind' || prop_name == 'index1_bind' || prop_name == 'range_bind' || prop_name == 'table_bind' || prop_name == 'index2_bind' || prop_name == 'enable_bind' || prop_name == 'visible_bind' || prop_name == 'handle_bind') { return true; } return false; } function is_event(prop_name) { if(prop_name == 'onClick' || prop_name == 'onDoubleClick' || prop_name == 'onChange' || prop_name == 'onHotKey' || prop_name == 'onHeaderClick') { return true; } return false; } function json_wrap(jsontree) { var ret = []; function json(jsontree) { if ((typeof jsontree == 'object') && (jsontree.constructor== Object.prototype.constructor)) { var arrey = []; arrey.push(jsontree); } else arrey = jsontree; for (var i = 0; i < arrey.length; i++) { var jn = arrey[i]; if(jn.property != undefined) { for(var loop = 0; loop < jn.property.length; ++loop) { var prop_name = jn.property[loop].$.name; var prop_value = jn.property[loop]._; if(is_binding(prop_name) && prop_value != undefined) { ret.push(prop_value); } } if (jn.widget && jn.widget.length > 0) { json(jn.widget); } } } } function json_binding_block(jsontree) { //console.log(JSON.stringify(jsontree)); //fs.writeFileSync("y:\\abc.json", JSON.stringify(jsontree)); if ((typeof jsontree == 'object') && (jsontree.constructor== Object.prototype.constructor)) { var arrey = []; arrey.push(jsontree); } else arrey = jsontree; for (var i = 0; i < arrey.length; i++) { var jn = arrey[i]; //console.log(JSON.stringify(jn)); if(jn.binding != undefined) { for(var loop = 0; loop < jn.binding.length; ++loop) { var prop_name = jn.binding[loop].$.name; var prop_value = jn.binding[loop]._; if(prop_value != undefined) { ret.push(prop_value); } } } if (jn.widget && jn.widget.length > 0) { json_binding_block(jn.widget); } } } json(jsontree); json_binding_block(jsontree); return ret; } var parser = new xml2js.Parser(); parser.addListener('end', function(result) { var ret = json_wrap(result.kul_pkg.widget); if(ret.length != 0) { data.parameters = ret; websocket.send(data); } //console.log(json_content); }); fs.readFile(kul_fname, function(err, data) { parser.parseString(data); }); };
/* Register feature string with URL */ capStr += " rbac.setFeatureByURL(" + "'" + itemList[i]['url'] + "'"; capStr += ", " + "'" + method + "'" + ", " + "app.routes, " + "'" + itemList[i]['feature'] + "'" + ");\n"; } urlCbStr += "\n"; urlCbStr += "\n"; urlCbStr += capStr; urlCbStr += "}\n"; urlCbStr += longPollArrStr; fs.writeFile(__dirname + '/../serverroot/web/routes/url.routes.js', urlCbStr, function(err) { if (err) throw err; }); } var parser = new xml2js.Parser(); parser.addListener('end', function(result) { /* Create new file and add this info */ createFile(result); console.log("Done, creating file: " + __dirname + '/../serverroot/web/routes/url.routes.js'); }); fs.readFile(__dirname + '/../xml/parseURL.xml', function(err, data) { parser.parseString(data); });
exports.GetKulEntryInfo = function(data){ var unit_name = data.parameters.unit_name; var unit_entry_filename = "y:\\" + unit_name + "\\kul\\kul.entry.xml"; //var json_fname = "y:\\" + unit_name + "\\kul\\kul.entry.json"; function json_wrap(jsontree) { var ret = {events : [], bindings : [], events_hdr : [], bindings_hdr : [], events_type : [], bindings_type : []}; function json(jsontree) { if ((typeof jsontree == 'object') && (jsontree.constructor== Object.prototype.constructor)) { var arrey = []; arrey.push(jsontree); } else arrey = jsontree; for (var i = 0; i < arrey.length; i++) { var jn = arrey[i]; if(jn.property != undefined) { var bIsEvent = false; var bIsBinding = false; var bind_hdr = ""; for(var loop = 0; loop < jn.property.length; ++loop) { var prop_name = jn.property[loop].$.name; var prop_value = jn.property[loop]._; if(prop_name == "handle_bind") { bind_hdr = prop_value; } } for(var loop = 0; loop < jn.property.length; ++loop) { var prop_name = jn.property[loop].$.name; var prop_value = jn.property[loop]._; if(is_binding(prop_name) && prop_value != undefined) { ret.bindings.push(prop_value); ret.bindings_type.push(prop_name); ret.bindings_hdr.push(bind_hdr); bIsBinding = true; } if(is_event(prop_name) && prop_value != undefined) { ret.events.push(prop_value); ret.events_type.push(prop_name); ret.events_hdr.push(bind_hdr); bIsEvent = true; } } if (jn.widget && jn.widget.length > 0) { json(jn.widget); } } } } json(jsontree); return ret; } var parser = new xml2js.Parser(); parser.addListener('end', function(result) { //var json_content = []; var json_content = []; //var ret = json_wrap(result.kul_pkg.widget); //fs.writeFileSync(json_fname, JSON.stringify(ret)); if(result.kul_pkg.blockid != undefined) { for(var loop = 0; loop < result.kul_pkg.blockid.length; ++loop) { var pkgid_obj = result.kul_pkg.blockid[loop]; var pkg_name = pkgid_obj.$.name; var pkg_kulfile = pkgid_obj.location[0]; pkg_kulfile = "y:/" + unit_name + "/kul/" + pkg_kulfile; json_content.push({"name" : pkg_name, "kul_filepath" : pkg_kulfile, "is_block" : true, "id" : ""}); } } for(var loop = 0; loop < result.kul_pkg.pkgid.length; ++loop) { var pkgid_obj = result.kul_pkg.pkgid[loop]; var pkg_name = pkgid_obj.$.name; var pkg_kulfile = pkgid_obj.location[0]; pkg_kulfile = "y:/" + unit_name + "/kul/" + pkg_kulfile; var parser_sub = new xml2js.Parser(); parser_sub.addListener('end', function(result_sub){ //fs.writeFileSync("y:\\abc.json", JSON.stringify(result_sub)); if(result_sub.kul_pkg.widget != undefined) { var js_filepath = result_sub.kul_pkg.widget[0].$.name + ".js"; var id = ""; //console.log(js_filepath); for(var loop_sub = 0; loop_sub < result_sub.kul_pkg.widget[0].property.length; ++loop_sub) { if(result_sub.kul_pkg.widget[0].property[loop_sub].$.name == "javascript") { js_filepath = result_sub.kul_pkg.widget[0].property[loop_sub]._; //console.log(js_filepath); } if(result_sub.kul_pkg.widget[0].property[loop_sub].$.name == "id") { id = result_sub.kul_pkg.widget[0].property[loop_sub]._; //console.log(js_filepath); } } js_filepath = "y:/" + unit_name + "/js/" + js_filepath; json_content.push({"name" : pkg_name, "kul_filepath" : pkg_kulfile, "js_filepath" : js_filepath, "is_block" : false, "id" : id}); } if(loop +1 == result.kul_pkg.pkgid.length) { //console.log(JSON.stringify(json_content)); //fs.writeFileSync(json_fname, JSON.stringify(json_content)); data.parameters = json_content; websocket.send(data); } }); //fs.readFile(block_fpath, function(err, data){ // parser_sub.parseString(data); //}); //console.log(pkg_kulfile); if(fs.existsSync(pkg_kulfile)) { parser_sub.parseString(fs.readFileSync(pkg_kulfile)); } } }); if(fs.existsSync(unit_entry_filename)) { fs.readFile(unit_entry_filename, function(err, data) { parser.parseString(data); }); } else { data.parameters = []; websocket.send(data); } };
fs.readFile(__dirname + '/../xml/parseURL.xml', function(err, data) { parser.parseString(data); });
self.request( options, function(err, res) { // an error with the request is an error full-stop if ( err ) { callback({ Code : 'AwsSum-Request', Message : 'Something went wrong during the request', OriginalError : err }, null); // console.log('CALLBACK: failed due to error from request'); return; } if ( debug ) { console.log('-------------------------------------------------------------------------------'); console.log('Response:'); console.log('- statusCode :', res.statusCode); console.log('- headers :', res.headers); console.log('- body :', res.body.toString()); console.log('-------------------------------------------------------------------------------'); } // save the whole result in here var result = {}; // (1) add the status code first result.StatusCode = res.statusCode; // (2) add some headers into the result if ( extractHeaders ) { // this should be removed in favour of a regex option if ( extractHeaders === 'x-amz' ) { result.Headers = {}; _.each(res.headers, function(val, hdr) { if ( hdr.match(/^x-amz-/) ) { // ToDo: it'd be nice if we convert things like: // x-amz-request-id -> RequestId // x-amz-id-2 -> Id2 // x-amz-server-side-encryption -> ServerSideEncryption // x-amz-version-id -> VersionId result.Headers[hdr] = val; } }); } else if ( _.isRegExp(extractHeaders) ) { result.Headers = {}; _.each(res.headers, function(val, hdr) { if ( hdr.match(extractHeaders) ) { result.Headers[hdr] = val; } }); } else if ( Array.isArray(extractHeaders) ) { // just return the headers that are in this list result.Headers = {}; extractHeaders.forEach(function(v) { result.Headers[v] = res.headers[v]; }); } else if ( _.isObject(extractHeaders) ) { // just return the headers that are in this list result.Headers = {}; _.each(extractHeaders, function(v, k) { result.Headers[k] = res.headers[k]; }); } else if ( _.isFunction(extractHeaders) ) { // this should return a hash of headers result.Headers = extractHeaders.apply(self, [ res ]); } else if ( extractHeaders === true ) { // extract _all_ headers result.Headers = res.headers; } } // else, don't extract any headers // (3) we may extract the body differently depending on the status code // // It seems the following services can do this: // // * Amazon S3 // * Amazon DynamoDB // * Amazon SWF // see if this is not a valid statusCode if ( ! isStatusCodeOk(statusCode, res.statusCode) ) { extractBody = extractBodyWhenError; } // now extract the body // create the result and parse various things into it if ( extractBody === 'xml' ) { // decode the returned XML var ok = true; // Note: parseString is synchronous (not async) parser.parseString(res.body.toString(), function (err, data) { if ( err ) { result.Code = 'AwsSum-ParseXml'; result.Message = 'Something went wrong during the XML parsing'; result.Error = err; result.Body = res.body.toString(); } else { result.Body = data; } }); // see if the xml parsing worked if ( !result.Body ) { callback(result, null); return; } } else if ( extractBody === 'json' ) { // get the JSON (should this be in a try/catch?) result.Body = JSON.parse(res.body.toString()); } else if ( extractBody === 'blob' ) { // just return the body result.Body = res.body; } else if ( extractBody === 'application/x-www-form-urlencoded' ) { // decode the body and return it result.Body = decodeWwwFormUrlEncoded(res.body); } else if ( extractBody === 'none' ) { // no body, so just set a blank one result.Body = ''; } else if ( extractBody === 'string' ) { // convert the body to a string result.Body = res.body.toString(); } else if ( typeof extractBody === 'function' ) { result.Body = extractBody.apply(self, [ res ]); } else { // shouldn't ever be here since extractBody is checked above throw new Error("Program Error: Shouldn't ever be here"); } // now we're ready to finally call the callback!!! :D if ( ! isStatusCodeOk(statusCode, res.statusCode) ) { // this was an error // console.log('CALLBACK: failed due to incorrect statusCode'); callback(result, null); return; } // everything so far looks fine, callback with the result // console.log('CALLBACK: success'); callback(null, result); });
module.exports = function( ss_key, auth_id, options ){ var self = this; var google_auth = null; var visibility = "public"; var projection = "values"; this.setAuthAndDependencies = function( auth ) { google_auth = auth; if ( options!=null && "visibility" in options ) { visibility = options.visibility; } else { visibility = google_auth ? 'private' : 'public'; } if ( options!=null && "projection" in options ) { projection = options.projection; } else { projection = google_auth ? 'full' : 'values'; } } var xml_parser = new xml2js.Parser({ // options carried over from older version of xml2js -- might want to update how the code works, but for now this is fine explicitArray: false, explicitRoot: false, }); if ( !ss_key ) { throw new Error("Spreadsheet key not provided."); } if ( auth_id ){ self.setAuthAndDependencies(auth_id) } this.setAuthId = function(auth_id) { self.setAuthAndDependencies(auth_id); } this.setAuth = function( username, password, cb ){ var new_auth = new GoogleClientLogin({ email: username, password: password, service: 'spreadsheets', accountType: GoogleClientLogin.accountTypes.google }) new_auth.on(GoogleClientLogin.events.login, function(){ self.setAuthAndDependencies(new_auth.getAuthId()); cb( null, new_auth ); }) new_auth.on(GoogleClientLogin.events.error, function(err){ cb( err ); }) new_auth.login(); } this.getInfo = function( cb ){ self.makeFeedRequest( ["worksheets", ss_key], 'GET', null, function(err, data, xml) { if ( err ) return cb( err ); if (data===true) { return cb(new Error('No response to getInfo call')) } var ss_data = { title: data.title["_"], updated: data.updated, author: data.author, worksheets: [] } var worksheets = forceArray(data.entry); worksheets.forEach( function( ws_data ) { ss_data.worksheets.push( new SpreadsheetWorksheet( self, ws_data ) ); }) cb( null, ss_data ); }); } this.getRows = function( worksheet_id, opts, query, cb ){ // the first row is used as titles/keys and is not included // opts is optional if ( typeof( opts ) == 'function' ){ cb = opts; opts = {}; query = {}; // so is query } else if ( typeof( query ) == 'function' ){ cb = query; query = {}; } if ( opts.start ) query["start-index"] = opts.start; if ( opts.num ) query["max-results"] = opts.num; if ( opts.orderby ) query["orderby"] = opts.orderby; if ( opts.reverse ) query["reverse"] = opts.reverse; self.makeFeedRequest( ["list", ss_key, worksheet_id], 'GET', query, function(err, data, xml) { if ( err ) return cb( err ); if (data===true) { return cb(new Error('No response to getRows call')) } // gets the raw xml for each entry -- this is passed to the row object so we can do updates on it later var entries_xml = xml.match(/<entry[^>]*>([\s\S]*?)<\/entry>/g); var rows = []; var entries = forceArray( data.entry ); var i=0; entries.forEach( function( row_data ) { rows.push( new SpreadsheetRow( self, row_data, entries_xml[ i++ ] ) ); }); cb(null, rows); }); } this.addRow = function( worksheet_id, data, cb ){ worksheet_id = parseInt(worksheet_id); if (typeof worksheet_id !== 'number' || worksheet_id < 0) { throw new Error('Valid worksheet not specified.'); } var data_xml = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">' + "\n"; Object.keys(data).forEach(function(key) { if (key != 'id' && key != 'title' && key != 'content' && key != '_links'){ data_xml += '<gsx:'+ xmlSafeColumnName(key) + '>' + xmlSafeValue(data[key]) + '</gsx:'+ xmlSafeColumnName(key) + '>' + "\n" } }); data_xml += '</entry>'; self.makeFeedRequest( ["list", ss_key, worksheet_id], 'POST', data_xml, cb ); } this.getCells = function (worksheet_id, opts, cb) { // opts is optional if (typeof( opts ) == 'function') { cb = opts; opts = {}; } var query = {}; if (opts.minRow) query["min-row"] = opts.minRow; if (opts.maxRow) query["max-row"] = opts.maxRow; if (opts.minCol) query["min-col"] = opts.minCol; if (opts.maxCol) query["max-col"] = opts.maxCol; if (opts.returnEmpty) query["return-empty"] = opts.returnEmpty; self.makeFeedRequest(["cells", ss_key, worksheet_id], 'GET', query, function (err, data, xml) { if (err) return cb(err); if (data===true) { return cb(new Error('No response to getCells call')) } var cells = []; var entries = forceArray(data['entry']); var i = 0; entries.forEach(function( cell_data ){ cells.push( new SpreadsheetCell( self, worksheet_id, cell_data ) ); }); cb( null, cells ); }); } this.makeFeedRequest = function( url_params, method, query_or_data, cb ){ var url; var headers = {}; if (!cb ) cb = function(){}; if ( typeof(url_params) == 'string' ) { // used for edit / delete requests url = url_params; } else if ( Array.isArray( url_params )){ //used for get and post requets url_params.push( visibility, projection ); url = GOOGLE_FEED_URL + url_params.join("/"); } if ( google_auth ) { if (google_auth.type === 'Bearer') { headers['Authorization'] = 'Bearer ' + google_auth.value; } else { headers['Authorization'] = "GoogleLogin auth=" + google_auth; } } if ( method == 'POST' || method == 'PUT' ){ headers['content-type'] = 'application/atom+xml'; } if ( method == 'GET' && query_or_data ) { url += "?" + querystring.stringify( query_or_data ); } request( { url: url, method: method, headers: headers, body: method == 'POST' || method == 'PUT' ? query_or_data : null }, function(err, response, body){ if (err) { return cb( err ); } else if( response.statusCode === 401 ) { return cb( new Error("Invalid authorization key.")); } else if ( response.statusCode >= 400 ) { // console.log( body ); return cb( new Error("HTTP error " + response.statusCode + ": " + http.STATUS_CODES[response.statusCode]) + " "+JSON.stringify(body)); } if ( body ){ xml_parser.parseString(body, function(err, result){ if ( err ) return cb( err ); cb( null, result, body ); }); } else { if ( err ) cb( err ); else cb( null, true ); } }) } };
function uploadFinished(responseData) { var parser = new xml2js.Parser(); parser.parseString(responseData.toString(), function(error, data) { conf.onUpload && conf.onUpload(data.PostResponse); }); }
compile: function(options){ // options should always be an object options = options || {}; // Since this method is async, let's setup a promise var deferred = Q.defer(); // parse the web.config using `xml2js` var parser = new xml2js.Parser(); // If the sources options is not an array, let's make it one to normalize if(!_.isArray(options.sources)){ options.sources = [options.sources]; } // Declare our destination settings object. This will be what we return var compiledWebConfig = { sources:[], appSettings: { }, applicationSettings: { } }; // Read all the contents of the web.config async.each(options.sources, function(source, done){ // let's read config file fs.readFile(source, function (err, data) { // Using the parser convert the XML to a JavaScript object parser.parseString(data, function (err, result) { // If an error occurred, reject the promise if (err) { done(err); return; } // Add the xml2js result to the compiled web config sources compiledWebConfig.sources.push(result); // The translated JavaScript object from the xml is really ugly and hard to work with. // Let's look for what we want in it and put the setting in key-value pairs. // Get the array of appSettings from the parsed web.config if(result.configuration["appSettings"] && result.configuration["appSettings"][0]) { var appSettings = result.configuration["appSettings"][0]['add']; // Loop through the translated appSettings _.each(appSettings, function (xmlSetting) { // Extract the names and values var appSetting = xmlSetting['$']; var settingName = appSetting.key; var settingValue = appSetting.value; // Put the setting in our applicationSettings object compiledWebConfig.appSettings[settingName] = settingValue; }); } // Get the array of applicationSettings from the parsed web.config if(result.configuration["applicationSettings"] && result.configuration["applicationSettings"][0]) { var applicationSettingsObject = result.configuration["applicationSettings"][0]; var applicationSettingStore = _(applicationSettingsObject).keys().first(); var applicationSettings = applicationSettingsObject[applicationSettingStore][0]['setting']; // Loop through the translated _.each(applicationSettings, function (xmlSetting) { // Extract the names and values var applicationSetting = xmlSetting['$']; var settingName = applicationSetting.name; var settingValue = xmlSetting['value'][0]; // Put the setting in our applicationSettings object compiledWebConfig.applicationSettings[settingName] = settingValue; }); } // Move to next item in async queue done(); }); }); }, function(err){ // If an error occurred, reject the promise if (err) { deferred.reject(err); return; } // If there is an override for applicationSettings, then extend the applicationSettings from the `compiledWebConfig` if(options.applicationSettings){ _.extend(compiledWebConfig.applicationSettings, options.applicationSettings); } // If there is an override for appSettings, then extend the appSettings from the `compiledWebConfig` if(options.appSettings){ _.extend(compiledWebConfig.appSettings, options.appSettings); } // Resolve the promise and return our nice settings object deferred.resolve(compiledWebConfig); }); // Return our promise return deferred.promise; }
add(filename, description, function (err, resp, body) { // save the body as a file in the current directory xmlparser.parseString(body, function (err, result) { return callback(err,result); }); });
function _Callback(error, response){ //logfct('callback '+currentStep + ' '+JSON.stringify(error)+' '+JSON.stringify(response)); if (error){ //means not found if ((currentStep==stepGetSageStorageAccount) || (currentStep==stepGetImage) || (currentStep==stepGetDeployment) || (currentStep==stepGetCloudService) || (currentStep==stepExecuteExtensionScript)) { _Next(); } else { logfct(error); logfct(response); return callback(1,null,error); } } else { if (currentStep==stepGetSageStorageAccount){ _Skip(); return _Next(); } if (currentStep==stepGetStorageAccountKeys){ //logfct(response.body); if (response.body.StorageServiceKeys) { primaryKey = response.body.StorageServiceKeys.Primary; logfct('primary key is '+primaryKey); //secondaryKey = response.body.StorageServiceKeys.Secondary; return _Next(); }else{ return callback(1,null,'No storage account keys found'); } } if (currentStep==stepGetContainer){ if (response.length==0){ return _Next(); }else{ for (i=0;i<response.length;i++) { if (response[i].name==sagecontainer){ logfct('Container '+sagecontainer+' already exists, skip creation'); _Skip(); return _Next(); } } return _Next(); } } if (currentStep==stepGetBlob){ for (i=0;i<response.length;i++) { if (response[i].name==sageblobname){ blobUrl = response[i].url; logfct('Blob '+sageblobname+' already exists, skip creation'); _Skip(); return _Next();//blob already exists } } return _Next();//copy blob } if (currentStep==stepCopyBlob){ function _CheckBlob(){ try{ logfct('Check if blob is created'); blobService.getBlobProperties(sagecontainer,sageblobname,function(error,response){ cpt++; if (cpt==500){throw "blob copy time out"}; if (error){ clearInterval(timer); throw error; } else { if (response){ if (response.copyStatus=='pending'){ logfct('copy progress ' + response.copyProgress);//progress } else { if (response.copyStatus=='success'){ clearInterval(timer); _Previous();//get blob url } else { throw "error copying blob "+response; } } } } }); } catch (err) { clearInterval(timer); throw err; } } azureCopyOperation = response.copyId;//pending var timer = setInterval(_CheckBlob,15000); var cpt = 0; return;//!! attention apres on est plus dans createvm ! } if (currentStep==stepGetImage){ if (response.isSuccessful && response.body){ for (i=0;i<response.body.length;i++){ if ((response.body[i].Category=='User') && (response.body[i].Name==sageImageName)){ logfct('Image '+sageImageName+' already exists, skip creation'); _Skip(); return _Next();//image already exists } } } return _Next(); } if (currentStep==stepGetCloudService){ if (response.isSuccessful && response.body){ for (i=0;i<response.body.length;i++) { if (response.body[i].ServiceName==param.vmData.vmName){ logfct('Cloud Service '+param.vmData.vmName+' already exists, skip creation'); _Skip(); return _Next();//service already exists } } } return _Next(); } if (currentStep==stepGetDatabaseServer){ if (param.accountData.useMaster==true){ sqlServerName = param.accountData.sqlServerName; sqlServerUserName = param.accountData.sqlServerUserName+'@'+sqlServerName; sqlServerPassword = param.accountData.sqlServerPassword; fullSqlServerName = sqlServerName + '.database.windows.net'; logfct('sql server used is ' + sqlServerName); logfct('admin login is ' + sqlServerUserName); _Skip();//stepCreateDatabaseServer _Skip();//stepCreateServerFirewallRule _Skip();//stepCopyMasterDatabase return _Next();//server database have been set by user } } if (currentStep==stepCreateDatabaseServer){ sqlServerName = response; sqlServerUserName = cstSqlAdminLogin+'@'+sqlServerName; fullSqlServerName = sqlServerName + '.database.windows.net'; logfct('sql server used is ' + sqlServerName); logfct('admin login is ' + sqlServerUserName); } if (currentStep==stepGetDeployment){ if (response.isSuccessful && response.body){ if (response.body.Name==param.vmData.vmName){ logfct('Deployment '+param.vmData.vmName+' already exists, skip creation'); _Skip(); return _Next();//deployment already exists } } return _Next(); } if ((currentStep==stepCopyMasterDatabase) || (currentStep==stepCopyBusinessDatabase)){ function _CheckDatabase(){ try{ logfct('Check if database is copied'); host = _LocationToDACWebServiceHost(location); path = '/DACWebService.svc/Status'+ '?servername='+encodeURIComponent(fullSqlServerName)+ '&username='******'&password='******'&reqId='+encodeURIComponent(databaseCopyOperation); var myurl = 'https://'+host+path; logfct(myurl); https.get(myurl, function(res) { res.on('data', function(responsexml) { cpt++; if (cpt==500){throw "database copy time out"}; if (responsexml){ var status; var fullResponse; var parser = new xml2js.Parser();//todo reprendre parser.on('end', function (str) { fullResponse = str; if ((str.ArrayOfStatusInfo!=undefined)&& (str.ArrayOfStatusInfo.StatusInfo[0]!=undefined)&& (str.ArrayOfStatusInfo.StatusInfo[0].Status[0]!=undefined)){ status = str.ArrayOfStatusInfo.StatusInfo[0].Status[0];/*reprendre ce beans*/ } else { throw JSON.stringify(str); } }); parser.parseString(responsexml); if (status=='Failed'){ clearInterval(timer); throw "error copying database "+JSON.stringify(fullResponse); } else { if (status=='Completed'){ clearInterval(timer); logfct('Copy OK'); return _Next(); } else { logfct('Copy in progress'); } } } }); }).on('error', function(e) { //throw e; logfct(JSON.stringify(e)); }); } catch(err){ clearInterval(timer); throw err; } } var parser = new xml2js.Parser(); parser.on('end', function (str) { if ((str.guid!=undefined)&&(str.guid._!=undefined)) {databaseCopyOperation = str.guid._;} else throw JSON.stringify(str);}); parser.parseString(response); var timer = setInterval(_CheckDatabase,30000); var cpt = 0; return;//!! } if (currentStep==(steps.length -1) ){ logfct('Done.'); return callback(0,null,""); } return _Next(); } }