Example #1
0
function getAccount(callback) {
  client.get(util.format("%s/accounts", baseURL), httpArgs,
    function(accounts, response) {
      if (response.statusCode != 200) {
        if (accounts.hasOwnProperty("error")) {
          callback(accounts.error, null);
        } else {
          callback(response.headers.status, null);
        }
        return;
      }
      callback(null, accounts[0].slug);
    })
}
 function (session, results) {
     session.userData.countryCode = results.response;
     var stateInfo = "";
     var Client = require('node-rest-client').Client;
     var client = new Client();
     // set content-type header and data as json in args parameter 
     var args = {
         data: { test: "hello" },
         headers: { "Content-Type": "application/json" }
     };
     client.get("http://services.groupkt.com/state/get/" + session.userData.countryCode + "/all", args, function (data, response) {
         // parsed response body as js object 
         var result = data["RestResponse"]["result"];
         for (var idx = 0; idx < result.length; idx++) {
             var info = result[idx];
             stateInfo = stateInfo + info["country"] + "-" + info["name"] + ",";
             console.log(info["country"] + "-" + info["name"]);
         }
         session.send("Hello " + session.userData.name + "! I am going to check the " + session.userData.product +
             " availability for the address:" + session.userData.address + ", ZipCode:" + session.userData.zipCode +
             "\nList of States for your country code:" + session.userData.countryCode + "\n" + stateInfo);
     });
 }
Example #3
0
app.get ('/jobList', function (req, response) {
    client.get(jenkinsURL + "/api/json", function (data, res) {
        x = data.jobs;
        var y = _.filter(x, {"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob"})
        output = [];
        for (var key in y) {
            output.push({Class:y[key]._class, Name:y[key].name, Color:y[key].color});
        }
        response.writeHeader(200, {"Content-Type" : "application/json"});
        response.write(JSON.stringify(output));
        response.end();
    });

});
Example #4
0
    .get(apicache('12 hours'), function(req, res) {
        var args = {};

        client.get(host.url + '/api/v1/directory', args,
            function(data, response) {
                var items = [];
                data = JSON.parse(data);

                data.forEach( function(product) {
                    items.push({"name":product.name});
                });
                res.json(items);
            });
    });
Example #5
0
 getAccount(function(err, slug) {
   exitIfErr(err, "Could not get account");
   accountslug = slug;
   client.post(util.format("%s/deployments/%s/%s/backups", baseURL,
     accountslug, deployment), httpArgs, function(backup, response) {
     if (response.statusCode != 201) {
       console.log(backup.error + " (" + response.headers.status + ")");
       process.exit(1);
     }
     backupId = backup.id;
     console.log("Backup started for with id=" + backupId)
     timerTimeout = setTimeout(backupReady, 15 * 1000);
   });
 });
Example #6
0
                request: (request, callback) => {
                    print('RFG:request', 'Posting a request to the RFG API');
                    client.post('http://realfavicongenerator.net/api/favicon', {
                        data: { favicon_generation: request },
                        headers: { 'Content-Type': 'application/json' }
                    }, (data, response) => {
                        const result = data.favicon_generation_result;

                        return result && response.statusCode === HTTP_SUCCESS ? callback(null, {
                            files: result.favicon.files_urls,
                            html: result.favicon.html_code
                        }) : callback(result.result.error_message);
                    });
                },
Example #7
0
                fetch: function fetch(address, callback) {
                    var name = path.basename(address),
                        image = contains(['.png', '.jpg', '.bmp', '.ico', '.svg'], path.extname(name));

                    print('RFG:fetch', 'Fetching ' + (image ? 'image' : 'file') + ' from RFG: ' + address);
                    client.get(address, function (buffer, response) {
                        var success = buffer && response.statusCode === HTTP_SUCCESS;

                        return success ? callback(null, {
                            file: image ? null : { name: name, contents: buffer },
                            image: image ? { name: name, contents: buffer } : null
                        }) : callback('Could not fetch URL: ' + address);
                    });
                }
Example #8
0
		function getFoodUnitID(userInfo, item_id) {
			console.log("Getting food id");
			var deferred = Q.defer();
			var client = new Client();
	        var fitbitUnitRequestURL = "https://api.fitbit.com/1/foods/" + item_id + ".json";

	        var args = {
				headers: {"Authorization": "Bearer " + userInfo.access_token} // request headers 
			};


			console.log("Sending args: ", args);
			client.get(fitbitUnitRequestURL, args, function(data, result) {
				var units = {
					unitType: data.food.defaultUnit.id,
					defaultAmount: data.food.defaultServingSize
				};
				console.log("has unit");
				console.log(units);
				deferred.resolve(units);  // fulfills the promise with 'units' as the value
			});
			return deferred.promise;
		}
