function getPackageInfo( projectName, config, repoInfo ) { var owner; var branch; var commit; var slug; var repoPath; var projectPath; var repoPromise; if( _.isString( repoInfo ) ) { repoPromise = git.repo( repoInfo ) .then( function( info ) { owner = info.owner; branch = info.branch; commit = info.commit; slug = info.slug; projectPath = path.resolve( info.path, config.path ); repoPath = repoInfo; return projectPath; } ); } else { owner = repoInfo.owner; branch = repoInfo.branch; commit = repoInfo.commit; slug = repoInfo.slug; projectPath = path.resolve( repoInfo.path, config.path ); repoPath = repoInfo.path; repoPromise = when( projectPath ); } var versionPromise = config.versionFile ? when.try( git.getCurrentVersion, repoPromise, config.versionFile ) : when.try( git.getCurrentVersion, repoPromise ); var buildPromise = config.versionFile ? when.try( git.getCommitsSinceCurrentVersion, repoPromise, config.versionFile ) : when.try( git.getBuildNumber, repoPromise ); return when.try( function( version, build ) { if( !version || !build ) { debug( "No versions found for project \"" + projectName + "\" at \"" + projectPath + "\". Using \"0.0.0\"." ); version = "0.0.0"; build = 0; } var packageName = _.filter( [ projectName, owner, branch, slug, version, build, sysInfo.platform, sysInfo.osName, sysInfo.osVersion, sysInfo.arch ] ).join( "~" ); var packagePath = path.resolve( "./packages", packageName + ".tar.gz" ); var info = { path: projectPath, name: packageName, output: packagePath, build: build, branch: branch, commit: commit, slug: slug, owner: owner, version: version, pattern: config.pack ? config.pack.pattern : undefined, }; return info; }, versionPromise, buildPromise ); }
C.open = function() { return when.try(this.allocate.bind(this)).then( function(ch) { return ch.rpc(defs.ChannelOpen, {outOfBand: ""}, defs.ChannelOpenOk); }); };
JSONRPCClient.prototype.call = function(method) { var remoteMethod = this.options.methodPrefix + method; var remoteArgs = [].slice.apply(arguments).slice(1); return when.try(function() { var deferred = when.defer(); debug('call', method, remoteArgs); if (this.signingFunctions) { var signedArgs = this.signingFunctions.sign({method: remoteMethod, arguments: remoteArgs}); remoteArgs = [signedArgs]; debug('signed', method, remoteArgs); } this.client.request(remoteMethod, remoteArgs, function(err, value) { debug('result', err, value ? value.error : "-", value ? value.result : "-"); if (err) { debug('call', 'rejecting with call error'); deferred.reject(err); } else if (value.error) { debug('call', 'rejecting remote error'); deferred.reject(value.error); } else { deferred.resolve(value.result); } }); return deferred.promise; }.bind(this)); };
function singlePass() { // Delegate the loading itself to the dependency-injected loader function (hopefully, it's something useful, such as a bound Event Store method). return when.try(loaderFunction, ARConstructor, ARID).then(function runUserFunction(aggregateInstance) { return when.try(userFunction, aggregateInstance).then(function saveAggregateState(userFunctionResult) { return when.try(aggregateInstance.commit.bind(aggregateInstance), options.commitMetadata || {}).catch(function handleSavingError(savingError) { failureLogger(savingError); var strategyAllowsAnotherTry = shouldTryAgain(savingError); if (strategyAllowsAnotherTry) { return delay(singlePass); } else { return when.reject(savingError); } }).yield(userFunctionResult); }); }, function handleLoadingError(loadingError) { failureLogger(loadingError); var strategyAllowsAnotherTry = shouldTryAgain(loadingError); if (strategyAllowsAnotherTry) { return delay(singlePass); } else { return when.reject(loadingError); } }); }
function compareSchema( riak, schemas, name, schemaContent ) { // DO NOT CHANGE THE EQUALITY COMPARER! return when.try( function( x, y ) { return x == y; // jshint ignore:line }, checkSchema( riak, schemas, name ), schemaContent ); }
function loadModule( resourcePath ) { try { var key = path.resolve( resourcePath ); delete require.cache[ key ]; var modFn = require( resourcePath ); var args = getArguments( modFn ); if( args[ 0 ] === 'host' ) { args.shift(); } if( args.length ) { var modPromise = fount.resolve( args ) .then( function( deps ) { var argList = _.map( args, function( arg ) { return deps[ arg ]; } ); return modFn.apply( modFn, argList ); } ); return when.try( processModule, modPromise, resourcePath ) .then( null, function( err ) { console.log( err.stack ); } ); } else { var mod = modFn( host ); return processModule( mod, resourcePath ); } } catch ( err ) { debug( 'Error loading resource module at %s with: %s', resourcePath, err.stack ); return when( [] ); } }
}).then(function (packageJson) { var tasks = []; var pluginModule; tasks.push(when.try(function () { //TO DO: Make this async pluginModule = require(pluginPath); }).catch(function (err) { if (err.message !== 'Cannot find module \'' + pluginPath + '\'') { throw err; } }) ); return when.all(tasks).then(function () { return { path: pluginPath, name: packageJson.name, package: packageJson, module: pluginModule, }; }); });
return this.svcs_container.route(route, options, function(msg) { when.try(function() { return handler(msg); }).done(function() { msg.ack(); }, function(err) { debug('error', 'Error thrown in routing handler, not acking message. Error: ', err.stack); }); });
module.exports = function upload(stream, idOrPath, tag, done) { var blob = blobManager.create(account); var tx = db.begin(); var blobIdP = blob.put(stream); var fileP = self.byUuidOrPath(idOrPath).get(); var version, fileId, file; when.try(function(blobId, fileV) { // when.all([blobIdP, fileP]).then(function(a) { // var blobId = a[0], fileV = a[1]; file = fileV; var previousId = file ? file.version : null; version = { userAccountId: userAccount.id, date: new Date(), blobId: blobId, creatorId: userAccount.id, previousId: previousId, }; version.id = Version.createHash(version); return Version.insert(version).execWithin(tx); }, blobIdP, fileP).then(function() { // }).then(function() { if (!file) { var splitPath = idOrPath.split('/'); var fileName = splitPath[splitPath.length - 1]; var newId = uuid.v1(); return self.createQuery(idOrPath, { id: newId, userAccountId: userAccount.id, name: fileName, version: version.id }).then(function(q) { return q.execWithin(tx); }).then(function() { return newId; }); } else { return file.id; } }).then(function(fileIdV) { fileId = fileIdV; return FileVersion.insert({ fileId: fileId, versionId: version.id }).execWithin(tx); }).then(function() { return File.whereUpdate({id: fileId}, {version: version.id}) .execWithin(tx); }).then(function() { tx.commit(); return done(); }, function(err) { tx.rollback(); return done(err); }); }
return function (user) { return when.try(saveUser, user) .then(sendAnyNotification) .catch(exceptions.InvalidOperationError, function (err) { console.log('throw'); return rollback(err, user); }); }
function checkPermission( user, action ) { var actionName = action.roles ? action.name : action, actionRoles = _.isEmpty( action.roles ) ? actions.getRoles( actionName ) : action.roles, userName = user.name ? user.name : user, userRoles = _.isEmpty( user.roles ) ? users.getRoles( userName ) : user.roles; if( user.roles && user.disabled ) { userRoles = []; } return when.try( userCan, userRoles, actionRoles ); }
defaultRequest(path, additionalAttributes) { return when.try(getServiceUrl, 'swift').then((serviceUrl) => { let requestAttributes = _.merge({ url: `${serviceUrl}${path}`, crossOrigin: true, method: 'GET' }, additionalAttributes); return when(request(requestAttributes)); }); }
function put( riak, idStrategy, bucketName, bucketType, key, obj, indexes, getBeforePut ) { if ( _.isObject( key ) ) { getBeforePut = indexes; indexes = obj; obj = key; key = undefined; } key = key || obj.id || idStrategy(); obj.id = obj.id || key; indexes = indexes || obj._indexes; if ( indexes ) { indexes = processIndexes( indexes ); } var getOriginal = function() { var vclock = obj.vclock; delete obj.vclock; return when( { type: bucketType, vclock: vclock, _indexes: obj._indexes } ); }; if ( !obj.vclock && getBeforePut ) { getOriginal = function() { return get( riak, bucketName, bucketType, key ) .then( function( result ) { return _.isArray( result ) ? result[ 0 ] : result; } ); }; } var request = when.try( buildPut, bucketName, bucketType, key, obj, indexes, getOriginal() ); return when.try( riak.put, request ) .then( function( reply ) { obj.id = key; obj.vclock = reply.vclock; return key; } ); }
ok = ok.then(function (result) { var ok = when.try(waveform, wfStyle, result.peaks, { asDataURL: true }); ok = ok.then(function (result) { _(result).chain().keys().map(function (k) { res.send('<img src="' + result[k] + '" alt=""\>'); }); }); return ok; });
return when.try(userFunction, aggregateInstance).then(function saveAggregateState(userFunctionResult) { return when.try(aggregateInstance.commit.bind(aggregateInstance), options.commitMetadata || {}).catch(function handleSavingError(savingError) { failureLogger(savingError); var strategyAllowsAnotherTry = shouldTryAgain(savingError); if (strategyAllowsAnotherTry) { return delay(singlePass); } else { return when.reject(savingError); } }).yield(userFunctionResult); });
defaultRequest(path, additionalAttributes) { return when.try(getServiceUrl, 'heat').then(serviceUrl => { let requestAttributes = _.merge( { url: `${serviceUrl}${path}`, headers: { 'X-Auth-Token': getAuthTokenId() }, crossOrigin: true, contentType: 'application/json', type: 'json', method: 'GET' }, additionalAttributes ); return when(this.request(requestAttributes)); }); }
defaultRequest(path, additionalAttributes) { return when.try(getServiceUrl, 'swift').then(serviceUrl => { let requestAttributes = _.merge( { url: `${serviceUrl}${path}`, crossOrigin: true, method: 'GET', headers: { 'X-Auth-Token': getAuthTokenId() } }, additionalAttributes ); return when(request(requestAttributes)); }); }
handleCommand(cmd, args) { return when.try(() => { if (~this.server.options.disabledCommands.indexOf(cmd)) { return this.reply(502, 'Command not allowed.'); } if (!this.server.options.anonymous && !this.authenticated && !~NO_AUTH_CMDS.indexOf(cmd)) { return this.reply(530, 'Command requires authentication.'); } if (commands.hasOwnProperty(cmd)) { return commands[cmd].fn.apply(this, [cmd].concat(args)); } else { return this.reply(502); } }); }
function setIndex( riak, indexes, name, schema ) { // jshint ignore:line return when.try( function( equal ) { if ( equal ) { return when( false ); } else { log.debug( 'Creating index "%s" with schema %s', name, schema ); return riak.yzPutIndex( { index: { name: name, schema: schema } } ) .then( function() { indexes[ name ] = schema; return ( true ); } ); } }, compareIndex( riak, indexes, name, schema ) ); }
RedisFacet.prototype.initialise = function() { return when.try(function() { var urlKey = this.name + ':url'; var url = this.service.config.get(urlKey); if (!url) { throw new Error('RedisFacet requires configuration at ' + urlKey); } debug(this.name, 'Configuration for RedisFacet using URL: ' + url); this._client = redis.createClient(url); var closeErr = new Error('Redis connection closed by remote host (redis server).'); this._client.on('close', this.emit.bind(this, 'error', closeErr)); return when(this._client.connect()).then(function() { this._bindRedisCommands(); }.bind(this)); }.bind(this)); };
function setSchema( riak, schemas, name, schemaPath ) { // jshint ignore:line var content = fs.readFileSync( schemaPath, 'utf8' ); return when.try( function( equal ) { if ( equal ) { return when( true ); } else { log.debug( 'Creating schema "%s" from file "%s"', name, schemaPath ); return riak.yzPutSchema( { schema: { name: name, content: content } } ) .then( function() { schemas[ name ] = content; } ); } }, compareSchema( riak, schemas, name, content ) ); }
AMQPFacet.prototype.initialise = function() { return when.try(function() { var urlKey = this.name + ':url'; var url = this.service.config.get(urlKey); if (!url) { throw new Error('AMQPFacet requires configuration at ' + urlKey); } debug(this.name, 'Configuration for AMQPFacet using URL: ' + url); var closeErr = new Error('AMQP connection closed by remote host (AMQP server).'); var routerErr = new Error('Error in router acting on AMQP connection.'); this.svcs_container = svcs(); var db = when(amqp.connect(url)); var setup = db.then(function(db) { this._db = db; db.on('error', this.emit.bind(this, 'error', closeErr)); this.svcs_container.set('amqpConnection', db); this.svcs_container.set('errorHandler', this.emit.bind(this, 'error', routerErr)); return db; }.bind(this)); var channelCreated = setup.then(function(db) { // now we're set up, get a channel for publishes return when(db.createChannel()).then(function(channel) { this._channel = channel; return db; }.bind(this)); }.bind(this)); return channelCreated; }.bind(this)); };
JSONRPCClient.prototype.initialise = function() { return when.try(function() { // FIXME: support pool of RPC servers var serverKey = this.name + ':server'; var server = this.service.config.get(serverKey); if (!server) { throw new Error('JSON RPC Client requires configuration at ' + serverKey); } ['hostname', 'port'].map(function(key) { if (!server.hasOwnProperty(key)) { throw new Error('JSON RPC Client requires configuration option: ' + key); } }); this.signingFunctions = json_signing.getSigningFunctions(this.service, this.name); debug(this.name, 'Configuration for JSON RPC Client: ' + server); this.client = jayson.client.http(server); }.bind(this)); };
module.exports = function pluginLoader(lfa) { return when.try(function () { var plugins = [ loadBuiltInPlugin(lfa, 'lfa-compilation'), loadBuiltInPlugin(lfa, 'lfa-analytics') ]; if (lfa.config.pluginProject) { plugins.push(loadPlugin(lfa, lfa.config.projectPath, lfa.config.packageJson)); return plugins; } if (lfa.config.loadCore) { plugins.push(loadBuiltInPlugin(lfa, 'lfa-core')); } var tasks = []; if (lfa.config.loadPlugins) { tasks.push(loadLocalPlugins(lfa, plugins)); } return when.all(tasks).then(function () { if (lfa.config.loadUser) { plugins.push(loadBuiltInPlugin(lfa, 'lfa-book')); plugins.push(loadBuiltInPlugin(lfa, 'lfa-user')); } return plugins; }); }).then(function (plugins) { return when.all(plugins); }).then(function (loadedPlugins) { lfa.plugins = loadedPlugins; _.each(loadedPlugins, function (plugin) { if (plugin.module) { plugin.module.call(plugin, lfa); } }); }); };
JSONRPCServer.prototype._setupServer = function() { return when.try(function() { var portKey = this.name + ':port'; var port = this.service.config.get(portKey); if (!port) { throw new Error('JSON RPC Client requires configuration at ' + portKey); } this.signingFunctions = json_signing.getSigningFunctions(this.service, this.name); var hostKey = this.name + ':host'; var host = this.service.config.get(hostKey); var wrappedMethods = {}; for (var name in this.methods) { if (!this.methods.hasOwnProperty(name)) continue; var method = this.methods[name]; (function(name, method) { wrappedMethods[name] = function() { var args = [].slice.apply(arguments); var callback = args.pop(); debug('call', args); var argsPromise; if (this.signingFunctions) { // ensure that we have an argument and that it is a string var encoded = args[0]; if (typeof encoded !== 'string') { encoded = ''; }; // decode and check JWT signature argsPromise = this.signingFunctions.verify(encoded).then(function(decoded) { if (decoded.method != name) { throw {code:403, message:'Method name mismatch during signature verification'}; } debug('verified', decoded.method, decoded.arguments); return decoded.arguments; }, function() { throw {code:403, message:'Verification of signed message failed'}; }); } else { // not using JWT signing, allow plaintext RPC argsPromise = when(args); } // promisify the maybe-promise result var promise = argsPromise.then(function(args) { return when.try(function() { return method.apply(this, args); }.bind(this)); }.bind(this)); // wrap back out to node callback style promise.done(function(val) { debug('result', val); callback(null, val); }, function(err) { debug('error', err.stack); // must be the correct format, check for node Errors and // magicify into {code: ..., message: ...} if (err.hasOwnProperty('message')) { callback(err); } else { callback({message: err.toString()}); } }); }.bind(this); }.bind(this))(name, method); } var portKey = this.name + ':port'; var port = this.service.config.get(portKey); this.server = jayson.server(wrappedMethods); var app = express(); var deferred = when.defer(); var args = [port]; if (host) { args.push(host); } args.push(function(err) { if (err) { deferred.reject(err); } else { deferred.resolve(true); } }); app.use(bodyParser.json()); app.get('/status', function (req, res) { res.status(200).send({status: 'ok'}); }); app.use(this.server.middleware()); app.listen(port, function() { debug(this.name, 'Listening on ' + port); deferred.resolve(app); }.bind(this)); return deferred.promise; }.bind(this)); };
var promise = argsPromise.then(function(args) { return when.try(function() { return method.apply(this, args); }.bind(this)); }.bind(this));
return when.all( _.map( adapters, function( adapter ) { return when.try( adapter.resource, resource, basePath ); } ) )
compile: function () { return when.try(this.create_folders.bind(this)) .with(this) .then(this.compile_and_save_project); },
this.initialiseCommentsWidget(); }, render() { return ( <div className="button-fb-like"> <div className="fb-like" data-href={ this.props.url } data-layout={ this.props.layout } data-action="like" data-show-faces="true" data-share="true"> </div> </div> ); }, initialiseCommentsWidget() { function clear() { $( this.getDOMNode() ).find( '.button-fb-like' ).empty(); } function initialize() { FB.XFBML.parse( this.getDOMNode() ); } when.try( clear.bind( this ) ) .then( initialize.bind( this ) ); } } );
AMQPFacet.prototype.publish = function(exchange, routingKey, content) { return when.try(function() { this._channel.publish(exchange, routingKey, content); }.bind(this)); };