Finding out when a GWT module has loaded - gwt

I am exporting a GWT method to native javascript in the following manner:
public class FaceBookGalleryEntryPoint implements EntryPoint {
#Override
public void onModuleLoad() {
FacebookGallery facebookGallery = new FacebookGallery();
RootPanel.get().add(facebookGallery);
initLoadGallery(facebookGallery);
}
private native void initLoadGallery(FacebookGallery pl) /*-{
$wnd.loadGallery = function (galleryId) {
pl.#com.example.fbg.client.FacebookGallery::loadGallery(Ljava/lang/String;)(galleryId);
};
}-*/;
}
In the host page, I am trying to invoke it:
<html>
<head>
<title>Facebook image gallery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" src="/fbg/fbg.nocache.js"></script>
<h1>Facebook gallery test</h1>
<script type="text/javascript">
$(document).ready(function() {
loadGallery('blargh');
});
</script>
</body>
</html>
Unfortunately, when the document.ready callback is invoked, the function is not yet defined. When manually executed from the Firebug console the function works just fine.
I could perform some polling every 50 milliseconds until I find a defined function by that name, but it seems like a horrible approach.
How can I get notified when the module is loaded and therefore when the function is available?

I would try to define a callback function in the hostpage and call it from GWT at the end of the onModuleLoad() method.
Hostpage function:
<script type="text/javascript">
function onGwtReady() {
loadGallery('blargh');
};
</script>
GWT:
public void onModuleLoad() {
FacebookGallery facebookGallery = new FacebookGallery();
RootPanel.get().add(facebookGallery);
initLoadGallery(facebookGallery);
// Using a deferred command ensures that notifyHostpage() is called after
// GWT initialisation is finished.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
notifyHostpage();
}
}
}
private native void notifyHostpage() /*-{
$wnd.onGwtReady();
}-*/;

Related

Call javascript function from Capacitor Java

//solution is:
import android.webkit.WebView;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
//in my case I call it the JS function when I press the back button
#Override
public void onBackPressed() {
WebView webView = getBridge().getWebView();
webView.loadUrl("javascript:pressBack()");
// in Index.html create tag
// <script type="text/javascript">
//function pressBack(){
// alert('yes!!')
//} </script>
return;
}
}
// it works fine 100%

asp.net core with signalR < - > static socket

Use Case:
I have a asp.net core web application with signalR core for messaging. :)
Problem:
I have to receive messages from a socket connection [via System.Net.Sockets] (machine with own socket communication)
Is there any way to integrate the socket client in the web app (maybe Progamm.cs or Startup.cs?)
And how can I get access to the signalR to forward the received message to the signalR Hub?
thx
I suggest you to read the stockticker sample on : https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-server-broadcast-with-signalr
I show you here a small sample which you can adapt to your application. You have to subscribe the messages from your own socket communication and then you can forward this messages to the connected clients.
Here is a small sample how to send the time from server to the clients.
(The interesting part for you is the line GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.All.sendTime(DateTime.UtcNow.ToString());. Which this you can send something to all connected clients.
My main class is a clock which sends the actual time to all connected clients:
public class Clock
{
private static Clock _instance;
private Timer timer;
private Clock()
{
timer = new Timer(200);
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{ // ---> This is the important part for you: Get hubContext where ever you use it and call method on hub GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.All.sendTime(DateTime.UtcNow.ToString());
GlobalHost.ConnectionManager.GetHubContext<ClockHub>().Clients.Clients()
}
public static Clock Instance
{
get
{
if (_instance == null)
{
_instance = new Clock();
}
return _instance;
}
}
}
}
In the startup I created a sigleton instance of this clock, which lives as long as the application is running.
public class Startup
{
public void Configuration(IAppBuilder app)
{
var inst = Clock.Instance;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}
My Hub:
public class ClockHub : Hub<IClockHub>
{
}
Hub interface which defines the method, which the server can call:
public interface IClockHub
{
void sendTime(string actualTime);
}
This is the clients part:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="timeLabel" ></div>
<script src="scripts/jquery-1.6.4.min.js"></script>
<script src="scripts/jquery.signalR-2.2.0.js"></script>
<script src="signalr/hubs"></script>
<script>
$(function () { // I use jQuery in this example
var ticker = $.connection.clockHub;
function init() {
}
ticker.client.sendTime = function (h) {
$("#timeLabel").html(h);
}
$.connection.hub.start().done(init);
});
</script>
</body>
</html>
How to inject hubcontext in asp.net core 2.x
Call SignalR Core Hub method from Controller

How to add back the "loading" Element after removed it from Parent?

Ok, in war/MyProject.html, I have:
<body>
<div id="loading">
<div id="waitingForLoading"></div>
<BR/>
<img src="../images/loading.gif" />
</div>
...
</body>
in MyProject.java
public class OfflineMatching implements EntryPoint {
#Override
public void onModuleLoad() {
// this code works fine
if(DOM.getElementById("loading")!=null){
DOM.getElementById("loading").removeFromParent();
}
Button myButton=new Button("Enter Main Page");
RootPanel.get().add(myButton);
myButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
// this code does not work
if(DOM.getElementById("loading")==null){
DOM.appendChild(RootPanel.getBodyElement(), DOM.createElement("loading"));
}
}
});
}
}
So, did i do anything wrong?
Why this code does not work?
// this code does not work
if(DOM.getElementById("loading")==null){
DOM.appendChild(RootPanel.getBodyElement(), DOM.createElement("loading"));
}
DOM.createElement(String tagName) creates a <tagname> element. So, if you pass "loading" to it, it will create a <loading> element.
For a quick workaround, you can use RootPanel.get, and then call setVisible on the widget:
// onModuleLoad:
RootPanel.get("loading").setVisible(false);
// onClick:
RootPanel.get("loading").setVisible(true);
But a better approach would be creating the loading <div> as a widget in GWT and just call setVisible on its instance, without relying on ids.

