socketio.emit doesn't work netty socketio - java

I'm working with socketio and netty with java and I'm new to both of them.
my client side code looks like this.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title >webSocket test</title>
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
< !-- New Bootstrap core CSS file-->
<!-- Optional Bootstrap theme file (generally not necessary to import) -->
<!- -jQuery file. Be sure to introduce before bootstrap.min.js -->
<!-- The latest Bootstrap core JavaScript file-->
<script type=" text/javascript">
$(function(){
/**
* The socket.emit("event name", "parameter data") method of the
front-end js is used when triggering the back-end custom message event, * front-end js The socket.on("event name", anonymous function (data sent by the server to the client)) for monitoring server-side events
**/
//io({path: 'ws://localhost:9099/', transports: ['websocket'] ,upgrade: false});
var socket = io.connect("ws://localhost:9099",{transports: ['websocket'] ,upgrade: false});
var firstconnect = true;
if(firstconnect) {
console.log("First connection initialization");
//Monitor server connection event
socket.on('connect',function(){
socket.emit('messageEvent', 'Hello server');
console.log("First connection success");
$("#tou").html("Connect to the server successfully!");
});
//Monitor server shutdown service event
socket.on('disconnect', function(){
$("#tou").html("Disconnected from the server!");
});
//Monitor server Send message event
socket.on('responseEvent', function(data) {
console.log('data');
$("#msg").html($("#msg").html() + "<br/>" + data);
} );
firstconnect = false;
} else {
console.log("why?");
socket.socket.reconnect();
}
$('#send').bind('click', function() {
send();
});
function send(){
if (socket != null) {
var message = document.getElementById('message').value;
var title = "message";
var obj = {message:message,title:title};
var str = JSON.stringify(obj);
socket.emit("messageEvent",str);
console.log("message event" , str);
} else {
alert('Send');
}
}
});
</script>
</head>
<body>
<div class="page-header" id="tou">
webSocket Demo
</div>
<div class="well" id="msg">
</div>
<div class="col-lg">
<div class="input-group">
<input type="text" class="form-control" placeholder="send Message..." id="message">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="send" >send</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row --><br><br>
</body>
</html>
The event handler is as shown below.
#Component
public class MessageEventHandler {
private static final Logger logger = LoggerFactory.getLogger(MessageEventHandler.class);
public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();
#Autowired
private RedissonClient redisson;
#Resource
private SocketIOServer socketIOServer;
#OnConnect
public void onConnect(SocketIOClient client){
Map<String,Object> clientMap = new HashMap<>(16);
client.sendEvent("responseEvent", client.getSessionId().toString()+": "+ "hello");
if(client!=null){
String room = client.getHandshakeData().getSingleUrlParam("room");
String nameSpace = client.getNamespace().getName();
logger.info("namespace {} ",nameSpace);
String sessionId = client.getSessionId().toString();
logger.info("namespace, room={}, sessionId={},namespace={}",room,sessionId,nameSpace);
if(StringUtils.isEmpty(room)){
//client.joinRoom(room);
clientMap.put("rooms",room);
}
clientMap.put("createTime", LocalDateTime.now().toString());
redisson.getBucket("room"+sessionId).trySet(clientMap);
}
return;
}
/**
* Triggered when the client closes the connection
*
* #param client
*/
#OnDisconnect
public void onDisconnect(SocketIOClient client) {
logger.info("client:" + client.getSessionId() + "disconnected");
}
/**
* Client events
*
* #param client  
* #param request
* #param msg  
*/
#OnEvent(value = "messageEvent")
public void onMessageEvent(SocketIOClient client, AckRequest request, String msg) {
System.out.println("haha");
logger.info("message :" + msg);
//Post the message back
JSONObject jsonObject = JSON.parseObject(msg);
String message = jsonObject.getString("message");
Collection<SocketIOClient> clients = socketIOServer.getBroadcastOperations().getClients();
for (SocketIOClient clientByRoom : clients) {
clientByRoom.sendEvent("responseEvent", client.getSessionId().toString()+": "+message);
}
}
}
The server starter code is shown below.
#Component
#Order(1)
public class SocketServerRunner implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(SocketServerRunner.class);
#Resource
private SocketIOServer socketIOServer;
#Resource
private PubSubStore pubSubStore;
#Autowired
private RedissonClient redisson;
#Override
public void run(String... args) throws Exception {
logger.info("socketIOServer ");
socketIOServer.start();
pubSubStore.subscribe(PubSubType.DISPATCH, data -> {
Collection<SocketIOClient> clients = null;
String room = data.getRoom();
String namespace = data.getNamespace();
Packet packet = data.getPacket();
String jsonData = packet.getData();
if(!StringUtils.isEmpty(namespace)){
SocketIONamespace socketIONamespace = socketIOServer.getNamespace(namespace);
if(StringUtils.isEmpty(room)){
clients = socketIONamespace.getRoomOperations(room).getClients();
}
}else{
clients = socketIOServer.getBroadcastOperations().getClients();
}
if(!CollectionUtils.isEmpty(clients)){
for (SocketIOClient client : clients) {
client.sendEvent("messageEvent",jsonData);
}
}
}, DispatchMessage.class);
// addNameSpace(socketIOServer);
}
I'm getting a connection registration on the OnConnect annoted method, but the method seems to run two times cause I get the log twice while the socket connects. I don't know why it happens.
But even worse is the emit method doesn't work that is written in client side javascript. There is no error. The log below the emit is executed. But the OnEvent annoted method in the java EventHandler doesn't seem to detect it.
Can someone help me understand this?

