Atmosphere On message Throwing message multiple times on single push - atmosphere

Hi i am learning Atmosphere framework and new to it, please help me out to fix issue that when i am pushing message through
socket.push(atmosphere.util.stringifyJSON({author:"user1", message: "hello"}));
but on server side i could see ***{"author":"user1","message":"hello"}, 4 times for single push.
****clientside***
mode.controller('pingController',['$scope','atmosphereService','$cookies',function($scope,atmosphereService,$cookies){
$scope.model = {
transport: 'websocket',
messages: []
};
var socket;
user=angular.fromJson($cookies.get('user_details_object'))['user_name'];
pingUrl='/chat/'+user;
request = {
url:pingUrl ,
contentType: 'application/json',
logLevel: 'debug',
transport: 'websocket',
trackMessageLength: true,
reconnectInterval: 5000,
enableXDR: true,
timeout: 60000
};
request.onOpen = function(response){
$scope.model.transport = response.transport;
$scope.model.connected = true;
$scope.model.content = 'Atmosphere connected using ' + response.transport;
};
/*request.onClientTimeout = function(response){
$scope.model.content = 'Client closed the connection after a timeout. Reconnecting in ' + request.reconnectInterval;
$scope.model.connected = false;
socket.push(atmosphere.util.stringifyJSON({ author: "author", message: 'is inactive and closed the connection. Will reconnect in ' + request.reconnectInterval }));
setTimeout(function(){
socket = atmosphereService.subscribe(request);
}, request.reconnectInterval);
};*/
request.onReopen = function(response){
$scope.model.connected = true;
$scope.model.content = 'Atmosphere re-connected using ' + response.transport;
};
//For demonstration of how you can customize the fallbackTransport using the onTransportFailure function
request.onTransportFailure = function(errorMsg, request){
atmosphere.util.info(errorMsg);
request.fallbackTransport = 'websocket';
$scope.model.header = 'Atmosphere Chat. Default transport is WebSocket, fallback is ' + request.fallbackTransport;
};
request.onMessage = function(response){
var responseText = response.responseBody;
console.log("###########",responseText);
try{
//var message = atmosphere.util.parseJSON(responseText);
var message = atmosphere.util.parseJSON(responseText);
console.log("#$$$$$##",message);
var date = typeof(message.time) === 'string' ? parseInt(message.time) : message.time;
$scope.model.messages.push({author: message.ping});
}catch(e){
console.error("Error parsing JSON: ", responseText);
throw e;
}
};
/*request.onClose = function(response){
$scope.model.connected = false;
$scope.model.content = 'Server closed the connection after a timeout';
socket.push(atmosphere.util.stringifyJSON({ author: $scope.model.name, message: 'disconnecting' }));
};*/
request.onError = function(response){
$scope.model.content = "Sorry, but there's some problem with your socket or the server is down";
$scope.model.logged = false;
};
request.onReconnect = function(request, response){
$scope.model.content = 'Connection lost. Trying to reconnect ' + request.reconnectInterval;
$scope.model.connected = false;
};
socket = atmosphereService.subscribe(request);
$scope.ping=function(name){
console.log("=="+name);
request = {
url:'/chat/'+name ,
contentType: 'application/json',
logLevel: 'debug',
transport: 'websocket',
trackMessageLength: true,
reconnectInterval: 5000,
enableXDR: true,
timeout: 60000
};
socket.push(atmosphere.util.stringifyJSON({author:"user1", message: "hello"}));
}
}]);
****serverside****
package resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Path;
import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.client.TrackMessageSizeInterceptor;
import org.atmosphere.config.service.AtmosphereHandlerService;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.AtmosphereSession;
import org.atmosphere.handler.OnMessage;
import org.atmosphere.interceptor.AtmosphereResourceLifecycleInterceptor;
import org.atmosphere.interceptor.BroadcastOnPostAtmosphereInterceptor;
import org.atmosphere.interceptor.HeartbeatInterceptor;
#Path("/")
#AtmosphereHandlerService(path = "/chat/{user}",
broadcasterCache = UUIDBroadcasterCache.class,
interceptors = {AtmosphereResourceLifecycleInterceptor.class,
BroadcastOnPostAtmosphereInterceptor.class,
TrackMessageSizeInterceptor.class,
HeartbeatInterceptor.class
})
public class NotificationResource extends OnMessage<String>{
List<AtmosphereResource> resourceList= new ArrayList<AtmosphereResource>();
#Override
public void onMessage(AtmosphereResponse response, String message)
throws IOException {
System.out.println("***"+message);
}
}
output:
***{"author":"user1","message":"hello"}
***{"author":"user1","message":"hello"}
***{"author":"user1","message":"hello"}
***{"author":"user1","message":"hello"}
please help me out to fix this, i need one message, single click of push