Example #9
0
                fetch: (address, callback) => {
                    const name = path.basename(address),
                        image = contains(['.png', '.jpg', '.bmp', '.ico', '.svg'], path.extname(name));

                    print('RFG:fetch', `Fetching ${ image ? 'image' : 'file' } from RFG: ${ address }`);
                    client.get(address, (buffer, response) => {
                        const success = buffer && response.statusCode === HTTP_SUCCESS;

                        return success ? callback(null, {
                            file: image ? null : { name, contents: buffer },
                            image: image ? { name, contents: buffer } : null
                        }) : callback(`Could not fetch URL: ${ address }`);
                    });
                }
	client.post(KeyStoneURL, args, function(data,response) {
		token    = data.access.token.id;
		tenantId = data.access.token.tenant.id; 
		var args = {headers:{"Content-Type": "application/json", "Accept": "application/json","X-Auth-Token": token}}
		client.get(NovaURL+tenantId+'/'+'servers', args, function(data,response) {
			for (var i in data.servers) {
				if(data.servers[i].id == server_id) {
					client.get(NovaURL+tenantId+'/'+'servers'+'/'+server_id, args, function(resdata,response) {
						callback(resdata);
					});
				}
			}
		});
	});
var deleteAllServers = function(callback)
{
	var postData = '{"auth":{ "tenantName":"'+tenantName+'", "passwordCredentials": {"username":"'+userName+'","password":"'+userPswd+'"}}}';
	var args = { data: JSON.parse(postData), headers:{"Content-Type": "application/json"} };
	client = new restClient();
	client.post(KeyStoneURL, args, function(data,response) {
		token    = data.access.token.id;
		tenantId = data.access.token.tenant.id; 
		var args = {headers:{"Content-Type": "application/json", "Accept": "application/json","X-Auth-Token": token}}
		client.get(NovaURL+tenantId+'/'+'servers', args, function(data,response) {
			var list = [];
			for (var i in data.servers)
			{
				var server_id = data.servers[i].id;
				console.log('deleting server'+server_id);
				client.delete(NovaURL+tenantId+'/'+'servers'+'/'+server_id, args, function(data,response) {
					list[i] = data.servers[i].name;
				});
			}
			callback(list);
		});
	});
}
Example #12
0
	nexmo.checkVerifyRequest({request_id:req.query.requestId,code:req.query.keycode},function(err,verifyResponse) {	
		console.dir(err);
		console.dir(verifyResponse);
		if (err || verifyResponse.status != '0') {
			res.send({error:"Code verification Failed"});
			return;
		} else {
			var phonenumber = phoneNumberCache.get(req.query.requestId);
			if (phonenumber == undefined) {
				res.send({error:"Error retriving phonenumber from cache, please try again"});
				return;
			} else {
				client.get(appConfig.ShopifySiteName + "/admin/orders.json", 
				function(buf, response){
					var StringDecoder = require('string_decoder').StringDecoder;
					var decoder = new StringDecoder('utf8');
					var dataString = decoder.write(buf);
					var data = JSON.parse(dataString);
					console.log("order lookedup");
					var orders = data['orders'];
					var foundOrder;
					for (var orderKey in orders) {
						var order = orders[orderKey];
						var orderPhone = order['billing_address'].phone;
						if (orderPhone.length > phonenumber.length) {
							orderPhone = orderPhone.substring(orderPhone.length-phonenumber.length);
						} else if (orderPhone.length < phonenumber.length) {
							phonenumber = phonenumber.substring(phonenumber.length-orderPhone.length);
						}
						if (orderPhone === phonenumber) {
							foundOrder = order;
							console.log("found order");
							console.dir(order);
							break;
						} else {
							continue;
						}
					}
					//res.send(output);
					phoneNumberCache.del(req.query.requestId);
					if (foundOrder) {
						res.send({order:foundOrder})
					} else {
						res.send({error:"No Matching Orders found for this number"})
					}
					return;
				});
			}
		}
	});
