Example #1
0
		function(){ 
			var promise = function(resolve, reject, notify){
				saveGroupData(group);
				console.log("Finished Archiving");
				resolve();
			}
			return Q.Promise(promise);
		}
Example #2
0
var newRequest = function(url){
	return Q.Promise(function(resolve,reject){
		newRequest._request(url,function(error,response,body){
			
			if(error){
				return reject(error);
			}

			if (response.statusCode != 200) {
				return reject(exception("http status code is not 200","EHTTPSTATUS"));
			}

			resolve(response);
		});
	});
};
Example #3
0
  }).then(function(appDetail) {
    try {
      fs.mkdirSync(appDetail.app_name);
    } catch (err) {
      if (err.code != 'EEXIST') {
        err.action = '创建项目';
        throw err;
      }
    }
    var zipFilePath = path.join(TMP_DIR, _appId + '.zip');
    return Q.Promise(function(resolve, reject) {
      request('http://lcinternal-cloud-code-update.leanapp.cn' + repoUrl)
      .pipe(fs.createWriteStream(zipFilePath))
      .on('close', function() {
        try {
          var unzipper = new AdmZip(zipFilePath);

          unzipper.getEntries().forEach(function(file) {
            console.log(color.green('  ' + file.entryName));
          });

          unzipper.extractAllTo(appDetail.app_name, true);

          setCloudPath(path.resolve(appDetail.app_name));
          Q.nfcall(addApp, appDetail.app_name, _appId).then(function() {
            return Q.nfcall(checkoutApp, appDetail.app_name);
          }).then(function() {
            console.log('项目创建完成!');
            resolve();
          }).catch(function(err) {
            reject(err);
          });
        } catch (err) {
          console.error('解压缩失败:%s,服务器响应:%s', err.stack, fs.readFileSync(zipFilePath, 'utf-8'));
          resolve();
        }
      }).on('error', function(err) {
        err.action = '创建项目:下载项目框架';
        reject(err);
      });
    });
  }).then(cb).catch(cb);
export default function(endpointParentType, resourceOrCollection, registry) {
  return Q.Promise(function(resolve, reject) {
    // validate that all resources are of types appropriate for the endpoint.
    const adapter = registry.dbAdapter(endpointParentType);
    const allowedTypes = adapter.getTypesAllowedInCollection(endpointParentType);
    const resourcesByType = groupResourcesByType(resourceOrCollection);

    if(!isSubsetOf(allowedTypes, Object.keys(resourcesByType))) {
      let title = "Some of the resources you provided are of a type that " +
                  "doesn't belong in this collection.";
      let detail = `Valid types for this collection are: ${allowedTypes.join(", ")}.`;

      reject(new APIError(400, undefined, title, detail));
    }

    else {
      // If there are extra attributes or missing attributes, we want the
      // adapter to decide how to handle that, depending on the model. But,
      // if there are paths that must be relationship names listed under the
      // attributes, that's a case that we can identify here and throw for.
      for(let type in resourcesByType) {
        let resources = resourcesByType[type];
        let relationshipNames = adapter.getRelationshipNames(type);

        /*eslint-disable no-loop-func */
        let invalid = resources.some((resource) => {
          return relationshipNames.some((relationshipName) => {
            return typeof resource.attrs[relationshipName] !== "undefined";
          });
        });
        /*eslint-enable no-loop-func */

        if(invalid) {
          let title = "Relationship fields must be specified under the `relationships` key.";
          return reject(new APIError(400, undefined, title));
        }
      }

      return resolve();
    }
  });
}
Example #5
0
     .then(function () {
     return q
         .Promise(function (resolve) {
         // 1) If getMultiCapabilities is set, resolve that as
         // `multiCapabilities`.
         if (config.getMultiCapabilities &&
             typeof config.getMultiCapabilities === 'function') {
             if (config.multiCapabilities.length || config.capabilities) {
                 logger.warn('getMultiCapabilities() will override both capabilities ' +
                     'and multiCapabilities');
             }
             // If getMultiCapabilities is defined and a function, use this.
             q.when(config.getMultiCapabilities(), function (multiCapabilities) {
                 config.multiCapabilities = multiCapabilities;
                 config.capabilities = null;
             }).then(function () { return resolve(); });
         }
         else {
             resolve();
         }
     })
         .then(function () {
         // 2) Set `multicapabilities` using `capabilities`,
         // `multicapabilities`,
         // or default
         if (config.capabilities) {
             if (config.multiCapabilities.length) {
                 logger.warn('You have specified both capabilities and ' +
                     'multiCapabilities. This will result in capabilities being ' +
                     'ignored');
             }
             else {
                 // Use capabilities if multiCapabilities is empty.
                 config.multiCapabilities = [config.capabilities];
             }
         }
         else if (!config.multiCapabilities.length) {
             // Default to chrome if no capabilities given
             config.multiCapabilities = [{ browserName: 'chrome' }];
         }
     });
 })
Example #6
0
function create_directory(dir_path){
    console.log('creating directory');

    return Q.Promise(function(resolve,reject,notify){
        check_directory(dir_path).then( function(){
            resolve();
        }).fail(function(){
            var cmd = 'mkdir ' + dir_path;
            exec(cmd, function(err,stout,sterr){
                if(err){
                    console.log('error creating directory',err);
                    reject();
                }else{
                    console.log('directory created');
                    resolve();
                }
            })
        })
    })
}
Example #7
0
  saveTo: function(dir) {
    return Q.Promise((function(resolve, reject, notify) {
      if (!fs.existsSync(dir)) {
        var error = new Error(dir + ' does not exist!');
        this._logger.error(LOG_PREFIX, error);
        return reject(error);
      }

      try {
        var url = this.url;
        var retryCount = MAX_RETRY_COUNT;
        this._trySave(url, dir, retryCount)
          .then(resolve)
          .catch(reject);
      } catch(error) {
        this._logger.error(LOG_PREFIX, error);
        reject(error);
      }
    }).bind(this));
  },
function findAndUpdateUser(req) {
  var body = req.body || {};
  var userData = {
    name: body.name,
    email: body.email
  };
  var dbOptions = {
    runValidators: true
  };
  return Q.Promise(function (resolve, reject) {
    UserModel.findByIdAndUpdate(req.params.id, userData, dbOptions,
      function findSuccess(error, user) {
        if (error) {
          reject(error);
        } else {
          resolve(user);
        }
      });
  });
}
Example #9
0
var getIssueEvents = function (issue) {
    log.debug('Creating promise for issue ' + issue.number + '\'s events');
    return Q.Promise(function (resolve, reject) {
        log.debug('Getting events for issue ' + issue.number);

        client.get(issue.events_url, function (err, status, eventsPage) {
            log.debug('Response received for issue ' + issue.number + '\'s events');
            if (err != null) {
                log.debug(err);
                reject(err);
            }
            if (status !== 200) {
                log.debug(err);
                reject('Issue Events error bad status ' + status);
            }
            issue.events = eventsPage;
            resolve(issue);
        });
    });
};
 }).then(function (db) {
     return Q.Promise(function (resolve, reject) {
         return db.transaction(function (tx) {
             try {
                 return tx.executeSql(query, [model.entity + '~' + model.get('id')], function (tx1, table) {
                     try {
                         chai_1.assert.equal(table.rows.length, 0);
                         resolve(true);
                     }
                     catch (error) {
                         reject(error);
                     }
                 });
             }
             catch (error) {
                 reject(error);
             }
         }, reject);
     });
 });
