Connecting to Openshift WebSocket issue - openshift

I'm trying to make my OpenShift Node.js app working, but the WS connection is not working. Client error is: connection refused.
Client side factory service:
var dataStream = $websocket(localStorageService.get('wsUrl'))
dataStream.onMessage(function(message) {
var call = JSON.parse(message.data)
if (fnMap[call.fn]) {
fnMap[call.fn](call.event, call.data)
}
})
dataStream.onError(function(err) {
console.log(err)
})
dataStream.onClose(function(event){
console.log('event: ' + JSON.stringify(event))
})
var fnMap = {
"broadcastResult": function(event, data) {
$rootScope.$broadcast(event, data)
}
}
var methods = {
callFn: function(paramJSON) {
dataStream.send(JSON.stringify(paramJSON));
}
}
return methods
I'm trying to connect on the following URL: ws://myapp-myname.rhcloud.com:8000
Could you please help?
Thank you in advance,
Csaba

First, you may want to make sure the websocket library, ws, is installed by declaring it in the dependencies section of your package.json and then doing another git push.
Otherwise, try the example provided in the openshift blog: https://blog.openshift.com/paas-websockets/
Specifically:
var websocket = new WebSocket("ws://myapp-myname.rhcloud.com:8000");
websocket.onopen = function(event) {
// The connection was opened
console.log(event)
};
websocket.onclose = function(event) {
// The connection was closed
console.log(event)
};
websocket.onmessage = function(event) {
// New message arrived
message = event.data
console.log(event)
};
websocket.onerror = function(event) {
// There was an error with your WebSocket
console.log(event)
};
The above at least might help point you toward a specific part of your code that's not working. Or, if the example isn't even working, it could be possibly something wrong with your cartridge, and you could try reaching out to RedHat's support.

Related

Alexa and mysql remote endpoint cannot be called or has invalid input