how to add script to the body (similar functionality like method renderHead(Component component, IHeaderResponse response))

With the following code, I add trackingpixel to some page page.html by overriding the method renderHead(Component component, IHeaderResponse response). This works fine.
page.html looks like this:
<!doctype html>
<html xmlns:wicket="http://wicket.apache.org/">
<head>
..
<wicket:container wicket:id="header"></wicket:container>
</head>
<body>
..
<script wicket:id="scriptHolder" type="text/javascript" > I would like to add my script here
</script>
..
</body>
</html>
TrackingPixel.java:
public abstract class TrackingPixel extends AbstractDefaultAjaxBehavior {
protected TrackingPixel(TrackingPixelType type) {
..
}
#Override
public void renderHead(Component component, IHeaderResponse response) {
response.renderOnDomReadyJavaScript("WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
");
}
}
renderHead-method adds a trackingpixel to the main page. Right mouse click on the page -> source code shows that the following script is added to the page:
<script type="text/javascript" >
Wicket.Event.add(window, "domready", function(event) {
WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
..
;});
</script>
Now I would like to add trackingpixel to a popup. My problem is that I can't add a script to the body. The method renderHead(Component component, IHeaderResponse response) doesn't do that, because (I guess) the popup pops up on the same page, so there is only one head and it will not render twice. So I tried to do this with WebMarkupContainer as you can see below.
OurServicePopup.java
/**
* Class to display our service as popup
*/
public class OurServicePopupPage<T> extends WebPage {
public OurServicePopupPage(PageParameters parameters) {
super(parameters);
}
#Override
protected void onInitialize() {
add(new OurServicePixel());
super.onInitialize();
}
}
OurServicePixel.java looks like this:
public class OurServicePopupPixel extends TrackingPixel{
public OurServicePopupPixel() {
}
WebMarkupContainer scriptContainer = new WebMarkupContainer("scriptContainer");
#Override
public void renderHead(Component component, IHeaderResponse response) {
scriptContainer.add(new AttributeAppender("type", Model.of("text/javascript")));
scriptContainer.add(
new AttributeAppender("src","WebtrekkInstance = {
..
'path' : 'anyPath',
...:...
..
};
");
}
add(scriptContainer); //this shows error
}
The problem here is that I cannot add the scriptContainer. add(scriptContainer); will not work, because OurServicePopupPixel is a behaviour and not a page.
Maybe you can simple use a Label component with setEscapeModelStrings(false). But it seems a bit strange.
I didn't full understand what is your javascript doing, but maybe you can try to execute it when the DOM is ready. Using a renderHead like this:
public void renderHead(IHeaderResponse response) {
response.render(OnDomReadyHeaderItem.forScript( ... YOUR SCRIPT HERE ... ));
}
I hope it helps.

tomcat websocket : cannot connect to tomcat server

I'm trying to use websocket on tomcat 7.0.29, to implement pub/sub system, but somehow I don't know why, it just always alert "close" every time I open the browser..
env is tomcat-7.0.29, Eclipse Juno, written in scala..
much appreciated if anyone can help...
My servlet is below:
[PubServlet]:
class PubServlet extends WebSocketServlet {
override def createWebSocketInbound (subProtocol: String, request: HttpServletRequest): StreamInbound = {
println("create#############################################")
new WebSocketHandler()
}
}
[InitServlet]:
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = -3163557381361759907L;
private static List<MessageInbound> socketList;
public void init(ServletConfig config) throws ServletException {
InitServlet.socketList = new ArrayList<MessageInbound>();
super.init(config);
System.out.println("Server start============");
}
public static synchronized List<MessageInbound> getSocketList() {
return InitServlet.socketList;
}
}
[WebsocketHandler]:
class WebSocketHandler extends MessageInbound{
protected override def onBinaryMessage(arg0: ByteBuffer) {
// TODO Auto-generated method stub
}
protected override def onTextMessage(msg: CharBuffer) {
}
protected override def onClose(status: Int) {
println(status)
super.onClose(status)
}
protected override def onOpen(outbound: WsOutbound) {
super.onOpen(outbound)
InitServlet.getSocketList().add(this)
}
}
and My client code is here:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
<script type="text/javascript">
var ws = null;
function startWebSocket() {
if ('WebSocket' in window){
ws = new WebSocket("ws://localhost:8080/PubSub_Web/index.do");
alert(ws);
}
else if ('MozWebSocket' in window)
ws = new MozWebSocket("ws://localhost:8080/PubSub_Web/index.do");
else
alert("not support");
ws.onmessage = function(evt) {
alert(evt.data);
};
ws.onclose = function(evt) {
alert("close");
};
ws.onopen = function(evt) {
alert("open");
};
}
function sendMsg() {
ws.send(document.getElementById('writeMsg').value);
}
</script>
</head>
<body onload="startWebSocket();">
<input type="text" id="writeMsg"></input>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>
See this answer. You are best off using the standard jaxax websocket-api which is available in Tomcat 7.0.47
You need to override getReadTimeout method, which is used to set socket timeout in milliseconds. for example, if you want to set socket timeout 2 minutes (2*60*1000) than you may use below code.
#Override
public int getReadTimeout() {
return 2*60*1000;
}
Note: you can set infinite (always open) by returning -1.