Example #11
0
Docker.prototype.imageExists = function(img){
    var self = this;
    return q.Promise( function(resolve,fail,notify){
        self.listImages( function(err,images){
            var image_res;

            var res = images.some( function(image){
                var img_name = image.RepoTags[0];
                image_res = image;
                return (img_name.indexOf(img) > -1)
            });

            if(res){
                resolve(image_res);
            }else{
                fail(img);
            }
        });
    });
}
module.exports.getListForParentId = function(parentId, entityType, internal){
	
	return Q.Promise(function(resolve, reject, notify) {


		function callback(err, values){
			if (!err) {
                resolve(values);

            } else {
                reject(new Error(err));
            }
		}

		var processor = require('./app/processors/get-property.js');


		processor.list(parentId, callback);
	});
};
Example #13
0
  show () {
    return q.Promise((resolve) => {

      TweenMax.set(this.img, { scale: 1, opacity: 0 });
      this.img.src = 'img/' + this.cells[this.index].src;

      this.img.onload = () => {
        this.imgSize = { w: this.img.width, h: this.img.height };
        this.resize(true);

        new TimelineMax()
          .set(this.img, { opacity: 1 })
          .addCallback(() => {
            this.showPoints()
              .then(resolve);
          });
      };

    });
  }
Example #14
0
// Read one csv file line by line.
function collapseSingle(map, domain, file) {
  var into = {
    name: domain,
    failed: 0
  };
  if (fs.existsSync(rundir + '/' + file + '.asn.json')) {
    return Q(0);
  }

  return Q.Promise(function (resolve, reject) {
    fs.createReadStream(rundir + '/' + file)
      .pipe(es.split())
      .pipe(es.mapSync(parseDomainLine.bind({}, map, into, domain)))
      .on('end', resolve)
      .on('error', reject);
  }).then(function () {
    fs.writeSync(outFD, JSON.stringify(into) + '\n');
    return true;
  });
}
Example #15
0
  function resizeImage() {
    return Q.Promise(function resize(resolve, reject) {
      var argSize = width + 'x' + height,
        command = '';
      if (type == 'resize') {
        command = 'gm convert ' + cacheOrginFile + ' -resize "' + argSize + '>" +profile "*" ' + cacheResizeFile;
        console.info(command);
      } else if (type == 'crop') {
        command = 'gm convert ' + cacheOrginFile + ' -gravity ' + gravity + ' -extent ' + argSize + '  ' + cacheResizeFile;
      }
      exec(command, function(error, stdout, stderr) {
        if (error !== null) {
          console.log('exec error: ' + error);
        } else {
          resolve();
        }
      });

    });
  }