Example #13
0
exports.index = function(req, res) {

	var client = new Client();
	client.get(endpoint, function(data, response_raw) {
		if (response_raw) {

			if (data) {
				json_responses = {
					"data" : data
				};
			}

			res.render('index', {
				values : data
			});
		}

		else {
			console.log("returned false");
			//		res.render('/womenerr');
		}
	});
};
                    tg.waitForRequest($.from.id, ($) => {
                      var monto = parseFloat($.message.text);

                      client.get('https://poloniex.com/public?command=returnTicker', (data, response) => {
                        var result_lsk = monto * parseFloat(data.BTC_LSK.last);
                        client.get('https://api.bitfinex.com/v1/pubticker/btcusd', function(data, response){
                          var rate_usd = parseFloat(data.high) + parseFloat(data.low);
                              rate_usd = rate_usd / 2;
                          var result_convert = result_lsk / rate_usd;
                          botan.track($.message, 'Convert Inline Menu');
                          $.sendMessage("" + monto + " $ equivalen a " + result_convert.toFixed(2) + " DAO");
                        });
                      });
                    });
                      tg.waitForRequest($.from.id, ($) => {
                        var monto = parseFloat($.message.text);

                        client.get('https://api.blinktrade.com/api/v1/BRL/ticker', function(data, response){
                            data = JSON.parse(data);
                            var rate_brl = parseFloat(data.high) + parseFloat(data.low);
                                rate_brl = rate_brl / 2;

                            var result = monto / rate_brl;

                            botan.track($.message, 'Convert Inline Menu');
                            $.sendMessage("" + monto + " R$ equivalen a " + result.toFixed(2) + "BTC");
                        });
                      });
Example #16
0
    .get(apicache('1 hours'), function(req, res) {

        var category_name = req.params.category_name;

        client.get(host.url + '/api/v1/directory', {},
            function(data, response) {
                data = JSON.parse(data);
                data.forEach(function(item) {
                    if (item.name === category_name) {
                        res.json(item);
                    }
                })
            });
    });
Example #17
0
meta.prototype.track = function (trackId, callback) {

  var url = 'http://developer.echonest.com/api/v4/song/profile';

  // direct way
  client = new Client();

  args = {
    // data passed to REST method (only useful in POST, PUT or PATCH methods)
    parameters: {
      format: "json",
      bucket: "audio_summary",
      api_key: this.apiKey,
      id: trackId
    }
  };
  var me = this;
  client.get(url, args, function (song, response) {
    song = JSON.parse(song);

    var analysisUrl = song.response.songs[0].audio_summary.analysis_url;

    me.emit('song', song);
    // parsed response body as js object
    // raw response
    var client = new Client();

    client.get(analysisUrl, {}, function (data, response) {
      me.emit('analysis', data);
      callback(data);
    }).on('error', function (err) {
      me.emit('error', err);
    });
  }).on('error', function (err) {
    me.emit('error', err);
  });
};
Example #18
0
router.get('/public/summoner/:id/data', jsonParser, function(req, res) {

    if (!req.params.id) {
        res.status("200").send({
            result: "failure",
            reason: "Wrong ID Input"
        });
    } else {
        //Get Summoner Information
        var id = req.params.id;
        var region = 'na';
        client.get(host + region + "/v1.4/summoner/" + id + "?api_key=" + api_key,
            function(data, response) {
                // parsed response body as js object
                // raw response
                console.log(data);
                if (!data) {
                    res.status("200").send({
                        result: "failure",
                        reason: "Champion not found!"
                    });
                } else {
                    var summonerInfo = data[id];
                    client.get(host + region + "/v2.5/league/by-summoner/" + id + "/entry?api_key=" + api_key,
                        function(data, response) {
                            // parsed response body as js object
                            // raw response
                            // console.log("https://na.api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + id + "/entry?api_key=" + api_key);
                            // console.log(id, region);
                            // console.log(data);
                            if (!data[id]) {
                                res.send({
                                    info: summonerInfo
                                });
                            } else {
                                var summonerRanked = data[id][0];
                                res.send({
                                    info: summonerInfo,
                                    ranked: summonerRanked
                                });
                            }
                            // res.json(data.name);
                        });

                }

            });
    }
});
Example #19
0
		client.get(url + "/@license", function(data) {
			if (typeof data === "string") {
				try {
					data = JSON.parse(data);
				}
				catch(e) {
					//console.log(data);
					if (data.length > 6 && data.substring(0, 6) === '<html>') {
						console.log('The server is alive, but the URL seems to be incorrect.'.red);
						return;
					}
					console.log(('Unable to parse server response - please make sure your URL is correct: ' + e).red);
					return;
				}
			}
			if (data.errorMessage) {
				console.log(data.errorMessage.red);
				return;
			}
			console.log("This server licensed to: " + data.company.red);

			client.post(url + "/@authentication",
				{
					data: {
						username: cmd.username,
						password: cmd.password
					},
					headers: {"Content-Type": "application/json"}
				},
				function(data, response) {
					if (data.errorMessage) {
						console.log(("Login failed: " + data.errorMessage).red);
						return;
					}
					var fullData = {
						url: url,
						userName: cmd.username,
						alias: cmd.serverAlias,
						loginInfo: data
					};
					dotfile.writeToDotFile(url, fullData);
					dotfile.setCurrentServer(url, fullData);
					console.log(('Login successful, API key will expire on: ' + data.expiration).green);
				}).on('error', function(err) {
					console.log(('ERROR: ' + err).red);
					throw "Error logging in: " + err;
				}
			);
		});