Related

Syntax error : unexpected token: identifier

I wish to display a mail icon with a counter
With my gnome-shell extension I get an error:
I don't know what the error means.
Keep in mind I do not have much knowledge about gnome..
Syntax error : unexpected token : identifier
const INDICATOR_ICON = 'mail-unread-symbolic';
const PanelMenu = imports.ui.panelMenu;
const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
class Extension extends PanelMenu.Button {
_init() {
super._init(0.0, null, false);
this._icon = new St.Icon({
icon_name: INDICATOR_ICON,
style_class: 'system-status-icon'});
this._iconBin = new St.Bin({ child: this._icon, x_fill: false, y_fill: false });
this._counterLabel = new St.Label({ text: "0",
x_align: Clutter.ActorAlign.CENTER,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
y_expand: true });
this._counterBin = new St.Bin({ style_class: 'mailnag-counter',
child: this._counterLabel,
layout_manager: new Clutter.BinLayout() });
this.add_actor(this._iconBin);
this.add_actor(this._counterBin);
}
}
function enable() {
return New Extension();
}
function disable() {
}

Upload image to Firebase from NativeScript

I'm trying to take a photo with the Camera module of NativeScript, then upload it to Firebase, but it doesn't seem to work. imageTaken and fileLocation come up as false and undefined. Is there something wrong with my code? (Written in TypeScript)
import fs = require('file-system')
import frame = require('ui/frame')
import utils = require('utils/utils')
import observableModule = require('data/observable')
import imageSource = require("image-source")
import camera = require('camera')
import image = require('ui/image')
import {
ImageFormat
} from 'ui/enums'
import view = require("ui/core/view")
import firebase = require('nativescript-plugin-firebase')
var dialog = require('nativescript-dialog')
var pd = new observableModule.Observable()
var imageContainer
var imageTaken = false
var fileLocation
exports.loaded = args => {
var page = args.object
imageContainer = view.getViewById(page, "img")
pd.set('imageTaken', imageTaken)
page.bindingContext = pd
}
exports.takePhoto = args => {
const options = {
width: 300,
height: 300,
keepAspectRatio: true
}
camera.takePicture().then((picture) => {
console.log('Take Picture')
var image = new image.Image()
image.imageSource = picture
imageContainer.imageSource = picture
let savePath = fs.knownFolders.documents().path;
let fileName = 'img_' + new Date().getTime() + '_' + this.currentUserId.getValue() + '.' + ImageFormat.jpeg
let filePath = fs.path.join(savePath, fileName)
console.log(filePath)
picture.saveToFile(filePath, ImageFormat.jpeg)
fileLocation = filePath
imageTaken = true
})
}
exports.sendPhoto = args => {
console.log(imageTaken)
console.log(fileLocation)
imageTaken ? upload(Math.random() + '-' + Date.now()) : dialog.show({
title: "Error",
message: "Please take a photo first.",
okButtonText: "OK"
})
}
const upload = (remoteFileName) => {
firebase.uploadFile({
remoteFullPath: 'uploads/images/' + remoteFileName,
localFile: fs.File.fromPath(fileLocation),
localFullPath: fileLocation,
onProgress: function (status) {
console.log("Uploaded fraction: " + status.fractionCompleted)
console.log("Percentage complete: " + status.percentageCompleted)
}
}).then(
uploadedFile => {
console.log("File uploaded: " + JSON.stringify(uploadedFile))
},
error => {
console.log("File upload error: " + error)
}
)
}
The old camera module is obsolete. Use nativescript-camera instead. Note that for Android API23+ you will need to explicitly request permissions runtime. With nativescript-camera it is done with
import * as camera from "nativescript-camera";
camera.requestPermissions();
More about nativescript-camera plugin here