Example #16
0
  return Q.ninvoke(Runtime, 'detect', CLOUD_PATH, options).then(function(runtimeInfo) {
    return Q.Promise(function(resolve, reject) {
      console.log('压缩项目文件 ...');
      var output = fs.createWriteStream(file);
      var archive = archiver('zip');

      output.on('close', function() {
        resolve();
      });

      archive.on('error', function(err) {
        err.action = '项目文件打包';
        reject(err);
      });

      archive.pipe(output);
      runtimeInfo.archive(archive);
      archive.finalize();
    });
  }).then(function() {
Example #17
0
mpv.prototype.sendMessage = function (message, cb) {
    if (!this.socket)
        return this.bufferMessage(message);
    this.socket.write(JSON.stringify(message) + '\n');
    if (!this.cbQueue)
        this.cbQueue = [];

    if (cb) {
        this.cbQueue.push(cb);
    } else {
        return Q.Promise(function (resolve, reject) {
            this.cbQueue.push(function (data) {
                if (data.error == 'success')
                    resolve(data.data);
                else
                    reject(data);
            });
        }.bind(this));
    }
};
Example #18
0
module.exports.getTokenUaaKey = function() {
    logger.debug('Getting uaa token key.');
    return Q.Promise(function (resolve, reject) {
        request.get({
            url: UAA_TOKEN_KEY_ENDPOINT
        }, function(err, response, body) {
            if(!err) {
                resolve({
                    code: response.statusCode,
                    body: JSON.parse(body)
                });
            } else {
                reject({
                    code: httpUtils.responses.error.InternalServerError.code,
                    message: err
                });
            }
        });
    });
};
HtmlFormatter.prototype._getHtmlIndexes = function() {
    var self = this,
        parser,
        result = [],
        pushTagIndexes = function() {
            result.push({startIndex: parser.startIndex, endIndex: parser.endIndex});
        };

    var promise = Q.Promise(function(resolve) {
        parser = new HtmlParser.Parser({
                onopentag: pushTagIndexes,
                onclosetag: pushTagIndexes,
                onend: resolve
            }, {decodeEntities:true, recognizeCDATA:true});
        parser.write(self._src);
        parser.end();
    });

    return promise.thenResolve(result);
};
Example #20
0
/**
 * Public "login" interface. Eg:
 * require('pepper-mint')(user, password)
 * .then(function(mint) {
 *  // do fancy stuff here
 * });
 *
 * If you need access to events before login is completed,
 *  the PepperMint class instance is stored on the returned
 *  Promise as `.mint`.
 */
function Prepare(email, password, token, cookies) {
    var mint = new PepperMint();
    mint.token = token;

    var promise = Q.Promise(function(resolve, reject) {
        // start login next frame so clients can register event handlers
        // for browser-login
        setTimeout(function() {
            mint._extractCookies(token, cookies);

            _login(mint, email, password, function(err) {
                if (err) return reject(err);

                resolve(mint);
            });
        }, 0);
    });
    promise.mint = mint;
    return promise;
}
Example #21
0
/**
 * Runs an action and returns the result.
 * - Streams return a Promise that returns the results as an array.
 * - Values are returned instantly.
 * - Promises are evaluated and returned as the result.
 * @param action
 * @returns {*}
 */
function results(action) {

    if (_.isFunction(action))
        throw errors('NOT_SUPPORTED', 'Running functions is currently not supported.');

    // ** Return a promise that completes when the stream is completed
    if ($.isStream(action)) {

        // ** Return a promise that will resolve this stream upon completion
        return Q.Promise((resolve, reject) =>
            $(action)
                .stopOnError(err => {
                    logger.error(errors('STREAM_ERROR', err));
                    reject(err);
                })
                .toArray(resolve));
    }

    return Q.when(action);
}
 return co(function *() {
   if (autoconf) {
     conf.salt = ~~(Math.random() * 2147483647) + "";
     conf.passwd = ~~(Math.random() * 2147483647) + "";
     logger.info('Key: %s', 'generated');
   } else {
     yield Q.Promise(function(resolve, reject){
       choose('You need a keypair to identify your node on the network. Would you like to automatically generate it?', true,
         function(){
           conf.salt = ~~(Math.random() * 2147483647) + "";
           conf.passwd = ~~(Math.random() * 2147483647) + "";
           resolve();
         },
         function(){
           doTasks(['key'], conf, (err) => err ? reject(err) : resolve());
         });
     });
   }
   done();
 })
var hgetall = function(distance, check, client){
  return q.Promise(function(resolve, reject, notify){
    var values = orderByDistance(distance, 6)
    client.multi([
        ["hgetall", "estacion:"+listbicis[values[0].key].id],
        ["hgetall", "estacion:"+listbicis[values[1].key].id],
        ["hgetall", "estacion:"+listbicis[values[2].key].id],
        ["hgetall", "estacion:"+listbicis[values[3].key].id],
        ["hgetall", "estacion:"+listbicis[values[4].key].id],
        ["hgetall", "estacion:"+listbicis[values[5].key].id]
    ]).exec(function (err, estaciones) {
      var iterestaciones = []
      for(var n=0;n<estaciones.length;n++)
        if(parseInt(estaciones[n].BicicletaDisponibles) >= check) iterestaciones.push(estaciones[n])
      if(err)
        reject(err);
      resolve(iterestaciones);
    });
  });
};
Example #24
0
 .then(() => {
   // Renaming angular-cli.json if needed      
   return Q.Promise((resolve, reject) => {
     fs.access(angularCliJSONPath, fs.constants.R_OK | fs.constants.W_OK, (angularCliExistanceError) => {
       if (angularCliExistanceError) {
         fs.access(oldAngularCliJSONPath, fs.constants.R_OK | fs.constants.W_OK, (oldAngularCliExistanceError) => {
           if (!oldAngularCliExistanceError) {
             fs.renameSync(oldAngularCliJSONPath, angularCliJSONPath);
             winston.info('[.angular-cli.json] Renaming angular-cli.json to .angular-cli.json');
             resolve();
           } else {
             reject('[.angular-cli.json] No angular-cli.json found!');
           }
         });
       } else {
         resolve();
       }
     });
   });
 })
Example #25
0
function getPersonInfo(personId) {
  return q.Promise(function(resolve, reject, notify){
    jquery.ajax({
      data: {
        personId: personId
      },
      url: '/person/getPersonInfo',
      success: function(data) {
        if(data.success) {
          resolve(data.person);
        } else {
          reject();
        }
      },
      error: function() {
        reject();
      }
    });
  });
}
Example #26
0
// Read one csv file line by line.
function collapseSingle(map, blacklist, domains, file) {
  var into = {},
    queries = {},
    start = fs.statSync(rundir + '/' + file).atime;
  domains.forEach(function (dom) {
    into[dom] = {
      name: dom,
      failed: 0
    };
  });

  return Q.Promise(function (resolve, reject) {
    fs.createReadStream(rundir + '/' + file)
      .pipe(es.split())
      .pipe(es.mapSync(parseDomainLine.bind({}, map, blacklist, into, queries, start, domains)))
      .on('end', resolve)
      .on('error', reject);
  }).then(function () {
    var i;
    for (i = 0; i < domains.length; i += 1) {
      fs.writeSync(outFD, JSON.stringify(into[domains[i]]) + '\n');
      if(ooniFile) {
        fs.writeSync(ooniFD, JSON.stringify({
          "software_name": "satellite",
          "software_version": version,
          "probe_asn": "AS73",
          "probe_cc": "US",
          "probe_ip": localip,
          "record_type": "entry",
          "report_id": reportid,
          "start_time": start.valueOf() / 1000,
          "test_name": "dns",
          "test_version": "1.0.0",
          "input": domains[i],
          "queries": queries[domains[i]]
        }) + '\n');
      }
    }
    return true;
  });
}
Example #27
0
exports.updateTop = function (pid, enable, value) {
  logger.debug('try to update user top for user:'******'boolean') {
      reject(new Error('value type must be boolean'));
    }
    if(enable){
      User.update({
        '_id': pid
      }, {
        $set: {
            'top': value
        }
        
      }, function (err) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    }else{
      User.update({
        '_id': pid
      }, {
        $set: {
            'top': -1
          }
        
      }, function (err) {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    }
    
  });
};
Example #28
0
 return oinvoke(db, 'getObjectByKey', feedId).then(function(feed) {
     var ldFeed = this.client._ldClient.feed.getLDFeed(feed);
     var account = this.client.auth.getAccount();
     var req = new LDProto.LDRemoveMemberRequest();
     req.Feed = ldFeed;
     req.Member = account;
     return Q.Promise(function(callback, errback) {
         return this.client._ldClient._msg.call(req, function(err, resp) {
             if (err)
                 errback(err);
             else
                 callback();
         }.bind(this));
     }.bind(this)).then(function() {
         // GIANT GIANT GIANT HACK
         // omclient does not process feed membership changes
         // in a sensible manner
         // so we just delete the feed manually here
         db._data.remove(feed);
     });
 }.bind(this));
Example #29
0
Docker.prototype.containerExistsByName = function(cont){
    var self = this;
    return q.Promise( function(resolve,fail,notify){
        self.listContainers({all:1},function(err,containers){
            var container_res;

            var res = containers.some(function(container){
                container_res = container;
                return container.Names.some( function(name){
                    return (name == '/'+cont)
                });
            });

            if(res){
                resolve(container_res);
            }else{
                fail('container does not exist');
            }
        })
    });
}
Example #30
0
 }).then(function () {
     // resolves to window once the device is ready
     return Q.Promise(function (resolve, reject) {
         try {
             if (!window || !('cordova' in window ||
                 'PhoneGap' in window || 'phonegap' in window ||
                 'forge' in window)) {
                 resolve(window);
                 return;
             }
             // see https://cordova.apache.org/docs/en/latest/cordova/events/events.html#deviceready
             document.addEventListener('deviceready', function () {
                 document.removeEventListener('deviceready', callback);
                 resolve(window);
             }, false);
         }
         catch (error) {
             reject(error);
         }
     });
 }).then(function () {