I'm trying to connect alexa to mysql.
The database is stored in localhost,via xampp.
I've got nodejs-mysql connection perfectly, but when i try to incorporate it with alexa, it says
"The remote endpoint could not be called, or the response it returned was invalid."
My database file:-
var mysql=require('mysql');
var con=mysql.createConnection({
host:'localhost',
user: 'root',
password:'',
database:'ctp'
});
function answer(){}
answer.prototype.getdata= function(question,callback)
{
sql="select answer from jarvis where question="+question;
con.query(sql,function(err,rows,fields)
{
callback(rows);
})
}
module.exports=answer;
My index.js file:-
'use strict';
var AlexaSkill = require('./AlexaSkill'),
recipes = require('./recipes'),
dbcon=require('./dbconfig');
var mys=new dbcon();
var APP_ID = "amzn1.ask.skill.1bfd2f06-1c46-464f-9f06-9195691e0aae"; //OPTIONAL: replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]';
var HowTo = function () {
AlexaSkill.call(this, APP_ID);
};
// Extend AlexaSkill
HowTo.prototype = Object.create(AlexaSkill.prototype);
HowTo.prototype.constructor = HowTo;
HowTo.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
var speechText = "Welcome to My Jarvis, version 1 point oh... How can I help you?";
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
var repromptText = "For instructions on what you can say, please say help me.";
response.ask(speechText, repromptText);
};
HowTo.prototype.intentHandlers =
{
"QuestionIntent": function (intent, session, response) {
var itemSlot = intent.slots.Item,
itemName,sp;
if (itemSlot && itemSlot.value){
itemName = itemSlot.value.toLowerCase();
}
sp=itemName;
mys.getdata(sp,function(rows)
{
sp=rows;
});
var cardTitle = "Details for " + itemName,
//recipe=recipes[itemName],
recipe = sp,
speechOutput,
repromptOutput;
if (recipe) {
//window.open("http://www.w3schools.com");
speechOutput = {
speech: recipe,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
response.tellWithCard(speechOutput, cardTitle, recipe);
} else {
var speech;
speech = "There are no plans for you today";
}
speechOutput = {
speech: speech,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
repromptOutput = {
speech: "What else can I help with?",
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
response.ask(speechOutput, repromptOutput);
},
"AMAZON.StopIntent": function (intent, session, response)
{
var speechOutput = "Goodbye";
response.tell(speechOutput);
},
"AMAZON.CancelIntent": function (intent, session, response) {
var speechOutput = "Goodbye";
response.tell(speechOutput);
},
"AMAZON.HelpIntent": function (intent, session, response) {
var speechText = "You can ask questions such as, what's the plan for today, or, you can say exit... Now, what can I help you with?";
var repromptText = "You can say things like, what's the plan for today, or you can say exit... Now, what can I help you with?";
var speechOutput = {
speech: speechText,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
var repromptOutput = {
speech: repromptText,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
response.ask(speechOutput, repromptOutput);
}
};
//what code do you want to see?
exports.handler = function (event, context)
{
var howTo = new HowTo();
howTo.execute(event, context);
};
i have two sp assignments because i want to see if the function call works or not, well it doesnt and it's displaying only the identified itemName
So seeing previous forums, Some amazon helper told me to put lambda request as a test event in lambda console, I've tried it and got
{
"errorMessage": "RequestId: 7a56e239-d4cc-11e6-9671-cfba622fbaaf Process exited before completing request"
}
I want to know why alexa does not wait for the callback to execute and query the result back to sp and into the speechOutput ,
Also, how can context.done()/succeed() help this? I've tried to pass context object to the dbconfig file but it just doesnt work.
Can you tell me a solution for this? or atleast provide alexa-mysql documentation if it exists?

Login Service implementation in angularjs not working

This is my controller which is calling the login service
mod.controller("loginCtrl",function($scope,loginService,$http)
{
$scope.Userlogin = function()
{
var User = {
userid :$scope.uname,
pass:$scope.pass
};
var res = UserloginService(User);
console.log(res);
alert("login_succ");
}
});
And this is the login service code which takes the User variable and checks for username & password
mod.service("loginService",function($http,$q) {
UserloginService = function(User) {
var deffered = $q.defer();
$http({
method:'POST',
url:'http://localhost:8080/WebApplication4_1/login.htm',
data:User
}).then(function(data) {
deffered.resolve(data);
}).error(function(status) {
deffered.reject({
status:status
});
});
return deffered.promise;
// var response = $http({
//
// method:"post",
// url:"http://localhost:8080/WebApplication4_1/login.htm",
// data:JSON.stringify(User),
// dataType:"json"
// });
// return "Name";
}
});
I have created a rest api using springs which upon passing json return back the username and password in json like this
Console shows me this error for angular
You need to enable CORS for your application for guidance see this link
https://htet101.wordpress.com/2014/01/22/cors-with-angularjs-and-spring-rest/
I prefer to use Factory to do what you're trying to do, which would be something like this:
MyApp.factory('MyService', ["$http", function($http) {
var urlBase = "http://localhost:3000";
return {
getRecent: function(numberOfItems) {
return $http.get(urlBase+"/things/recent?limit="+numberOfItems);
},
getSomethingElse: function(url) {
return $http.get(urlBase+"/other/things")
},
search: function (searchTerms) {
return $http.get(urlBase+"/search?q="+searchTerms);
}
}
}]);
And then in your controller you can import MyService and then use it in this way:
MyService.getRecent(10).then(function(res) {
$scope.things = res.data;
});
This is a great way to handle it, because you're putting the .then in your controller and you are able to control the state of the UI during a loading state if you'd like, like this:
// initialize the loading var, set to false
$scope.loading = false;
// create a reuseable update function, and inside use a promise for the ajax call,
// which is running inside the `Factory`
$scope.updateList = function() {
$scope.loading = true;
MyService.getRecent(10).then(function(res) {
$scope.loading = false;
$scope.things = res.data;
});
};
$scope.updateList();
The error in the console shows two issues with your code:
CORS is not enabled in your api. To fix this you need to enable CORS using Access-Control-Allow-Origin header to your rest api.
Unhandled rejection error, as the way you are handling errors with '.error()' method is deprecated.
'Promise.error()' method is deprecated according to this and this commit in Angular js github repo.
Hence you need to change the way you are handling errors as shown below :
$http().then(successCallback, errorCallback);
function successCallback (res) {
return res;
}
function errorCallback (err) {
return err;
}
One more thing in your code which can be avoided is you have defined a new promise and resolving it using $q methods, which is not required. $http itself returns a promise by default, which you need not define again inside it to use it as a Promise. You can directly use $http.then().

Delete function not working in JSONStore in Mobilefirst Platform

I'm trying to delete a value which is stored in JSONStore. I'm facing this error:
03-26 18:52:10.391: I/chromium(1890): [INFO:CONSOLE(0)] "document.clear() is deprecated. This method doesn't do anything.", source: (0)
and the value is not not deleted.
Here is the code:
function clear() {
var collectionName = 'people';
//Build the query object
var query = {
_id: 3
};
var options = {
exact: true
};
try {
WL.JSONStore.get(collectionName).remove(query, options)
.then(function(res) {
alert("Success" + res);
})
.fail(function(errorObject) {
alert(errorObject.msg);
});
} catch (e) {
_logError("");
}
}
I would really appreciate the help. Thanks.
well, this error occur because you set clear function but moiblefist(worklight) has this type of API clear so i think it is a bug . you should be use aother name which not in moiblefist API method .
or try with latest version in http://www-01.ibm.com/support/docview.wss?uid=swg2C7000003#71

DevExtreme datasource can't load Data Service data

I tried to accomplish the tutorial here, and when I used their data service, it worked just fine.
I modified the source to my data service (WCF Data Service v5.6, OData V2), and the list just shows the Loading sign and nothing happens.
The code should load any data type, it just has to be mapped accordingly. My service is availabe through the browser, I checked.
Here is the code:
DevExTestApp.home = function (params) {
var viewModel = {
dataSource: DevExpress.data.createDataSource({
load: function (loadOptions) {
if (loadOptions.refresh) {
try {
var deferred = new $.Deferred();
$.get("http://192.168.1.101/dataservice/dataservice.svc/People")
.done(function (result) {
var mapped = $.map(result, function (data) {
return {
name: data.Name
}
});
deferred.resolve(mapped);
});
}
catch (err) {
alert(err.message);
}
return deferred;
}
}
})
};
return viewModel;
}
What else should I set?
The try-catch block would not help is this case, because data loading is async. Instead, subscribe to the fail callback:
$.get(url)
.done(doneFunc)
.fail(failFunc);
Another common problem with accessing a web service from JavaScript is Same-Origin Policy. Your OData service have to support either CORS or JSONP. Refer to this discussion.

peerConnection.addIceCandidate giving error: invalid string

I am trying to implement a Voice-only WebRTC app. I am running it on Chrome Version 29.0.1547.0 dev. My app uses Socket.IO for the signaling mechanism.
peerConnection.addIceCandidate() is giving me this error: Uncaught SyntaxError: An invalid or illegal string was specified.
and separately, peerConnection.setRemoteDescription(); is giving me this error: Uncaught TypeMismatchError: The type of an object was incompatible with the expected type of the parameter associated to the object.
Here's my code:
SERVER (in CoffeeScript)
app = require("express")()
server = require("http").createServer(app).listen(3000)
io = require("socket.io").listen(server)
app.get "/", (req, res) -> res.sendfile("index.html")
app.get "/client.js", (req, res) -> res.sendfile("client.js")
io.sockets.on "connection", (socket) ->
socket.on "message", (data) ->
socket.broadcast.emit "message", data
CLIENT (in JavaScript)
var socket = io.connect("http://localhost:3000");
var pc = new webkitRTCPeerConnection({
"iceServers": [{"url": "stun:stun.l.google.com:19302"}]
});
navigator.getUserMedia = navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia;
navigator.getUserMedia({audio: true}, function (stream) {
pc.addStream(stream);
}, function (error) { console.log(error); });
pc.onicecandidate = function (event) {
if (!event || !event.candidate) return;
socket.emit("message", {
type: "iceCandidate",
"candidate": event.candidate
});
};
pc.onaddstream = function(event) {
var audioElem = document.createElement("audio");
audioElem.src = webkitURL.createObjectURL(event.stream);
audioElem.autoplay = true;
document.appendChild(audioElem);
console.log("Got Remote Stream");
};
socket.on("message", function(data) {
if (data.type === "iceCandidate") {
console.log(data.candidate);
candidate = new RTCIceCandidate(data.candidate);
console.log(candidate);
pc.addIceCandidate(candidate);
} else if (data.type === "offer") {
pc.setRemoteDescription(data.description);
pc.createAnswer(function(description) {
pc.setLocalDescription(description);
socket.emit("message", {type: "answer", description: description});
});
} else if (data.type === "answer") {
pc.setRemoteDescription(data.description);
}
});
function offer() {
pc.createOffer( function (description) {
pc.setLocalDescription(description);
socket.emit("message", {type: "offer", "description": description});
});
};
The HTML just contains a button that calls offer().
I can confirm the ICECandidates and SessionDescriptions are transferring successfully from one client to the other.
What am I doing wrong? And how should I fix these and any other errors so that I can transfer audio from one client to the other?
PS: If you know about a good source documenting the WebRTC API (except the W3C documentation), please tell me about it!
Thanks!
For that error the point is, ICE Candidates must be added only after successfully setting remote description.
Note that just after creating Offer (by Offerer), ice candidates are produced immediately. So, if somehow the answerer receives those candidates, before setting remote description (which in theory would arrive before candidates), you get error.
The same is true for offerer. It must set remote description before adding any ice candidate.
I see that in your javascript code you are not guaranteeing that remote description is set before adding ice candidates.
First of all you can check just before pc.addIceCandidate(candidate); if pc's remoteDescription is set. If you see that it is null (or undefined), you can locally store received ice candidates to add them after setting remoteDescription (or wait in offerer to send them in proper time.)