Grunt jshint reporter to send out emails

I have added grunt jshint task to my grunt. I created custom reporter to send out jsHint output as email. My custom reporter function is invoked. But no emails are coming through. There are no errors in the code.
Grunt version: "grunt": "^0.4.5",
"nodemailer": "^1.11.0",
"nodemailer-sendmail-transport": "^1.0.0"
Here is the sample code:
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var async = require('async');
module.exports = {
reporter: function (errors) {
var len = errors.length,
str = '';
var items = [1];
errors.forEach(function (r) {
var file = r.file,
err = r.error;
str += file + ": line " + err.line + ", col " +
err.character + ", " + err.reason + "\n";
});
if (str) {
str += "\n" + len + " error" + ((len === 1) ? "" : "s") + "\n";
}
var transporter = nodemailer.createTransport( smtpTransport( {
service: "gmail",
secureConnection: false, // use SSL
port: 587, // port for secure SMTP
auth: {
user: "<my gmail username>",
pass: "<gmail account password>"
},
tls:{
ciphers:'SSLv3'
},
logger: true, // log to console
debug: true // include SMTP traffic in the logs
}));
// setup e-mail data with unicode symbols
var mailOptions = {
from: '<sender address>',
to: '<recipient address>',
subject: 'Hello', // Subject line
text: "why are you not working"
/* text: str */// plaintext body
/*html: '<b>Hello world</b>' // html body*/
};
async.eachSeries(items, function (item, next) {
transporter.sendMail(mailOptions, function(error, response){
// THIS CALLBACK IS NOT CALLED AT ALL
if(error){
console.log(error);
}else{
console.log("Message sent");
}
next(null);
});
}, function(err){
// All tasks are done now
console.log('All tasks are done now');
});
}
};
with async or without async doesn't matter. No emails are coming. I tried bye turning on the "Receive emails from unsecured apps" by following another stackoverflow post. That also did not help.
I would like to know is this correct approach or not? Any help/input is appreicated.

Dealing with EventEmitter events in Meteor?