Example #20
0
exports.index = function(req, res){
	var http = require('http');
	var Client = require('node-rest-client').Client;
	var client = new Client();
	var secretkey = "qwerty123456789";
	var crypto = require('crypto');
	var algorithm = "sha256";
	
	client.get("https://api.mongolab.com/api/1/databases/cmpe_281/collections/Gumball?apiKey=O1eUOdvOeHo17UcWx9pGUN7ed0VH-qkz",function(req , resp){
		//console.log(data);
		
		var encrypt  = crypto.createHmac(algorithm,secretkey);
		encrypt.setEncoding('hex');
    	var text = req[0].model+req[0].serialNumber+req[0].count+"NoCoinState";
    	encrypt.write(text);
    	encrypt.end();
    	var hash = encrypt.read();
        console.log(req);
        console.log(hash);
        res.render('index', { id:req[0]._id,model : req[0].model, serialNumber : req[0].serialNumber, state:"NoCoinState", count :req[0].count,hashmsg: hash});
	});


};
Example #21
0
exports.women = function(req, res){

    var client = new Client();
  //  var datf = "error";
            client.get( endpoint, function(data, response_raw){
            	if(response_raw) {
  
            		//console.log(response_raw);
            		console.log(data[0].countGumballs) ;
                    console.log(data[0].modelNumber) ;
                    console.log(data[0].serialNumber) ;
                    count = data[0].countGumballs
                    console.log( "count = " + count ) ;
                    //res.end( "count = " + count + "\n");
                    
                    res.render('women', { data: data });
            	} 
            	
            	else {
    				console.log("returned false");
  //  				res.render('/womenerr');
            	}
            	 });
}
Example #22
0
	htmIndexResponse: function(done) {
		var nodeserver = new nodeserverClass(false);
		nodeserver.readConfig({
			nodeserver: {
				admin: {}
			},
			sites: [{
				name: 'CDN Site',
				type: 'cdn',
				bindings: [
					'localhost:3000'
				],
				script: __dirname + '/../webs/cdn'
			}]
		});

		nodeserver.start();


		var serverStatus = function(status) {
			assert(status, 'The index content not correct');
			nodeserver.exit();
			done();
		};


		
		var client = new Client();
		client.get('http://localhost:3000/index.htm', function (data, response) {
			if(data == 'index-htm-ok') {
				serverStatus(true);
			} else {
				serverStatus(false);
			}
		});
	}
Example #23
0
        getAuthToken(options.serviceendpoints.identity, options.username, options.password, options.tenantName, function(err, token) {
            if (token) {
                logger.debug("Token Id::" + token);
                logger.debug("Tenant Id::" + tenantId);

                var args = {
                    headers: {
                        "X-Auth-Token": token
                    }
                };

                client = new Client();

                var serversUrl = options.serviceendpoints.compute + '/' + tenantId + '/servers';

                logger.debug("serversUrl:" + serversUrl);
                client.registerMethod("jsonMethod", serversUrl, "GET");

                client.methods.jsonMethod(args, function(data, response) {
                    logger.debug("get Servers Response::" + data);
                    if (data.servers) {
                        logger.debug("END:: getServers");
                        callback(null, data);
                        return;
                    } else {
                        logger.debug("Error in getServers");
                        callback(data, null);
                    }
                });
            } else {
                logger.debug("error:" + err);
                callback(err, null);
                return;
            }

        });
