Subscriptions via websockets in Orion - fiware-orion

Is it possible to create a websockets subscription from a browser? We are using the branch feature/1181_websockets branch, git version 5ca6770aa401b52a31293fdcef4a9743fb1de2c4.
We made a PoC trying to subscribe a browser via websockets. We tried connecting some JS code running in the browser to the subscriptions url. The connection was established, but orion crashed when sending data from the client through the socket. Is this use case supported? Do you have a working example for it? The JS code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="send" type="button" name="button">send</button>
<script type="text/javascript">
var payload = `{"description": "One subscription to rule them all",
"subject": {
"entities": [{
"idPattern": ".*",
"type": "Room"
}],
"condition": {
"attrs": ["temperature"],
"expression": {
"q": "temperature>40"
}
}
},
"expires": "2016-04-05T14:00:00.00Z",
"throttling": 5
}`;
var ws = new WebSocket('ws://orion-url:9010/v2/subscriptions', 'ngsiv2-json');
var button = document.getElementById('send');
button.addEventListener('click', function(event) {
ws.send(payload)
});
</script>
</body>
</html>
As an alternative, we tried to create a subscription using the REST API, asking Orion to notify us via websockets. We POSTed the following JSON:
{
"description": "One subscription to rule them all",
"subject": {
"entities": [
{
"idPattern": ".*",
"type": "Room"
}
],
"condition": {
"attributes": [
"temperature"
],
"expression": {
"q": "temperature>40"
}
}
},
"notification": {
"callback": "ws://my-websocket-listener:8081"
},
"expires": "2016-04-05T14:00:00.00Z",
"throttling": 5
}
The subscription process fails and Orion returns a 422 status code with the message:
{
"error": "BadRequest",
"description": "Invalid URL"
}
Did we make any mistake in the subscription request? Is this use case supported?
Thanks!