I am trying to use an Asterisk Manager NPM module in Meteor, but am having difficulties with processing emitted events.
This NPM module establishes a permanent connection to Asterisk Manager and emits whatever Events it receives from Asterisk. I've managed to patch the code so that it runs in Meteor. It connects to Asterisk, emits events and I can log them to console, but once I try to do something with the data, like insert it into a collection, I receive the following error:
Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
How do I overcome that? Thank you.
server side code:
var ami = new AsteriskManager( { username: 'meteor', password: '123456' } );
ami.on('ami_data', function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
});
ami.connect(function(){});//creates a socket connection and sends the login action
the patched npm module code:
var util = Npm.require('util');
var events = Npm.require('events').EventEmitter;
var net = Npm.require('net');
var AsteriskConstructor = function AsteriskManager(params){
params = params || {};
this.net = net;
this.CRLF = "\r\n";
this.END = "\r\n\r\n";
this.buffer = "";
this.port = params.port || 5038;
this.host = params.host || 'localhost';
this.username = params.username || 'username';
this.password = params.password || 'password';
this.enable_debug = params.debug || false;
this.reconnect = params.reconnect || false;
this.reconnect_after = params.reconnect_after || 3000;
this.events = (params.events != undefined ? params.events : true);
this.identifier = params.identifier || false;
this.ami_encoding = params.ami_encoding || 'ascii';
};
AsteriskManager = AsteriskConstructor;
util.inherits(AsteriskManager, events);
AsteriskManager.prototype.connect = function(connect_cb, data_cb){
var self = this;
self.debug('running ami connect');
self.socket = null;
self.socket = this.net.createConnection(this.port, this.host);//reopen it
self.socket.setEncoding(this.ami_encoding);
self.socket.setKeepAlive(true, 500);
self.socket.on('connect', function(){
self.debug('connected to Asterisk AMI');
//login to the manager interface
self.send({Action: 'login', Username : self.username, Secret : self.password, Events: (self.events ? 'on' : 'off')});
if(connect_cb && typeof connect_cb == 'function'){
connect_cb();
}
}).on('data', function(data){
if(data_cb && typeof data_cb == 'function'){
data_cb(data);
}
var all_events = self.processData(data);
for(var i in all_events){
var result = all_events[i];
if(result.response && result.message && /Authentication/gi.exec(result.message) == 'Authentication'){
self.emit('ami_login', ((result.response == 'Success') ? true : false) ,result);
}
self.emit('ami_data', result);
}
}).on('drain', function(){
self.debug('Asterisk Socket connection drained');
self.emit('ami_socket_drain');
}).on('error', function(error){
if(error){
self.debug('Asterisk Socket connection error, error was: ' + error);//prob lost connection to ami due to asterisk restarting so restart the connection
}
self.emit('ami_socket_error', error);
}).on('timeout',function(){
self.debug('Asterisk Socket connection has timed out');
self.emit('ami_socket_timeout');
}).on('end', function() {
self.debug('Asterisk Socket connection ran end event');
self.emit('ami_socket_end');
}).on('close', function(had_error){
self.debug('Asterisk Socket connection closed, error status - ' + had_error);
self.emit('ami_socket_close', had_error);
if(self.reconnect){
self.debug('Reconnecting to AMI in ' + self.reconnect_after);
setTimeout(function() {
self.connect(connect_cb, data_cb);
}, self.reconnect_after);
}
});
}
AsteriskManager.prototype.disconnect = function(){
this.reconnect = false;//just in case we wanted it to reconnect before, we've asked for it to be closed this time so make sure it doesnt reconnect
this.socket.end(this.generateSocketData({Action: 'Logoff'}));
}
AsteriskManager.prototype.destroy = function(){
this.socket.destroy();
}
AsteriskManager.prototype.processData = function(data, cb){
/*
Thanks to mscdex for this bit of code that takes many lots of data and sorts them out into one if needed!
https://github.com/mscdex/node-asterisk/blob/master/asterisk.js
*/
data = data.toString();
if (data.substr(0, 21) == "Asterisk Call Manager"){
data = data.substr(data.indexOf(this.CRLF)+2); // skip the server greeting when first connecting
}
this.buffer += data;
var iDelim, info, headers, kv, type, all_events = [];
while ((iDelim = this.buffer.indexOf(this.END)) > -1) {
info = this.buffer.substring(0, iDelim+2).split(this.CRLF);
this.buffer = this.buffer.substr(iDelim + 4);
result = {}; type = ""; kv = [];
for (var i=0,len=info.length; i<len; i++) {
if (info[i].indexOf(": ") == -1){
continue;
}
kv = info[i].split(": ", 2);
kv[0] = kv[0].toLowerCase().replace("-", "");
if (i==0){
type = kv[0];
}
result[kv[0]] = kv[1];
}
if(this.identifier){
result.identifier = this.identifier;
}
all_events.push(result);
}
return all_events;
}
AsteriskManager.prototype.debug = function(data){
if(this.enable_debug){
console.log(data);
}
}
AsteriskManager.prototype.generateRandom = function(){
return Math.floor(Math.random()*100000000000000000);
}
AsteriskManager.prototype.generateSocketData = function(obj){
var str = '';
for(var i in obj){
str += (i + ': ' + obj[i] + this.CRLF);
}
return str + this.CRLF;
}
AsteriskManager.prototype.send = function(obj, cb) {
//check state of connection here, if not up then bail out
if(!obj.ActionID){
obj.ActionID = this.generateRandom();
}
//maybe i should be checking if this socket is writeable
if(this.socket != null && this.socket.writable){
this.debug(obj);
this.socket.write(this.generateSocketData(obj), this.ami_encoding, cb);
}else{
this.debug('cannot write to Asterisk Socket');
this.emit('ami_socket_unwritable');
}
}
As the error message says "Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment"
ami.on('ami_data', Meteor.bindEnvironment( function(data){
console.log(data); // <- this works fine
// the following causes the error
EventsLog.insert({ timestamp: (new Date()).getTime(),
data: data});
}, function( error) { console.log( error);})
);
There are a lot of other examples around.
If the server code above is not in a Fiber you might get "Meteor code must always run within a Fiber" error.

Atmosphere #Disconnect does not get called when we close browser window

