ChainCode.findOne({_id: id}).populate('chain').exec(function (err, chainCode) { if (err) { res.json({success: false}) } else { helper.initialize(chainCode.chain.template) helper.setupChaincodeDeploy() instantiate.initialize(chainCode.chain.template) instantiate.instantiateChaincode(channelName, chainCode.chainCodeName, chaincodeVersion, fcn, args, req.username, orgName) .then(function(message) { chainCode.status = "instantiated" chainCode.save() io.to(user_id).emit('instantiate done', { chainName: chainCode.chain.name, name: chainCode.name, id: chainCode.id, message: 'instantiate done' }); }); chainCode.status = "instantiating" chainCode.save() res.json({ success: true }); } })
exports.loadModules = function*( app ){ var initializers = utils.readdirRecursiveSync(app.APP + 'modules/'); // initialize db-module first, because it initializes all database models // (fix for potential race-conditions if a filename starts with a,b,c) for(var i = 0; i < initializers.length; i++) { // get db-module, initialize it and remove it from initializers-array if(initializers[i].name === 'Db') { try { var module = require(initializers[i].path); yield module.initialize(app); initializers.splice(i, 1); } catch(err) { app.exit('Initializer db failed with: ' + err); } break; } } for (var initializer in initializers){ try { var module = require(initializers[initializer].path); yield module.initialize(app); } catch(err){ app.exit('Initializer "' + initializers[initializer].name + '" failed with: ' + err); } } };
register: function(vorpal_inst, session_id, vm_server_client) { vm_server_controller.initialize(vm_server_client); vm_controller.initialize(vm_server_client); for (var i = 0; i < COMMANDS.length; i++) { vorpal_inst.command(COMMANDS[i]['name'], COMMANDS[i]['description']) .action(COMMANDS[i]['action'](vorpal_inst, session_id)) } }
function loadPlugins(projectDir, plugins) { var options = {}; for (var plugin in plugins) { var val = plugins[plugin]; if (!val) continue; var found = findFile(plugin + ".js", projectDir, path.resolve(distDir, "plugin")); if (!found) { try { found = require.resolve("tern-" + plugin); } catch (e) { process.stderr.write("Failed to find plugin " + plugin + ".\n"); continue; } } var mod = require(found); if (mod.hasOwnProperty("initialize")) mod.initialize(distDir); options[path.basename(plugin)] = val; } defaultPlugins.forEach(function(name) { if (!plugins.hasOwnProperty(name)) { options[name] = true; require("../plugin/" + name); } }); return options; }
server.listen(port, function () { port = server.address().port; var config = configurator.initialize({ 'app_name' : 'node.js Tests', 'license_key' : 'd67afc830dab717fd163bfcb0b8b88423e9a1a3b', 'host' : 'staging-collector.newrelic.com', 'port' : 80, 'proxy' : fmt('http://*****:*****@localhost:%d', port), 'ssl' : false, 'logging' : { 'level' : 'trace' }, 'feature_flag': { // FLAG: proxy proxy: true } }) , agent = new Agent(config) , api = new CollectorAPI(agent) ; api._methods.redirect.invoke(null, function cb_invoke() { server.close(); t.end(); }); });
module.exports = function binding(options) { const bindingPath = nodePreGyp.find( path.resolve(path.join(__dirname,'../package.json')), options || {} ); const initialize = require(bindingPath).initialize; const gemfire = initialize({ EventEmitter: EventEmitter, process: process }); var cacheSingleton; gemfire.configure = function configure(xmlFilePath, gemfireProperties) { if(cacheSingleton) { throw( "gemfire: configure() can only be called once per process. " + "Please call configure() once in an application initializer. " + "Afterwards, you can call getCache() multiple times to get the cache singleton object." ); } var cacheFactory = new CacheFactory(gemfireProperties, function(cacheInstance){ cacheSingleton = cacheInstance; }); cacheFactory.set("cache-xml-file", xmlFilePath); var cacheInstance = cacheFactory.create(); }; const Cache = gemfire.Cache; const CacheFactory = gemfire.CacheFactory; gemfire.createCacheFactory = function createCacheFactory(gemfireProperties){ if(cacheSingleton) { throw( "gemfire: configure() or createCacheFactory() can only be called once per process. " + "Please call configure() or createCacheFactory() after a create() once in an application initializer. " + "Afterwards, you can call getCache() multiple times to get the cache singleton object." ); } var cacheFactory = new CacheFactory(gemfireProperties, function(cacheInstance){ cacheSingleton = cacheInstance; }); return cacheFactory; }; gemfire.getCache = function getCache() { if(!cacheSingleton) { throw "gemfire: You must call configure() before calling getCache()."; } return cacheSingleton; }; delete gemfire.Cache; delete gemfire.CacheFactory; inherits(gemfire.Region, EventEmitter); delete gemfire.Region; return gemfire; };
server.configure(function() { if(configuration.env !== 'production') { //Embed live-reload snippets if not in prod server.use(require('connect-livereload')({ port: 35729 })); } server.use(express.cookieParser()); server.use(express.bodyParser()); server.use(express.methodOverride()); server.use(express.session({ secret: configuration.cookieSecret, store: new RedisStore({ "host": redisUrl.hostname, "pass": (redisUrl.auth || '').split(':')[1] || '', "port": redisUrl.port, "ttl": 3600 }) })); server.use(passport.initialize()); server.use(passport.session()); server.use(flash()); server.use(server.router); server.use('/assets', express.static('build')); });
ChainModel.findOne({_id: chainId}, function (err, chain) { const chainRootDir = util.format(config.path.chain, req.username, chainId) const query = require(`${chainRootDir}/lib/query`) query.initialize(chain.template) query.getBlockByNumber('peer1', blockId, req.username, 'org1') .then(function(message) { let txList = [] message.data.data.map((item, index) => { const {payload: {header: {channel_header: {tx_id, timestamp, channel_id}}}} = item; const txTime = moment(timestamp, "ddd MMM DD YYYY HH:mm:ss GMT+0000 (UTC)") txList.push({ id: tx_id, timestamp: txTime.unix(), channelId: channel_id }) }) res.send({ success: true, txList }); }, (err) => { res.json({ success: false, error: err.stack ? err.stack : err }) }).catch((err) => { res.json({ success: false, txList: [], error: err.stack ? err.stack : err }) }); })
ChainModel.findOne({_id: chainId}, function (err, chain) { const chainRootDir = util.format(config.path.chain, req.username, chainId) const query = require(`${chainRootDir}/lib/query`) query.initialize(chain.template) query.getTransactionByID('peer1', trxnId, req.username, 'org1') .then(function(message) { logger.debug(`message ${JSON.stringify(message, null, 2)}`) const {transactionEnvelope: {payload: {header: {channel_header: {type}}}}, validationCode} = message // const action = actions.length ? actions[0] : {} // const {payload: {chaincode_proposal_payload: {input: {chaincode_spec: {type, chaincode_id: {name}, input: {args}}}}}} = action res.json({ success: true, validationCode, type // name // args }) }, (err) => { res.json({ success: false, error: err.stack ? err.stack : err }) }).catch((err) => { res.json({ success: false, error: err.stack ? err.stack : err }) }); })
it("internal instrumentation can be configured", function () { var config = configurator.initialize({debug : {internal_metrics : true}}); var debugged = new Agent(config); var debug = debugged.config.debug; expect(debug.internal_metrics).equal(true); });
test("connecting when the collector is unavailable", function (t) { t.plan(7); /* * THIS TEST USES TIME TRAVEL * * That's why it's on its own in an integration test. */ var clock = sinon.useFakeTimers(); var agent = new Agent(configurator.initialize(logger)); agent.config.host = 'localhost'; agent.config.port = 8765; agent._nextConnectAttempt = function (backoff) { t.ok(backoff, "got the backoff information"); t.equal(backoff.warn, false, "first retry doesn't warn"); t.equal(backoff.error, false, "first retry doesn't error"); t.equal(backoff.interval, 15, "first retry is after 15 seconds"); agent.stop(); clock.restore(); }; // needed to create the connection agent.start(); agent.connection.once('connectError', function (data, error) { t.equal(agent.connectionFailures, 1, "got a failure"); t.notOk(data, "no actual data sent with message"); t.equal(error.message, 'connect ECONNREFUSED', "got expected error"); clock.tick(15001); }); });
it("should not collect traces for transactions that don't exceed apdex_f", function () { var BELOW_THRESHOLD = 27; var APDEXT = 0.007; var config = configurator.initialize({ transaction_tracer : { enabled : true, top_n : 10 } }); var aggregator = new TraceAggregator(config) , transaction = new Transaction(agent) ; aggregator.reported = 10; // needed to override "first 5" // let's violating Law of Demeter! transaction.metrics.apdexT = APDEXT; transaction.getTrace().setDurationInMillis(BELOW_THRESHOLD); transaction.url = '/test'; transaction.name = 'WebTransaction/Uri/test'; transaction.statusCode = 200; aggregator.add(transaction); expect(aggregator.requestTimes['WebTransaction/Uri/test']).equal(undefined); });
it("should have its own logical notion of a harvest cycle", function (done) { var config = configurator.initialize({ transaction_tracer : { enabled : true, top_n : 10 } }); var aggregator = new TraceAggregator(config); expect(function harvestExists() { aggregator.harvest(function (error, empty) { should.not.exist(error); should.not.exist(empty); expect(function addExists() { aggregator.add(createTransaction('/test', 4180)); }).not.throws(); aggregator.harvest(function (error, traceData) { expect(traceData).an('array'); expect(traceData.length).equal(8); expect(traceData[2]).equal('WebTransaction/Uri/test'); done(); }); }); }).not.throws(); });
it("should always report slow traces until 5 have been sent", function (done) { agent.apdexT = 0; var config = configurator.initialize(logger, { config : { apdex_t : 0, transaction_tracer : { enabled : true } } }); var aggregator = new TraceAggregator(config); var verifier = function (encoded, shouldExist) { if (shouldExist) { should.exist(encoded); } else { should.not.exist(encoded); } }; aggregator.add(createTransaction('/testOne', 503)); aggregator.once('harvest', function (encoded) { verifier(encoded, true); aggregator.add(createTransaction('/testTwo', 406)); aggregator.once('harvest', function (encoded) { verifier(encoded, true); aggregator.add(createTransaction('/testThree', 720)); aggregator.once('harvest', function (encoded) { verifier(encoded, true); aggregator.add(createTransaction('/testOne', 415)); aggregator.once('harvest', function (encoded) { verifier(encoded, true); aggregator.add(createTransaction('/testTwo', 510)); aggregator.once('harvest', function (encoded) { verifier(encoded, true); aggregator.add(createTransaction('/testOne', 502)); aggregator.once('harvest', function (encoded) { verifier(encoded, false); return done(); }); aggregator.harvest(); }); aggregator.harvest(); }); aggregator.harvest(); }); aggregator.harvest(); }); aggregator.harvest(); }); aggregator.harvest(); });
it("should have its own logical notion of a harvest cycle", function (done) { var config = configurator.initialize(logger, { config : { transaction_tracer : { enabled : true, top_n : 10 } } }); var aggregator = new TraceAggregator(config); aggregator.once('harvest', function firstHarvest(empty) { expect(empty).equal(undefined); expect(function addExists() { aggregator.add(createTransaction('/test', 4180)); }).not.throws(); aggregator.once('harvest', function finalHarvest(traceData) { expect(traceData).an('array'); expect(traceData.length).equal(8); expect(traceData[2]).equal('WebTransaction/Uri/test'); return done(); }); aggregator.harvest(); }); expect(function harvestExists() { aggregator.harvest(); }).not.throws(); });
it("should collect traces for transactions that exceed apdex_f", function () { var ABOVE_THRESHOLD = 29; var APDEXT = 0.007; var config = configurator.initialize(logger, { config : { transaction_tracer : { enabled : true, top_n : 10 } } }); var aggregator = new TraceAggregator(config) , transaction = new Transaction(agent) , trace = transaction.getTrace() ; aggregator.reported = 10; // needed to override "first 5" // let's violating Law of Demeter! transaction.metrics.apdexT = APDEXT; transaction.measureWeb('/test', 200, ABOVE_THRESHOLD); aggregator.add(transaction); expect(aggregator.requestTimes['WebTransaction/Uri/test']).equal(ABOVE_THRESHOLD); });
test("no proxy set should not use proxy agent", function (t) { var config = configurator.initialize({ 'app_name' : 'node.js Tests', 'license_key' : 'd67afc830dab717fd163bfcb0b8b88423e9a1a3b', 'host' : 'staging-collector.newrelic.com', 'port' : 443, 'ssl' : true, 'logging' : { 'level' : 'trace' }, 'feature_flag': { // FLAG: proxy proxy: true } }) , agent = new Agent(config) , api = new CollectorAPI(agent) ; api.connect(function cb_connect(error, returned) { t.notOk(error, "connected without error"); t.ok(returned, "got boot configuration"); t.ok(returned.agent_run_id, "got run ID"); t.ok(agent.config.run_id, "run ID set in configuration"); api.shutdown(function cb_shutdown(error, returned, json) { t.notOk(error, "should have shut down without issue"); t.equal(returned, null, "collector explicitly returns null"); t.deepEqual(json, {return_value : null}, "raw message looks right"); t.notOk(agent.config.run_id, "run ID should have been cleared by shutdown"); t.end(); }); }); });
fs.readdirSync('./controllers').forEach(function (file) { if(file.substr(-3) == '.js' && file.indexOf("ontroller") > -1) { var controller = require('./controllers/' + file); controllers.push(controller); controller.initialize(app); } });
beforeEach(function () { config = configurator.initialize({ transaction_tracer : { enabled : true } }); });
jobs.push(function(done){ init(api, options, function(serverObject){ api.servers.servers[serverName] = serverObject; api.log(['Initialized server: %s', serverName], 'debug'); return done(); }); });
test("Agent should send metrics to staging-tpm.oneapm.com", function (t) { var config = configurator.initialize({ 'app_name' : 'node.js Tests', 'license_key' : 'd67afc830dab717fd163bfcb0b8b88423e9a1a3b', 'host' : 'staging-tpm.oneapm.com', 'port' : 80, 'ssl' : false, 'logging' : { 'level' : 'trace' } }) , agent = new Agent(config) ; agent.start(function cb_start(error) { t.notOk(error, "started without error"); agent.metrics.measureMilliseconds('TEST/discard', null, 101); t.equal(agent.metrics.toJSON().length, 1, "only one metric"); agent._sendMetrics(function cb__sendMetrics(error) { t.notOk(error, "sent metrics without error"); agent.stop(function cb_stop(error) { t.notOk(error, "stopped without error"); t.end(); }); }); }); });
process.nextTick(function () { var api = require('./server/controllers/users'); var addResult = { // method for adding the user result send: function(r) { if(r.error) { // if there was a problem with the api adding the user return done(r.error); // return the error } else { return done(null, r); // otherwise return the user } } }; var findResult = { // method for user exists check result send: function(r) { if(r.error) { // if there's an error if(r.error === 'User not found') { // if not found create the user api.add({ body: { id: profile.id, username: profile.username }}, addResult); } else { return done(r.error); // otherwise return the error } } else { return done(null, r); // if found, return the user } } }; api.initialize(app.get('storageName'), app.get('storageKey')); // initialize Azure Storage api.findById({ params: { id: profile.id }}, findResult); // see if user exists });
it("should set apdexT on the supportability metrics on connect", function (done) { var config = configurator.initialize({ license_key : 'license key here', debug : {internal_metrics : true} }); debugged = new Agent(config); expect(debugged.config.debug.supportability.apdexT).equal(0.1); var redirect = nock(URL) .post(helper.generateCollectorPath('get_redirect_host')) .reply(200, {return_value : 'collector.newrelic.com'}); var connect = nock(URL) .post(helper.generateCollectorPath('connect')) .reply(200, {return_value : {agent_run_id : RUN_ID, apdex_t : 0.5}}); var shutdown = nock(URL) .post(helper.generateCollectorPath('shutdown', RUN_ID)) .reply(200, {return_value : null}); debugged.start(function () { expect(debugged.config.debug.supportability.apdexT).equal(0.5); redirect.done(); connect.done(); debugged.stop(function () { shutdown.done(); done(); }); }); });
test("Collector API should connect to staging-collector.newrelic.com", function (t) { var config = configurator.initialize({ 'app_name' : 'node.js Tests', 'license_key' : 'd67afc830dab717fd163bfcb0b8b88423e9a1a3b', 'host' : 'staging-collector.newrelic.com', 'port' : 80, 'logging' : { 'level' : 'trace' } }) , agent = new Agent(config) ; agent.start(function (error, returned) { t.notOk(error, "connected without error"); t.ok(returned, "got boot configuration"); t.ok(returned.agent_run_id, "got run ID"); t.ok(agent.config.run_id, "run ID set in configuration"); agent.stop(function (error) { t.notOk(error, "should have shut down without issue"); t.notOk(agent.config.run_id, "run ID should have been cleared by shutdown"); t.end(); }); }); });
beforeEach(function () { var config = configurator.initialize({ run_id : RUN_ID, license_key : 'license key here' }); agent = new Agent(config); });
value: function loadPlugins(projectDir, config) { var plugins = config.plugins; var options = {}; for (var plugin in plugins) { var val = plugins[plugin]; if (!val) { continue; } var found = this.findFile(plugin + '.js', projectDir, path.resolve(this.distDir, 'plugin')); if (!found) { try { found = require.resolve('tern-' + plugin); } catch (e) {} } if (!found) { try { found = require.resolve(this.projectDir + '/node_modules/tern-' + plugin); } catch (e) { atom.notifications.addError('Failed to find plugin ' + plugin + '\n', { dismissable: true }); continue; } } var mod = require(found); if (mod.hasOwnProperty('initialize')) { mod.initialize(this.distDir); } options[path.basename(plugin)] = val; } this.defaultPlugins(config).forEach(function (name) { if (!plugins.hasOwnProperty(name)) { options[name] = true; } }); return options; }
QUnit.test( 'isEditable() is false by default', function ( assert ) { var StatementPanel = require( pathToWidget ), config = { $element: $( '.wbmi-entityview-statementsGroup' ) }, sp = new StatementPanel( config ); sp.initialize(); assert.strictEqual( sp.isEditable(), false ); } );
QUnit.test( 'constructor', function ( assert ) { var StatementPanel = require( pathToWidget ), config = { $element: $( '.wbmi-entityview-statementsGroup' ) }, sp = new StatementPanel( config ); sp.initialize(); assert.ok( true ); } );
beforeEach(function () { var config = configurator.initialize(logger, { config : {rules : {ignore : [ /^\/ham_snadwich\/ignore/ ]}} }); configured = new Agent(config); });
beforeEach(function () { var config = configurator.initialize({ rules : {ignore : [ /^\/ham_snadwich\/ignore/ ]} }); agent = new Agent(config); });