Apparently it seems the problem is with the libraries. There is some compatibility issue with newer versions of socketio client library with netty dependencies for java and it is causing the weird problems.
My dependency for netty socketio is shown below which obviously is the latest as of answering this question.
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.19</version>
</dependency>
And for the client library to work smoothly I had to downgrade the library from 3.X.X to 2.X.X .
In my case from
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
to
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>

Related

Is there a way to fetch Paypal's vaulted credit card information from Braintree?

In my project, I am using scheduler cron job to do monthly subscription with a trail period of 2 months. So, if there is any service that expires in current date, a particular amount will be payed to admin, thus enabling monthly subscription process. Being said that, I have stored the credit card reference ID from Paypal vault in my DB. Now, I want to use this reference ID for payment via Braintree. Is there any way to get the details from Paypal vault or use the card-reference ID to directly do the payment. Please help!
I tried the below code. But not sure how to fetch the credit card details from Paypal vault or the card-ref ID from DB and add it here.
public class BrainTreeImplementation {
private static Logger logger = Logger.getLogger(BrainTreeImplementation.class.getName());
// Below are the Braintree sandbox credentials
private static BraintreeGateway gateway = null;
private static String publicKey = "YOUR_PUBLIC_KEY";
private static String privateKey = "YOUR_PRIVATE_KEY";
private static String merchantId = "YOUR_MERCHANT_ID";
public static void main(String[] args) {
// Initialize Braintree Connection
gateway = connectBraintreeGateway();
braintreeProcessing();
}
public static void braintreeProcessing() {
System.out.println(" ----- BrainTree Implementation Starts --- ");
// Generate client Token
String clientToken = generateClientToken();
System.out.println(" Client Token : " + clientToken);
// Receive payment method nonce
String nonceFromTheClient = receivePaymentMethodNonce();
// Do payment transactions
BigDecimal amount = new BigDecimal("5.10");
doPaymentTransaction(nonceFromTheClient, amount);
}
// Connect to Braintree Gateway.
public static BraintreeGateway connectBraintreeGateway() {
BraintreeGateway braintreeGateway = new BraintreeGateway(Environment.SANDBOX, merchantId, publicKey,
privateKey);
return braintreeGateway;
}
// Make an endpoint which return client token.
public static String generateClientToken() {
// client token will be generated at server side and return to client
String clientToken = gateway.clientToken().generate();
return clientToken;
}
// Make an endpoint which receive payment method nonce from client and do payment.
public static String receivePaymentMethodNonce() {
String nonceFromTheClient = "fake-valid-mastercard-nonce";
return nonceFromTheClient;
}
// Make payment
public void String
doPaymentTransaction(String paymentMethodNonce, BigDecimal amount) {
TransactionRequest request = new TransactionRequest();
request.amount(amount);
request.paymentMethodNonce(paymentMethodNonce);
CustomerRequest customerRequest = request.customer();
customerRequest.email("cpatel#gmail.com");
customerRequest.firstName("Chirag");
customerRequest.lastName("Patel");
TransactionOptionsRequest options = request.options();
options.submitForSettlement(true);
// Done the transaction request
options.done();
// Create transaction ...
Result<Transaction> result = gateway.transaction().sale(request);
boolean isSuccess = result.isSuccess();
if (isSuccess) {
Transaction transaction = result.getTarget();
displayTransactionInfo(transaction);
} else {
ValidationErrors errors = result.getErrors();
validationError(errors);
}
}
private static void displayTransactionInfo(Transaction transaction) {
System.out.println(" ------ Transaction Info ------ ");
System.out.println(" Transaction Id : " + transaction.getId());
System.out.println(" Processor Response Text : " + transaction.getProcessorResponseText());
}
private static void validationError(ValidationErrors errors) {
List<ValidationError> error = errors.getAllDeepValidationErrors();
for (ValidationError er : error) {
System.out.println(" error code : " + er.getCode());
System.out.println(" error message : " + er.getMessage());
}
}
}
Use PayPal Vault or PayPal Checkout with Vault to get the nonce and send it to the server. PayPal Vault
The server use the nonce to create user. Create Customer
The server use the user id or payment token to create a transaction. Sale
sample code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="paypal-button" style="padding-top: 150px"></div>
</body>
<!-- Load the client component. -->
<script src="https://js.braintreegateway.com/web/3.88.2/js/client.min.js"></script>
<!-- Load the PayPal Checkout component. -->
<script src="https://js.braintreegateway.com/web/3.88.2/js/paypal-checkout.min.js"></script>
<script>
// Create a PayPal Checkout component
// Create a client.
braintree.client.create({
authorization: '' //tokenizationKey
}, function (clientErr, clientInstance) {
// Stop if there was a problem creating the client.
// This could happen if there is a network error or if the authorization
// is invalid.
if (clientErr) {
console.error('Error creating client:', clientErr);
return;
}
// Create a PayPal Checkout component.
braintree.paypalCheckout.create({
client: clientInstance
}, function (paypalCheckoutErr, paypalCheckoutInstance) {
paypalCheckoutInstance.loadPayPalSDK({
vault: true
}, function () {
paypal.Buttons({
fundingSource: paypal.FUNDING.PAYPAL,
createBillingAgreement: function () {
return paypalCheckoutInstance.createPayment({
flow: 'vault', // Required
// The following are optional params
billingAgreementDescription: 'Your agreement description',
enableShippingAddress: false,
shippingAddressEditable: false,
});
},
onApprove: function (data, actions) {
return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
// Submit `payload.nonce` to your server
console.log('nonce:',payload.nonce)
});
},
onCancel: function (data) {
console.log('PayPal payment canceled', JSON.stringify(data, 0, 2));
},
onError: function (err) {
console.error('PayPal error', err);
}
}).render('#paypal-button').then(function () {
// The PayPal button will be rendered in an html element with the ID
// `paypal-button`. This function will be called when the PayPal button
// is set up and ready to be used
});
});
});
});
</script>
</html>
public class BraintreePayDemo {
private static BraintreeGateway gateway = new BraintreeGateway(
Environment.SANDBOX,
"merchantId",
"publicKey",
"privateKey"
);
public static void customerCreate(){
CustomerRequest request = new CustomerRequest()
.id("test123")
.firstName("Hu")
.lastName("Z")
.paymentMethodNonce("3614a3fe-7503-0d1a-cfea-cad702094cc2");
Result<Customer> result = gateway.customer().create(request);
if(result.isSuccess()){
Customer customer = result.getTarget();
System.out.println(customer.getId());
System.out.println(customer.getPaymentMethods().get(0).getToken());
}else{
System.out.println(result.getMessage());
}
}
public static void saleByCustomerId(){
TransactionRequest request = new TransactionRequest()
.customerId("204871267")
.amount(new BigDecimal("1.00"))
.options()
.submitForSettlement(true)
.done();;
Result<Transaction> result = gateway.transaction().sale(request);
if (result.isSuccess()) {
Transaction transaction = result.getTarget();
System.out.println("Success ID: " + transaction.getId());
} else {
System.out.println("Message: " + result.getMessage());
}
}
public static void saleByPaymentMethodToken(){
TransactionRequest request = new TransactionRequest()
.paymentMethodToken("16mv5t7k")
.amount(new BigDecimal("10.00"))
.options()
.submitForSettlement(true)
.done();
Result<Transaction> result = gateway.transaction().sale(request);
if (result.isSuccess()) {
Transaction transaction = result.getTarget();
System.out.println("Success ID: " + transaction.getId());
} else {
System.out.println("Message: " + result.getMessage());
}
}
}