Using the chat example, when I close the browser window, I do not ever see the #Disconnect method called.
Here is my service:-
package org.atmosphere.samples.chat;
import java.io.IOException;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedService(path = "{room: [a-zA-Z][a-zA-Z_0-9]*}")
public class Chat
{
private static final Logger LOGGER = LoggerFactory.getLogger(Chat.class);
#Ready
public void onReady(final AtmosphereResource inAtmosphereResource)
{
LOGGER.info("Browser {} connected.", inAtmosphereResource.uuid());
}
#Disconnect
public void onDisconnect(AtmosphereResourceEvent event)
{
if (event.isCancelled())
{
LOGGER.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
}
else if (event.isClosedByClient())
{
LOGGER.info("Browser {} closed the connection", event.getResource().uuid());
}
else
{
LOGGER.info("close event was called, but I know not why");
}
}
#org.atmosphere.config.service.Message(encoders = { JacksonEncoder.class }, decoders = { JacksonDecoder.class })
public Message onMessage(Message message) throws IOException
{
LOGGER.info("{} just send {}", message.getAuthor(), message.getMessage());
return message;
}
}
Here is my JS:-
$(function () {
"use strict";
var header = $('#header');
var content = $('#content');
var input = $('#input');
var status = $('#status');
console.log(document.location.hash);
var bookingNumber = document.location.hash.substring(1, document.location.hash.length);
console.log(bookingNumber);
var myName = false;
var author = null;
var logged = false;
var socket = $.atmosphere;
var subSocket;
var transport = 'websocket';
// We are now ready to cut the request
var request = { url: document.location.toString().replace(/#.*/, "") + 'chat/' + bookingNumber,
contentType : "application/json",
trackMessageLength : true,
shared : true,
logLevel : "debug",
transport : transport ,
fallbackTransport: 'long-polling'};
request.onOpen = function(response) {
content.html($('>p<', { text: 'Atmosphere connected using ' + response.transport }));
input.removeAttr('disabled').focus();
status.text('Choose name:');
transport = response.transport;
if (response.transport == "local") {
subSocket.pushLocal("Name?");
}
};
request.onTransportFailure = function(errorMsg, request) {
jQuery.atmosphere.info(errorMsg);
if (window.EventSource) {
request.fallbackTransport = "sse";
transport = "see";
}
header.html($('<h3>', { text: 'Atmosphere Chat. Default transport is WebSocket, fallback is ' + request.fallbackTransport }));
};
request.onMessage = function (response) {
// We need to be logged first.
if (!myName) return;
var message = response.responseBody;
try {
var json = jQuery.parseJSON(message);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
if (!logged) {
logged = true;
status.text(myName + ': ').css('color', 'blue');
input.removeAttr('disabled').focus();
subSocket.pushLocal(myName);
} else {
input.removeAttr('disabled');
var me = json.author == author;
var date = typeof(json.time) == 'string' ? parseInt(json.time) : json.time;
addMessage(json.author, json.message, me ? 'blue' : 'black', new Date(date));
}
};
request.onClose = function(response) {
logged = false;
}
subSocket = socket.subscribe(request);
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (author == null) {
author = msg;
}
subSocket.push(jQuery.stringifyJSON({ author: author, message: msg }));
$(this).val('');
input.attr('disabled', 'disabled');
if (myName === false) {
myName = msg;
}
}
});
function addMessage(author, message, color, datetime) {
content.append('<p><span style="color:' + color + '">' + author + '</span> # ' +
+ (datetime.getHours() < 10 ? '0' + datetime.getHours() : datetime.getHours()) + ':'
+ (datetime.getMinutes() < 10 ? '0' + datetime.getMinutes() : datetime.getMinutes())
+ ': ' + message + '</p>');
}
});
I am running on glassfish 3, with web sockets and comet enabled.
UPDATE I forgot to mention that I am using v 2.1.0RC1
tested with GF 3.1.2.2:
Blockquote
[#|2013-12-02T10:43:24.743-0500|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=25;_ThreadName=http-thread-pool-8080(4);|10:43:24.743 [http-thread-pool-8080(4)] INFO org.atmosphere.samples.chat.Chat - Browser 0f7f5596-bd25-4dda-a488-1357da8487f5 closed the connection
Let's havce the discussion on the Atmosphere ML in case you are still experiencing issue. I've tested with the sample BTW.
-- Jeanfrancois

Resources