Currently you can subscribe with your browser and receive notifications, the restriction are the following:
From WS you can create a WS or REST subscription.
From REST you cannot create a WS subscription.
Only in the REST subscriptions you can specify the callback, in WS always must be "ws://". If you create a WS subscription the creator will be the receiver.
WS subscription are deleted if a connection is closed.
Here I let a little code as example, you only need change the URL by your Orion's URL
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
window.WebSocket = window.WebSocket || window.MozWebSocket;
// Here change with your URL
var websocket = new WebSocket('ws://127.0.0.1:9010', 'ngsiv2-json');
websocket.onopen = function () {
$('h1').css('color', 'green');
};
websocket.onerror = function () {
$('h1').css('color', 'red');
};
websocket.onmessage = function (message) {
console.log(message.data);
console.log(message);
$('div').append(message.data + '<br/>');
};
$('#send').click(function(e) {
e.preventDefault();
if ($('#txt').val().length > 0)
{
websocket.send($('#txt').val());
$('#txt').val('');
}
});
$('#new').click(function(e) {
e.preventDefault();
var msg = "{\"verb\":\"POST\",\"url\":\"/v2/entities\", \
\"params\":{\"options\":\"keyValues\"}, \
\"payload\":{\"type\":\"1\",\"id\":\"1\",\"temp\":1}}";
$('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
});
$('#upd').click(function(e) {
e.preventDefault();
var msg = "{\"verb\":\"POST\",\"url\":\"/v2/entities/1\", \
\"params\":{\"options\":\"keyValues\"},\"payload\":{\"temp\": 1}}";
$('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
});
$('#get').click(function(e) {
e.preventDefault();
var msg = "{\"verb\":\"GET\",\"url\":\"/v2/entities/1\"}";
$('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
});
$('#del').click(function(e) {
e.preventDefault();
var msg = "{\"verb\":\"DELETE\",\"url\":\"/v2/entities/1\"}";
$('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
});
$('#sub').click(function(e) {
e.preventDefault();
var msg = "{\"verb\":\"POST\",\"url\":\"/v2/subscriptions\", \
\"payload\":{\"description\":\"My subscription\", \
\"subject\":{\"entities\":[{\"id\":\"1\",\"type\":\"1\"}], \
\"condition\":{\"attributes\":[\"temp\"],\"expression\":{\"q\":\"temp>40\"}}}, \
\"notification\":{\"callback\":\"ws://\",\"attributes\":[\"temp\"], \
\"throttling\":5},\"expires\":\"2017-04-05T14:00:00.00Z\"}}";
$('#txt').val(JSON.stringify(JSON.parse(msg), null, 2));
});
});
</script>
</head>
<body>
<h1>WebSockets test</h1>
<form>
<table border="0">
<tr>
<td colspan="2">
<textarea rows="35" cols="70" id="txt"></textarea>
</td>
</tr>
<tr>
<td>
<button id="new">New</button>
<button id="upd">Update</button>
<button id="get">Show</button>
<button id="del">Delete</button>
<button id="sub">Subcription</button>
</td>
<td align="right">
<button id="send">Send</button>
</td>
</tr>
</table>
</form>
<br/>
<p>Server:</p>
<div></div>
</body>
</html>
I'm not a JS expert... but this work to me as a test when I work in the WS for Orion
Cheers

Related

Unfortunately we were unable to process the request. Please try again

I'm trying to integrate Paypal Plus to my store, using API Reference guide (see the screenshot). Everything is done but the paypal returns 500 error when I try to complete the checkout: UNKNOWN_INTERNAL_ERROR.
Searching through Google wasn't successful.
<script src="https://www.paypalobjects.com/webstatic/ppplusdcc/ppplusdcc.min.js" type="text/javascript"></script>
<div id="ppplusDiv" style="width: 300px; height: 502px;"></div>
<script type="application/javascript">
var ppp = PAYPAL.apps.PPP({
"approvalUrl": "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-25D26051FW287782J",
"placeholder": "ppplusDiv",
"mode": "sandbox",
"payerFirstName": "John",
"payerLastName": "Doe",
"payerPhone": "33927349232",
"payerEmail": "admin#example.com",
"payerTaxId": "831.899.557-00",
"payerTaxIdType": "BR_CPF",
"disableContinue": "continueButton",
"enableContinue": "continueButton",
"language": "en_US",
"country": "BR",
});
<button id="continueButton" class="ty-btn__big ty-btn__primary cm-ajax cm-checkout-place-order ty-btn" type="submit" name="dispatch[checkout.place_order]" onclick="if (!document.getElementById('product_agreements') || document.getElementById('product_agreements').checked) { ppp.doContinue(); return false;}">Разместить заказ</button>

Outlook REST API: V1IDToken is not applicable for the current protocol

I'm trying to retrieve my email messages from an Outlook account through Javascript.
I use ADAL to authenticate myself and that seems to work. However if I try to use the returned token in a GET request to the outlook REST API I get an unauthorised error back with following additional info in the header:
x-ms-diagnostics:2000001;reason="This token profile 'V1IdToken' is not applicable for the current protocol.";error_category="invalid_token"
My request looks like:
function test2(token) {
try
{
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://outlook.office.com/api/v1.0/me/messages');
// The APIs require an OAuth access token in the Authorization header, formatted like this: 'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + token);
// Process the response from the API.
xhr.onload = function () {
// ...
}
// Make request.
xhr.send();
I both tried v1.0 and v2.0 REST api.
Based on the error message you were request the Outlook online REST using the id_token. The id_token is only used for the client to authenticate users. To request the Outlook online REST, we need to use the access token.
And if you were developing with angularJS, there is no need to append the token manually. Here is a code sample for your reference:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal-angular.min.js"></script>
<script src="//unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<div ng-app="myApp">
<div> Hello {{ userInfo.userName }}</div>
<div ng-controller="homeCtrl">
<ul class="nav navbar-nav navbar-right">
<li><a ng-click="getMessages()">Get Messages</a></li>
<li><a class="btn btn-link" ng-show="userInfo.isAuthenticated" ng-click="logout()">Logout</a></li>
<li><a class="btn btn-link" ng-hide="userInfo.isAuthenticated" ng-click="login()">Login</a></li>
</ul>
<div>
<table class="table table-striped">
<tbody>
<tr data-ng-repeat="item in messages">
<td>
<p>{{item.Subject}}</p>
</td>
<td>
<p>{{item.Sender.EmailAddress.Address}}</p>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script>
var myApp = angular.module('myApp', ['AdalAngular'])
.config(['$httpProvider', 'adalAuthenticationServiceProvider', function ($httpProvider, adalProvider) {
var endpoints = {
"https://outlook.office.com": "https://outlook.office.com",
};
adalProvider.init(
{
instance: 'https://login.microsoftonline.com/',
tenant: '{yourTenant}.onmicrosoft.com',
clientId: '{yourAppId}',
extraQueryParameter: 'nux=1',
endpoints: endpoints,
},
$httpProvider
);
}])
myApp.controller('homeCtrl', ['$scope', '$http', 'adalAuthenticationService', '$location', 'toGetMessagesSvc', function ($scope, $http, adalService, $location, toGetMessagesSvc) {
$scope.login = function () {
adalService.login();
};
$scope.logout = function () {
adalService.logOut();
};
$scope.getMessages = function () {
toGetMessagesSvc.getMessages().success(function (results) {
$scope.messages = results.value;
$scope.loadingMessage = "";
});
}
}]);
myApp.factory('toGetMessagesSvc', ['$http', function ($http) {
var apiEndpoint = "https://outlook.office.com/";
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
return {
getMessages: function () {
return $http.get(apiEndpoint + 'api/v1.0/me/messages');
}
};
}]);
</script>

socket.io troubles - 404 (Not Found)

Despite following the exact instructions of this video: https://www.youtube.com/watch?v=pNKNYLv2BpQ and changing details where necessary (e.g. I am using localhost:8888 as oppose to 3000), I am always getting error messages, no matter what I try. It is becoming extremely frustrating as I can't, for the life of me, figure out where I am going wrong.
I am currently getting the error message GET http://localhost:8888/socket.io/1/?t=1462670368869 404 (Not Found)after a massive struggle of continuously getting an error where it couldn't locate the 'socket.io.js' file. Can anyone shed some light on this devastatingly cryptic topic?
HTML:
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat{
height:500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data){
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
JavaScript:
var express = require('express');
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.on('send message', function(data){
io.sockets.emit('new message', data);
});
});
JSON:
{
"name": "chat",
"version": "0.0.1",
"private": "true",
"dependencies": {
"express": "^4.10.2",
"socket.io": "^0.9.16"
}
}

Inline edit form in Angular.Js

I am trying to make a small app with items pulled from a json source and i want a form to edit each element. Each element has several attributes, name, id, description.
Here is the example but the edit form does nothing at the moment. I will later use the example to store the data in a database.
I am trying to find out the best solution to have this edit form directly on each element when pushing on edit for example. What is the best way to do it?
Thanks in advance!
script.js
var app = angular.module('myApp', []);
function Controller($scope) {
var items = [
{
"id": "1",
"name": "John",
"price": "55.33",
"description": "Lorem ipsums aute irure doln v anim id est laborum.",
"flag": "0"
},
{
"id": "2",
"name": "Mike",
"price": "68",
"description": "Loriannaj jh said ihsa djni cjipsums aute irure doln v anim id est laborum.",
"flag": "0"
},
{
"id": "15",
"name": "George",
"price": "78",
"description": "This is the description",
"flag": "1"
}
];
//Initialize the controller and the UI
$scope.items = angular.fromJson(items);
}
html
<html ng-app="myApp">
<head>
<title>Test Page</title>
<link type="text/css" rel="stylesheet" href="style.css">
<!-- Angular Staff -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<header>
</header>
<section>
<div class="columns2" ng-controller="Controller">
<div style="width: 500px; display: inline-block">
<h3>ITEMS</h3>
<div ng-repeat="item in items">
<div class="user_div" >
{{item.name}}
<a style="float: right" href="#" ng-click="showEdit = ! showEdit">Edit </a>
</div>
<div class="user_data" ng-show="showDetails" >{{item.description}}</div>
<div class="user_data" ng-show="showEdit" >
<h3>Edit Item</h3>
<input value="{{item.name}}" type="text" >
<input value="{{item.description}}" type="text" >
<button ng-click="editItem({{item.id}},{{itemName}},{{itemDescription}})">Edit</button>
</div>
</div>
<br>
<pre>Items: {{items|json}}</pre> </div>
</div>
</body>
</html>
I ran into the same requirement and came up with this solution:
<tr ng-repeat="transaction in data.transactions">
...
<td>
<input ng-model="transaction.numAvailable"
ng-style="!transaction.edit && {'background-color': '#eeeeee'}"
ng-blur="saveShelf(transaction)"
ng-click="editShelf(transaction)"
class="form-control"
ng-value="transaction.numAvailable"/>
</td>
</tr>
And in my controller.js:
$scope.editShelf = function(trans){
trans.edit = true;
};
$scope.saveShelf = function(trans){
trans.edit = false;
//call service to save value
};
Basically, you have an input that looks disabled with bg-color:#eee, onclick removes the bg-color, onblur resets the bg-color. To make this work I added an 'edit=false' to my list with lodash:
_.forEach($scope.data.transactions, function(trans){
trans.edit = false;
});
You can use x-editable for inline edit. As we can't see any example , you can use this module for inline-edit.
you can create a factory like this
app.factory('userFactory', function ($http) {
var factory = {};
factory.get = function () {
return $http.get('your_rest_url', {}).then(function (resp) {
console.log('Success', resp);
}, function (err) {
console.error('ERR', err);
});
};
});
inject it to your controller
var Ctrl = function ($scope, userFactory) {
$scope.items = userFactory.get();
};
then bind the data to your form elements
<input ng-model="items.property">

WebSockets can't establish connection to server

I'm running the simple Echo example of WebSockets but it doesn't seem to establish a connection. This is happening on Windows 7, Eclipse, and Tomcat.
The error messages in firefox are:
"NetworkError: 404 Not Found - http://my_ip_address:8080/websockets/echo"
and
Firefox can't establish a connection to the server at ws://my_ip_address:8080/websockets/echo.
What am I missing? Is there some configuration I need to set up?
The jars I have in the build path are javax.annotation_1.0.jar and websocket-api-0.2.jar
The code I'm running:
package org.javaee.glassfishwebsocket;
import org.glassfish.websocket.api.annotations.WebSocket;
import org.glassfish.websocket.api.annotations.WebSocketMessage;
#WebSocket(path="/echo")
public class EchoBean {
#WebSocketMessage
public String echo(String message) {
System.out.println("##################### Message received");
return message + " (from your server)";
}
}
This is index.jsp:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<meta charset="utf-8">
<title>WebSocket Echo Client</title>
<script language="javascript" type="text/javascript">
console.log("trying to connect");
var wsUri = "ws://my_ip_address:8080/websockets/echo";
console.log("wsUri = ");
console.log(wsUri);
var websocket = new WebSocket(wsUri);
console.log("websocket = " );
console.log(websocket);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
function init() {
console.log("init called");
output = document.getElementById("output");
}
function send_echo() {
console.log("sending_echo with " + textID.value);
websocket.send(textID.value);
writeToScreen("SENT: " + textID.value);
}
function onOpen(evt) {
console.log("onOpen");
writeToScreen("CONNECTED");
}
function onMessage(evt) {
console.log("onMessage");
writeToScreen("RECEIVED: " + evt.data);
}
function onError(evt) {
console.log("onError");
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2 style="text-align: center;">WebSocket Echo Client</h2>
<div style="text-align: center;"><img style=" width: 64px; height: 64px;" alt=""src="HTML5_Logo_512.png"></div>
<br></br>
<div style="text-align: center;">
<form action="">
<input onclick="send_echo()" value="Press me" type="button">
<input id="textID" name="message" value="Hello WebSocket!" type="text"><br>
</form>
</div>
<div id="output"></div>
</body>
</html>