Example #24
0
exports.index = function(req, res) {
	var http = require('http');
	var ts=new Date().getTime();
	var state="NoCoinState";
	var hash=getHash(state,ts);
	
	var Client = require('node-rest-client').Client;
	var client = new Client();

	// direct way
	client.get("http://gumballnoderest-deepakkole.rhcloud.com/gumball/1", function(data,
			response) {

		var count=data.countGumballs;
		var msg="\n\n Mighty Gumball INC \n Model#"+data.modelNumber+"\n"+"Serial #"+data.serialNumber+"\n"+"\n"+state+"\n\n";
		

		res.render('index', {
			message : msg,state:state,ts:ts,hash:hash,modelNumber:data.modelNumber,serialNumber:data.serialNumber
		});

	});

};
Example #25
0
function viewAllVehicles() {
    var postData = {}; // Prepare the rest data that will be used in the post request. In case of ViewAllVehicles, it will be empty body
    // set content-type header and data as json in args parameter 
    var args = {
        data: postData,
        headers: {
            'X-API-KEY': apiKey,
            'Content-Type': 'application/json' //How the Data will be returned from API. In case of Detrack API it will be JSON format
        }
    };
    client.post("https://app.detrack.com/api/v1/vehicles/view/all.json", args, function (data, response) {
        console.log(data);
        console.log("vehicle name: " + data["vehicles"][0]["name"]); //Return data is in JSON array format. Access the individual Elements with index or iterate over it to access the individual property
    });
}
Example #26
0
function getSensorId(callback) {
	console.log("\n\n==========================================");
    console.log("GETing sensor id command.");
    console.log("------------------------------------------");
	var requestData = {
		headers:{
			"Accept": "application/json"
		}
	};
	client.get("http://localhost:8080/amtProject/v1/api/sensors", requestData, function(data, response) {
		sensorIdGlobal = data[0].id;
		console.log("GETSENSORID response status code: " + response.statusCode);
		callback(null, "The GETSENSORID operation has been processed (status code: " + response.statusCode + ")");
	});
}
Example #27
0
exports.getInsert=function(req,res)
{
	
		var client=new Client();	
		var state=req.param('state');	
		console.log("Insert"+state);

		
		client.get("http://grailsgumballmachinev2.cfapps.io/gumballs/1",function(info,response){
						
						var info1=
							
						{
								id:info.id,
								countGumballs:info.countGumballs,
								modelNumber:info.modelNumber,
								serialNumber:info.serialNumber,
								state: "HasCoinState"
						};
						
			
					res.render('home',{page_title:"Edit Customers - Node.js",data:info1});
		});
};
Example #28
0
		GoogleBooks.findOne({id : req.params.book_isbn}, function(err, book) {
			if (book){
				var arr = [];
				arr.push(book);
				res.json(arr);
			}
			
			else {
			        client.get("https://www.googleapis.com/books/v1/volumes?q="+req.params.book_isbn, function(rsdata, restRes) {
                       	var temp = JSON.parse(rsdata);
                      	res.send(temp.items);
                    });
			}
			
		});
module.exports.sendPostRequest = function (cba, reply) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

    var baseUri = config.contextbroker.protocol + "://" + config.contextbroker.hostname + ":" + config.contextbroker.port;

    client.post(baseUri + "/v1/updateContext", cba, function (data, response) {
        logger.info("Request to Context Broker. URI: " + JSON.stringify(baseUri));
        logger.info("Response from Context Broker. HEADERS: " + JSON.stringify(response.headers));
        logger.info("Response from Context Broker. BODY: " + JSON.stringify(data));

        reply(JSON.stringify(data));
    })
        .on('error', function (err) {
            logger.error('Something went wrong on the request', JSON.stringify(err.request.options));
        });
};
Example #30
0
	login = function(req, res){
		console.log(req.body);
		
		var args = {
		  data: req.body,
		  headers:{"Content-Type": "application/json"} 
		};

		client.post("http://localhost:5000/login",args,function(data,response){
	  	//client.get("https://polar-fortress-3883.herokuapp.com/getsesion/2491196788",function(data,response){
			console.log(data);
			//res.send(data);
			console.log(__dirname +'../www/home.html');
			res.sendfile('/Users/marttin/node/ccles/www/home.html');
		});
	};