WebSocket Programming in Java: client server communication issue

I am trying to implement simple WebSocket program using Java Web Application.
However, not able to establish communication between client and server.
Can anybody help me?
Web Server: Tomcat
client code: jsp/javascrip
<body>
<div>
<input type="text" value="" id="message" /> <br /> <input
type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket;
var uri = 'ws://' + window.location.host + '/ZebraHosting/testwebsocket';
alert('ur url is ' + uri);
function connect() {
if ('WebSocket' in window) {
alert('I am in Websocket in window');
websocket = new WebSocket(uri);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket(uri);
alert('I am in MozWebsocket in window');
} else {
alert('WebSocket is not supported by this browser.');
return;
}
webSocket.onerror = function(event) {
alert('I am onerror');
onError(event);
};
webSocket.onopen = function(event) {
alert('I am onopen');
onOpen(event);
};
webSocket.onmessage = function(event) {
alert('I am onmessage');
onMessage(event);
};
webSocket.onclose = function(event) {
alert('I am onclose');
onClose(event);
};
}
function onMessage(event) {
document.getElementById('messages').innerHTML += '<br />'
+ event.data;
}
function onOpen(event) {
alert("function onOpen " );
document.getElementById('messages').innerHTML = 'Connection established';
}
function onError(event) {
alert("Error ocurred " );
}
function start() {
alert("function start " );
webSocket.send(document.getElementById('message').value);
return false;
}
function onClose(event) {
alert("function onClose" );
document.getElementById('messages').innerHTML = 'Connection closed';
}
connect();
</script>
Server Code:
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/testwebsocket")
public class WebSocketTest {
#OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
// Print the client message for testing purposes
System.out.println("Received: " + message);
// Send the first message to the client
session.getBasicRemote().sendText("replay from server for :" + message);
}
#OnOpen
public void onOpen() {
System.out.println("Client connected");
}
#OnClose
public void onClose() {
System.out.println("Connection closed");
}}
You have typos in your code: You create WebSocket objects and assign it to variable websocket but later use variable webSocket.
I think #ApplicationScoped annotation is missing for server side class.
See this tutorial http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

How to cancel response from server?

This is my code
function sendMessage()
{
if(textMessage.value!=="close")
{
if(searchid==="John" && login_id==="Mary" || searchid==="Mary" && login_id==="John")
{
webSocket.send(textMessage.value);
textMessage.value="";
}
}
else
{
webSocket.close();
}
}
I am making a chat application and getting response from server.Firstly the server was sending response to all the clients connected to it.But now I am converting it into one to one client based chat but the problem is if john is chatting with mary these values are placed in database and I can only one time get the data from database via scriplet when page is loaded so how to implement it when user want to chat with say dave.Then I can't get the values from database.
I totally understand that you would like to write this by your self, but there are lots of frameworks out there that will help you with the complex stuff and let you focus on the actuall business issues to solve.
We use XSockets.NET most of the time since that is perfect for our needs.
Setting ap a one to one chat (or other scenarios) is very easy with XSockets since it is all about publish/subscribe... And you can also filter where to send messages on the server with powerful extension methods
A simple sample chat:
To save some time and keep it stupid and simple I will use two dropdowns where you select your name and the city you are in. So not actually 1-1, but it is so that you would get the concept.
JAVASCRIPT/MARKUP
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.0.js"></script>
<script src="Scripts/moment.js"></script>
<script src="Scripts/XSockets.latest.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script>
//viewmodel for our messages
var vm = {
messages : ko.observableArray([])
}
//xsockets connection
var conn;
$(function() {
ko.applyBindings(vm);
//Connect to our controller (Chat)
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Chat');
conn.onopen = function() {
//open, set city and username (for demo only)
conn.setProperty("UserName", $('#username').val());
conn.setProperty("City", $('#cities').val());
//listen for chatmesages
conn.on('chatmessage', function (d) {
//Add message to viewmodel
vm.messages.push(d);
});
}
//When we hit enter, send a message
$('input').on('keydown', function (e) {
if (e.keyCode == 13) {
//Build message, we do not need to set From since the server know who I am
var message = { Text: $(this).val(), Time: moment().format('MMMM Do YYYY, h:mm:ss a') };
conn.publish('chatmessage', message);
}
});
//When City or Username is changed, tell the server
$('#cities').on('change', function(d) {
conn.setProperty("City", $(this).val());
});
$('#username').on('change', function (d) {
conn.setProperty("UserName", $(this).val());
});
});
</script>
</head>
<body>
<input type="text" placeholder="type here, enter to send"/>
<select id="username">
<option value="steve">steve</option>
<option value="ben">ben</option>
<option value="tomas">tomas</option>
</select>
<select id="cities">
<option value="london">london</option>
<option value="paris">paris</option>
<option value="tokyo">tokyo</option>
</select>
<div data-bind="foreach:messages">
<h5 data-bind="text:From + ' - ' + Time"></h5>
<div data-bind="text:Text"></div>
</div>
</body>
</html>
C#
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace SimpleChat
{
public class ChatMessage
{
public string From { get; set; }
public string Text { get; set; }
public string Time { get; set; }
}
public class Chat : XSocketController
{
/// <summary>
/// My name, we set this from javascript...
/// </summary>
public string UserName { get; set; }
/// <summary>
/// We only send to people being in the same city, we set it from javascript
/// </summary>
public string City { get; set; }
/// <summary>
/// A user sends a message
/// </summary>
/// <param name="chatMessage"></param>
public void ChatMessage(ChatMessage chatMessage)
{
chatMessage.From = this.UserName;
//Send only to the client(s) being in the same city, but you can ofcourse change ot to another user only etc
this.SendTo(p => p.City == this.City, chatMessage,"chatmessage");
}
}
}
Summary
The only thing I did except the code above was to create a new project and then
Install XSockets (to start a xsockets server)
Install XSockets.JsApi (for publish subscribe over websockets)
Install jQuery (becasue I am lazy)
Install Momoent.JS (for working wiht dates in javascript)
Install knockoutjs (for modelbinding)
Added a XSockets bootstrapper into App_Start (found under Add->NewItem->XSockets->XSockets.Web.Bootstrapper
I guess you simply need to add control functionality to your program:
Add two listboxes and two buttons for picking sender, receiver (search_id,log_id)
List <string> logins=new List<string>();
List <string> search=new List<string>();
........
logins.Add("John");
logins.Add("Mary");
.....
search.Add("Dave");
listBox1.Datasource=logins;
listBox2.Datasource=search;
private void button1_Click(object sender, EventArgs e) //pick login_id
{
login_id_to_Compare=listBox1.SelectedValue.ToString();
}
private void button2_Click(object sender, EventArgs e) //pick searcid
{
searchid_to_Compare=listBox2.SelectedValue.ToString();
}
function sendMessage()
{
if(textMessage.value!=="close")
{
if((searchid===searchid_to_Compare) && (login_id===login_id_to_Compare))
{
webSocket.send(textMessage.value);
textMessage.value="";
}
}
else
{
webSocket.close();
}
}
Your send message seems too simplistic. There is not enough info for the server to route the message to the correct destination.
You would need to send along with the message the destination so your server can route the message to the correct user.
In your db you then can save the "to" and "from" and display the correct messages for only the parties involved.
You would of course have to add the fields to your chat program to select the destination.
function sendMessage(from, to, msg)
{
webSocket.send("{'from':" + from + ", 'to':" + to + ", 'msg': " + msg + "}");
}

use deployJava.js to call java methods in javascript

I want to call java methods in javascript and Andrew Thompson suggested to use the deployJava.js library for this. I followed these instructions:
http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html
Here is explained how to use the java class in javascript, but I would like to call the java methods from within the javascript. (This is because I want to import a .owl file in java en export the information in json-format to my code written in javascript.)
Does anybody know how to do this with the deployJava library?
This is my code to import the java file:
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Sending Messages to Other Applets</h1>
<script>
function sendMsgToIncrementCounter() {
receiver.incrementCounter();
}
</script>
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'Sender.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'../Receiver.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
and this is are the sender and receiver java files:
import javax.swing.*;
public class Receiver extends JApplet {
private int ctr = 0;
private JLabel ctrLbl = null;
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ctrLbl = new JLabel("");
add(ctrLbl);
}
});
} catch (Exception e) {
System.err.println("Could not create applet's GUI");
}
}
public void incrementCounter() {
ctr++;
String text = " Current Value Of Counter: " + (new Integer(ctr)).toString();
ctrLbl.setText(text);
}
}
import javax.swing.*;
import java.awt.event.;
import netscape.javascript.;
public class Sender extends JApplet implements ActionListener {
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
final ActionListener al = this;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JButton btn = new JButton("Click To Increment Counter");
add(btn);
btn.addActionListener(al);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public void actionPerformed(ActionEvent e) {
try {
JSObject window = JSObject.getWindow(this);
window.eval("sendMsgToIncrementCounter()");
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
I just copy-paste this from the example given on this site:
http://docs.oracle.com/javase/tutorial/deployment/applet/iac.html
This example works perfect in my browser, so the way it is done is correct, but I suspect that I don't import the javafiles correct, since this are the errors from je java-console:
load: class Sender.class not found.
java.lang.ClassNotFoundException: Sender.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:195)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:249)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:179)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:690)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3045)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1497)
at java.lang.Thread.run(Thread.java:680)
Exception: java.lang.ClassNotFoundException: Sender.class
Combining your original method, with the new JS snippet, and part of the accepted answer on your last question (tweaked), gives..
<html>
<head>
<script>
// dangerous to have a 0x0 applet! Some security plug-ins regard it
// as suspicious & automatically remove the element. Better to set it
// not visible using styles
var attributes = {
codebase:'../sesame',
code:'applet_test',
width:10,
height:10
};
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<FORM>
<INPUT
type="button"
value="call JAVA"
onClick = "test()">
</FORM>
<script>
deployJava.runApplet(attributes, parameters, version);
</script>
</body>
</html>
But I just wrote that up off the top of my head. Don't trust me, trust a validation service. ;)
I would advise setting up a simple webservice that your javascript code can use. It doesn't need to be very involved, personally I'd use a simple REST layout with JAX-RS (jersey is really nice to work with), especially if you want something simple with JSON support built-in (with the right plugin).
Trying to actually communicate with the applet on the page might be possible, but very browser dependent and IMHO not worth the hassle. If you're working on the web, might as well use a web service.
There was a problem with the directory of the .class files given in the attributes. Here is the correct code:
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'sesame/Sender.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'sesame/Receiver.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>

How To Implement a progress bar using Spring 3 MVC?

Can anyone teach me or direct to a working example to satisfy this requirement.
Scenario:
List item My Web App is using spring mvc.
One of the services it provides is that when the user clicks on a button a long running process will occur on the server. (Query database, write files, write logs, etc...) this process can take a few seconds or a few minutes.
*Problem***
How can I implement the service to update the client of its progress.
The service returns true or false if the process was successful.
Thanks for your replies. A code snippet or a complete tutorial will be most helpful.
Here is a possible solution to this progress bar problem:
task.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<script src="../js/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON(window.location.href.concat('/status'), function(data) {
if (data === "created") {
} else {
// task is already being executed
refreshProgress();
}
});
});
var width = 0;
function getProgress() {
$.getJSON(window.location.href.concat('/progress'), function(percentage) {
$('#progressBar').css('width', percentage+'%');
document.getElementById("label").innerHTML = percentage * 1 + '%';
width = percentage;
});
}
function start() {
$.ajax({
type: "post",
data: $('#task').serialize(),
success: function(data) {
$('#progressBar').css('width', 100+'%');
document.getElementById("label").innerHTML = 100 * 1 + '%';
// do sth with the data after finished task
}
});
width = 0;
$('#progressBar').css('width', 0+'%');
document.getElementById("label").innerHTML = 0 * 1 + '%';
refreshProgress();
}
function refreshProgress() {
$("#btnStart").prop("disabled",true);
var id = setInterval(frame, 1000);
function frame() {
if (width >= 100) {
clearInterval(id);
$("#btnStart").prop("disabled",false);
} else {
getProgress();
}
}
}
</script>
</head>
<body>
<div class="container">
<h2 class="text-center">Progress Bar Example</h2>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:0%">
<div id="label">0%</div>
</div>
</div>
<form:form method="POST" commandName="task" cssClass="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-md-4 control-label" for="btnStart">Actions</label>
<div class="col-md-8">
<button id="btnStart" name="btnStart" class="btn btn-success">Start</button>
<button id="btnStop" name="btnStop" class="btn btn-danger">Stop</button>
</div>
</div>
</fieldset>
</form:form>
</div>
<script>
$('#task').submit(function () {
start();
return false;
});
</script>
</body>
</html>
TaskController.java
#Controller
#RequestMapping(value = "/task")
public class TaskController {
private Task task;
#RequestMapping("")
protected ModelAndView page() {
ModelAndView model = new ModelAndView(VIEW_DIR + "task");
if (this.task == null) {
this.task = new Task();
}
model.addObject("task", this.task);
return model;
}
#RequestMapping(value = "/status", method = GET)
public #ResponseBody
String getStatus() {
return task.getStatus();
}
#RequestMapping(value = "/progress", method = GET)
public #ResponseBody
int getProgress() {
return task.getProgress();
}
public ModelAndView form(#ModelAttribute Task task) {
this.task = task;
ModelAndView model = new ModelAndView(VIEW_DIR + "task");
task.execute();
model.addObject("task", this.task);
return model;
}
}
Task.java
public class Task {
private int total;
private int progress;
private String status;
public Task() {
this.status = "created";
// TODO get total here or pass via form
}
public void execute() {
status = "executing";
int i = 0;
while (i < total && status.equals("executing")) {
progress = (100 * (i + 1) / total);
i++;
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
There are a good number of ways to handle a scenario like this. One way is to model the work in terms of a "Process", which contains a "status", including a percentage completion.
If you imagine what this might look like on a website, clicking the button to start the process would submit a form that begins the process and assigns some sort of identity to the process, almost like if you were creating any other sort of object. It would then redirect you to a "process status" page.
The process status page would query for the status of the process and display it. It'd probably have a URL parameter for the process's ID. It would perhaps update itself using an AJAX call to return a progress percentage.
On the backend, you now need to solve a couple of problems: finding out the current status of process N, and updating the status of process N. You could accomplish this in a number of ways, including storing the progress in the database or having some sort of in-memory table of running jobs. You could also use some sort of heuristic to estimate a percent. For example, if it's a "register new user" job, maybe it's 20% done if the user's table has an email address, 40% done if the user avatar table has data in it for this user, etc. I don't recommend this as much.

Categories