Created
October 5, 2014 22:39
-
-
Save lbrenman/f8ae358854e0e62dbaf4 to your computer and use it in GitHub Desktop.
Appcelerator Titanium Node.ACS REST to REST example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"routes": [ { | |
"path": "/", | |
"callback": "application#index" | |
}, { | |
"path": "/getMovies", | |
"method": "get", | |
"callback": "services#getMovies" | |
} ], | |
"filters": [ { | |
"path": "/", | |
"callback": "" | |
} ], | |
"websockets": [ { | |
"event": "", | |
"callback": "" | |
} ] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var startTime, endTime; | |
function infoBtnClick(){ | |
Ti.API.info("index: $.infoBtnClick.addEventListener(click)"); | |
alert("Node.ACS Demo\nC-WS RT = Client Web Service Response Time\nTTime = total time\nS-WS RT = Server Web Service Response Time\nTTime = total time"); | |
}; | |
$.tabBar.addEventListener('click', function(){ | |
Ti.API.info("index: $.tabBar.addEventListener(click)"); | |
switch($.tabBar.index) { | |
case 0: | |
$.serverDataVW.height=0; | |
$.sTotalTimeLBL.text = "-- mS"; | |
$.sResponseTimeLBL.text = "-- mS"; | |
break; | |
case 1: | |
$.serverDataVW.height=Ti.UI.SIZE; | |
break; | |
case 2: | |
$.serverDataVW.height=Ti.UI.SIZE; | |
break; | |
} | |
}); | |
$.movieTV.addEventListener('click', function(e) { | |
Ti.API.info("index: $.movieTV.addEventListener(click)"); | |
}); | |
$.movieTF.addEventListener('click', function(e){ | |
Ti.API.info("index: $.movieTF.addEventListener(click)"); | |
//clearTable(); | |
}); | |
$.movieTF.addEventListener('return', function(e){ | |
Ti.API.info("index: $.movieTF.addEventListener(change)"); | |
clearTable(); | |
searchForMovies(); | |
}); | |
$.searchBTN.addEventListener('click', function(e){ | |
Ti.API.info("index: $.searchBTN.addEventListener(click)"); | |
clearTable(); | |
searchForMovies(); | |
}); | |
function clearTable(){ | |
Ti.API.info("index: clearTable()"); | |
var rd = []; | |
$.movieTV.data=rd; | |
} | |
function searchForMovies(){ | |
Ti.API.info("index: searchForMovies()"); | |
if(!($.movieTF.value==="" || $.movieTF.value===null)) { | |
getMovies($.movieTF.value, { | |
success: function(e) { | |
Ti.API.info('Received data = '+e); | |
loadTable(e); | |
}, | |
error: function(e) { | |
Ti.API.info('Error = '+e); | |
alert("No network or server not available. Please try again."); | |
} | |
}); | |
} | |
} | |
function loadTable(e) { | |
Ti.API.info("index: loadTable()"); | |
var reply = JSON.parse(e); | |
var rows = []; | |
var i = 0; | |
Ti.API.info("index: reply = "+JSON.stringify(reply)); | |
Ti.API.info("index: reply.total = "+reply.total); | |
if(reply.movies.length>0){ | |
_.each(reply.movies, function(item) { | |
rows.push(Alloy.createController('movieRow', { | |
name: item.title, | |
year: item.year, | |
}).getView()); | |
}); | |
} | |
else { | |
alert("No movies found."); | |
} | |
$.movieTV.setData(rows); | |
endTime = new Date().getTime(); | |
$.cTotalTimeLBL.text = endTime-startTime+" mS"; | |
if($.tabBar.index != 0){ | |
$.sTotalTimeLBL.text = reply.tottime+" mS"; | |
$.sResponseTimeLBL.text = reply.wstime+" mS"; | |
} | |
} | |
function getMovies(text, o){ | |
Ti.API.info("getMovies() - text = "+text); | |
if(Titanium.Network.networkType == Titanium.Network.NETWORK_NONE){ | |
Ti.API.info("index: getMovies() - No Network"); | |
if (o.error) { o.error("No Network"); }; | |
return; | |
} | |
var xhr = Titanium.Network.createHTTPClient({ | |
onload: function() { | |
endTime = new Date().getTime(); | |
$.cResponseTimeLBL.text = endTime-startTime+" mS"; | |
if (o.success) { o.success(this.responseText); }; | |
}, | |
onerror: function(e) { | |
if (o.error) { o.error("Error with Rotten Tomatoes API"); }; | |
}, | |
timeout: 10000, | |
}); | |
var DirectURL = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q="+text+"&apikey=<YOUR ROTTEN TOMATOES API KEY>"; | |
var NodeURL = "https://<YOUR NODE.ACS BASE ADDRESS>.cloudapp-enterprise.appcelerator.com/getMovies?searchText="+text; | |
var OSNodeURL = "https://nodejs-lbrenman.rhcloud.com/getMovies?searchText="+text; | |
var url = DirectURL; | |
switch($.tabBar.index) { | |
case 0: | |
url=DirectURL; | |
break; | |
case 1: | |
url=url=NodeURL; | |
break; | |
case 2: | |
url=OSNodeURL; | |
break; | |
} | |
Ti.API.info("url = "+url); | |
startTime = new Date().getTime(); | |
xhr.open("GET", url); | |
xhr.send(); | |
}; | |
$.index.open(); | |
$.tabBar.setIndex(0); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Alloy> | |
<Window class="container" layout="vertical"> | |
<View height="40" backgroundColor="black"> | |
<Label color="white">Node.ACS Demo</Label> | |
<Button right="10" onClick="infoBtnClick" color="white">I</Button> | |
</View> | |
<View height="Ti.UI.SIZE" backgroundColor="darkgray" layout="horizontal"> | |
<Label color="white" left="10">C-WS RT: </Label> | |
<Label id="cResponseTimeLBL" color="white" left="5">-- ms</Label> | |
<Label color="white" left="20">TTime:</Label> | |
<Label id="cTotalTimeLBL" color="white" left="5">-- ms</Label> | |
</View> | |
<View id="serverDataVW" height="0" backgroundColor="darkgray" layout="horizontal"> | |
<Label color="white" left="10">S-WS RT: </Label> | |
<Label id="sResponseTimeLBL" color="white" left="5">-- ms</Label> | |
<Label color="white" left="20">TTime:</Label> | |
<Label id="sTotalTimeLBL" color="white" left="5">-- ms</Label> | |
</View> | |
<View height="40"> | |
<TabbedBar id="tabBar"> | |
<Labels> | |
<Label>Client</Label> | |
<Label>Node.ACS</Label> | |
<Label>OpenShift</Label> | |
</Labels> | |
</TabbedBar> | |
</View> | |
<View layout="vertical"> | |
<View layout="horizontal" height="Ti.UI.SIZE"> | |
<TextField id="movieTF" hintText="Enter search term" top="20" width="70%"/> | |
<Button id="searchBTN" width="20%" top="15">Search</Button> | |
</View> | |
<TableView id="movieTV" top="20"/> | |
</View> | |
</Window> | |
</Alloy> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var args = arguments[0] || {}; | |
//Ti.API.info("row created, args.name = "+args.name); | |
$.movieRow.name = args.name; | |
$.movieRow.year = args.year; | |
$.movieLbl.text = args.name; | |
$.yearLbl.text = args.year; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Alloy> | |
<TableViewRow class="movieTVR"> | |
<Label id="movieLbl" width="80%" left="10"/> | |
<Label id="yearLbl" width="20%" right="0"/> | |
</TableViewRow> | |
</Alloy> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env node | |
// OpenShift sample Node application | |
var express = require('express'); | |
var fs = require('fs'); | |
var https = require('http'); | |
/** | |
* Define the sample application. | |
*/ | |
var SampleApp = function() { | |
// Scope. | |
var self = this; | |
/* ================================================================ */ | |
/* Helper functions. */ | |
/* ================================================================ */ | |
/** | |
* Set up server IP address and port # using env variables/defaults. | |
*/ | |
self.setupVariables = function() { | |
// Set the environment variables we need. | |
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP; | |
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8080; | |
if (typeof self.ipaddress === "undefined") { | |
// Log errors on OpenShift but continue w/ 127.0.0.1 - this | |
// allows us to run/test the app locally. | |
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1'); | |
self.ipaddress = "127.0.0.1"; | |
}; | |
}; | |
/** | |
* Populate the cache. | |
*/ | |
self.populateCache = function() { | |
if (typeof self.zcache === "undefined") { | |
self.zcache = { 'index.html': '' }; | |
} | |
// Local cache for static content. | |
self.zcache['index.html'] = fs.readFileSync('./index.html'); | |
}; | |
/** | |
* Retrieve entry (content) from cache. | |
* @param {string} key Key identifying content to retrieve from cache. | |
*/ | |
self.cache_get = function(key) { return self.zcache[key]; }; | |
/** | |
* terminator === the termination handler | |
* Terminate server on receipt of the specified signal. | |
* @param {string} sig Signal to terminate on. | |
*/ | |
self.terminator = function(sig){ | |
if (typeof sig === "string") { | |
console.log('%s: Received %s - terminating sample app ...', | |
Date(Date.now()), sig); | |
process.exit(1); | |
} | |
console.log('%s: Node server stopped.', Date(Date.now()) ); | |
}; | |
/** | |
* Setup termination handlers (for exit and a list of signals). | |
*/ | |
self.setupTerminationHandlers = function(){ | |
// Process on exit and signals. | |
process.on('exit', function() { self.terminator(); }); | |
// Removed 'SIGPIPE' from the list - bugz 852598. | |
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', | |
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM' | |
].forEach(function(element, index, array) { | |
process.on(element, function() { self.terminator(element); }); | |
}); | |
}; | |
/* ================================================================ */ | |
/* App server functions (main app logic here). */ | |
/* ================================================================ */ | |
/** | |
* Create the routing table entries + handlers for the application. | |
*/ | |
self.createRoutes = function() { | |
self.routes = { }; | |
self.routes['/asciimo'] = function(req, res) { | |
var link = "http://i.imgur.com/kmbjB.png"; | |
res.send("<html><body><img src='" + link + "'></body></html>"); | |
}; | |
self.routes['/'] = function(req, res) { | |
res.setHeader('Content-Type', 'text/html'); | |
res.send(self.cache_get('index.html') ); | |
}; | |
self.routes['/getMovies'] = function(req, res) { | |
startTime = new Date().getTime(); | |
console.log("start time = "+startTime); | |
console.log(req.query.searchText); | |
var myreq = https.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+req.query.searchText+'&apikey=<YOUR ROTTEN TOMATOES API KEY>', function(r) { | |
var str=""; | |
var results=[]; | |
var response={}; | |
r.setEncoding('utf8'); | |
r.on('data', function (chunk) { | |
str += chunk; | |
}); | |
r.on('end', function () { | |
endTime = new Date().getTime(); | |
console.log("end time = "+endTime); | |
wsTime = endTime-startTime; | |
console.log("ws time = "+wsTime); | |
var d = JSON.parse(str); | |
console.log(d.movies.length); | |
var dlength = d.movies.length; | |
for(var i=0; i<dlength;i++){ | |
var o={}; | |
o.title = d.movies[i].title; | |
o.year = d.movies[i].year; | |
results.push(o); | |
} | |
console.log(results); | |
endTime = new Date().getTime(); | |
console.log("end time = "+endTime); | |
totTime = endTime-startTime; | |
console.log("end time = "+totTime); | |
response = {wstime: wsTime, tottime: totTime, "movies":results}; | |
res.write(JSON.stringify(response)); | |
res.end(); | |
}); | |
}); | |
}; | |
}; | |
/** | |
* Initialize the server (express) and create the routes and register | |
* the handlers. | |
*/ | |
self.initializeServer = function() { | |
self.createRoutes(); | |
self.app = express.createServer(); | |
// Add handlers for the app (from the routes). | |
for (var r in self.routes) { | |
self.app.get(r, self.routes[r]); | |
} | |
}; | |
/** | |
* Initializes the sample application. | |
*/ | |
self.initialize = function() { | |
self.setupVariables(); | |
self.populateCache(); | |
self.setupTerminationHandlers(); | |
// Create the express server and routes. | |
self.initializeServer(); | |
}; | |
/** | |
* Start the server (starts up the sample application). | |
*/ | |
self.start = function() { | |
// Start the app on the specific interface (and port). | |
self.app.listen(self.port, self.ipaddress, function() { | |
console.log('%s: Node server started on %s:%d ...', | |
Date(Date.now() ), self.ipaddress, self.port); | |
}); | |
}; | |
}; /* Sample Application. */ | |
/** | |
* main(): Main code. | |
*/ | |
var zapp = new SampleApp(); | |
zapp.initialize(); | |
zapp.start(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var https = require('http'); | |
var startTime, endTime, wsTime, totTime; | |
function getMovies(req, res) { | |
startTime = new Date().getTime(); | |
console.log("start time = "+startTime); | |
console.log(req.query.searchText); | |
var myreq = https.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+req.query.searchText+'&apikey=<YOUR ROTTEN TOMATOES API KEY>', function(r) { | |
var str=""; | |
var results=[]; | |
var response={}; | |
r.setEncoding('utf8'); | |
r.on('data', function (chunk) { | |
str += chunk; | |
}); | |
r.on('end', function () { | |
endTime = new Date().getTime(); | |
console.log("end time = "+endTime); | |
wsTime = endTime-startTime; | |
console.log("ws time = "+wsTime); | |
var d = JSON.parse(str); | |
console.log(d.movies.length); | |
var dlength = d.movies.length; | |
for(var i=0; i<dlength;i++){ | |
var o={}; | |
o.title = d.movies[i].title; | |
o.year = d.movies[i].year; | |
results.push(o); | |
} | |
console.log(results); | |
endTime = new Date().getTime(); | |
console.log("end time = "+endTime); | |
totTime = endTime-startTime; | |
console.log("end time = "+totTime); | |
response = {wstime: wsTime, tottime: totTime, "movies":results}; | |
res.write(JSON.stringify(response)); | |
res.end(); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment