make work an applet in a osgi bundle - applet

I would like to create a web application that performs some sort of animation of some bundle's activity inside an OSGI Framework. I'm using Equinox embedded in Tomcat through Servletbridge. I have tried to create an OSGI bundle that registers an HTML page (with an applet tag) using httpservice. The OSGI bundle contains a package with the applet class.
When I export the plugin project in the tomcat/webapps/bridge/WEB-INF/eclipse/plugin directory the jar content is:
META-INF
META-INF/MANIFEST.MF
name/of/packages/.class files
home.html
In the activator class of this bundle I get an httpservice and register the home.html file as /home. When I start Tomcat and go to:
localhost:8080/bridge/home
The page loads, but I get a ClassNotFoundException on the applet, whereas opening the HTML page from the Jar archive the Applet load. How can I make it work?
edit:
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<applet code="thesis.bot.wab.applet.DApplet.class" width="400" height="250"></applet>
</body>
</html>
src/thesis.bot.wab.Activator
public class Activator implements BundleActivator {
private static boolean started=false;
HttpServiceTracker http;
public void start(BundleContext context) throws Exception {
System.out.println("started");
http = new HttpServiceTracker(context);
http.open();
started=true;
}
public void stop(BundleContext context) throws Exception {
System.out.println("stopped");
started=false;
http.close();
}
public static boolean isStarted(){
return started;
}
private class HttpServiceTracker extends ServiceTracker {
public HttpServiceTracker(BundleContext context) {
super(context, HttpService.class.getName(), null);
}
public Object addingService(ServiceReference reference) {
HttpService httpService = (HttpService) context.getService(reference);
try {
httpService.registerResources("/home", "/home.html", null);
httpService.registerServlet("/servlet", new DServlet(context), null, null);
}
catch (Exception e) {
e.printStackTrace();
}
return httpService;
}
public void removedService(ServiceReference reference, Object service) {
HttpService httpService = (HttpService) service;
httpService.unregister("/servlet"); //$NON-NLS-1$
httpService.unregister("/home");
super.removedService(reference, service);
}
}
}
edit: my purpose is to retrieve the bundlecontext and getting information about bundles to visualize them in the applet.

First your browser downloads the html file. After it is downloaded, the browser checks the applet tag in the html. It starts a JVM that tries to download the applet from the url:
http://localhost:8080/bridge/thesis.bot.wab.applet.DApplet.class
However, nothing is there and why would be anything?
You should register the class file or the full jar file as a resource. After that, you should insert an applet tag into the html file that points to the jar or class file. In case your applet has any dependencies, those jars should be listed as well.
It is useful to switch on the Java console (google for it) and push the button "5" to have low level debug messages. There you will see the issues why your applet does not start (downloading urls, dependency issues...)

Related

Eclipse display browser in view

I am trying to create a plug-in, which will show local .html file inside internal browser. Currently i am extending class ViewPart, and writing code into its createPartControl method. Most of people are using this snippet
IWebBrowser browser = PlatformUI.getWorkbench().getBrowserSupport().createBrowser("SOMELABEL");
browser.openURL(url);
Problem is that this snippet opens another view where internal browser is opened, but in my case it needs to be in this view...
I also tried other forms of createBrowser method, e.g.
createBrowser(int style, String browserId, String name, String tooltip);
where i tried to configure flags, but all of these options just open another view or editor. Is there a way do draw HTML inside my view?
I have found the solution. Yes i have tried Browser control before, but i did not created Browser properly (wrong arguments). If anybody else tries to implement ViewPart displaying html pages via SWT, here is the code snippet.
public class CustomView extends ViewPart {
private static final String URL = "file:///d:/playground/d3/project.html";
#Override
public void createPartControl(Composite parent) {
final Browser browser = new Browser(parent, SWT.NONE);
browser.setUrl(URL);
}
#Override
public void setFocus() {
}
}

window.parent not working in jsni

I am using GXT's sencha
We have a web application named "dashboard"
url = localhost:8080/dashboard/
We have another webapplication named issuetracker
url = localhost:2990/issuetracker/
Now i have a velocity template in the issuetracker web application in which i have given the following code
<iframe src="localhost:8080/dashboard" width="500" height="600">
</iframe>
When i click a button in the dashboard web application the url of the issuetracker application should change like "localhost:8080/issuetracker/issues?mqlVersion=25".
This 25 value comes from the dashboard web application.
When i tried writing jsni code none of the following values showed up
the top most window's url which is "localhost:2990/issuetracker/"
$wnd.top.location
$wnd.top.location.href
$wnd.parent.location.href
$wnd.parent.location
window.top.location
window.top.location.href
window.parent.location.href
window.parent.location
Where am i going wrong?
Any suggestions.
Use $wnd in JSNI instead of window.
Try (clean browser cache)
JSNI
Window.Location.replace(url);
public static final native String getParentWindow() /*-{
return $wnd.parent.location.href;
}-*/;
JSP/HTML
<script type="text/javascript">
function changeURL() {
try {
window.parent.location.href = 'http://localhost:8080/issuetracker/issues?mqlVersion=25';
} catch (e) {
window.location.href = 'http://localhost:8080/issuetracker/issues?mqlVersion=25';
}
}
</script>
Sample code
JSP/HTML
<div>
<div id='myDiv'>hello</div>
<iframe src="localhost:8080/dashboard" width="500" height="600">
</iframe>
</div>
dashboard Entry Point class:
public static final native Element getParentElementById(String id) /*-{
return $wnd.parent.document.getElementById(id);
}-*/;
....
public void onModuleLoad() {
getParentElementById("myDiv").setInnerHTML("hi");
}
Output:
Inner HTML hello of myDiv is replaced with hi.

GWT Script Injection Failure with PubNub

New to GWT but I love it so far. I do have a problem that's easy to reproduce. It is a big problem for me because I want to create a GWT Module for PubNub - a utility we use internally.
I created a demo project to test out encapsulation and I have found an interesting problem with ScriptInjector/Pubnub.
At first I followed the PubNub instructions. NOTE: I have included my keys for my test account. Feel free to use them.
Following the instructions I put these two items in the html file in the GWT project (with my keys specified):
<div pub-key="pub-b8b75fbd-c4cf-4583-bab9-424af7a7f755" sub-key="sub-5e843c94-1193-11e2-bba9-b116c93082cf" ssl="off" origin="pubsub.pubnub.com" id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
When I do this, I can use JSNI to access pubnub. It all works great.
What doesn't work is if I delete the tag here and inject the script instead with the following code. I know the script injects because I can see the success message and I can see the script in Developer tools in Chrome.
ScriptInjector.fromUrl("http://cdn.pubnub.com/pubnub-3.1.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).inject();
I feel this must be somehow related to accessing the DOM with the delayed script, or because the script is not a part of the DOM. It's trying to access the setup div and it's not able to...(just my guess)
Any thoughts? I need to move the items out of the html file because I need to modularize this project for use in other larger projects. Any help would be appreciated.
(PS, I have tried to create html widgets as well, and add them in EntryPoint. This also adds the tag to the page based on my browsing in Developer Tools in Chrome, but it fails to work just as ScriptInjector fails.)
EDIT: Here is as simple a project as I can make to demo the problem:
html file:
above the closing body tag:
<div pub-key="pub-b8b75fbd-c4cf-4583-bab9-424af7a7f755" sub-key="sub-5e843c94-1193-11e2-bba9-b116c93082cf" ssl="off" origin="pubsub.pubnub.com" id="pubnub"></div>
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
<script src="pubnubWrapper.js"></script>
pubnubWrapper.js (basically what's at the pubnub website):
function subToPubNub(){
    PUBNUB.subscribe({
        channel    : "hello_world",      // CONNECT TO THIS CHANNEL.
 
        restore    : false,              // STAY CONNECTED, EVEN WHEN BROWSER IS CLOSED
                                         // OR WHEN PAGE CHANGES.
 
        callback   : function(message) { // RECEIVED A MESSAGE.
            alert(message);
        },
 
        disconnect : function() {        // LOST CONNECTION.
            alert(
                "Connection Lost." +
                "Will auto-reconnect when Online."
            )
        },
 
        reconnect  : function() {        // CONNECTION RESTORED.
            alert("And we're Back!")
        },
 
        connect    : function() {        // CONNECTION ESTABLISHED.
 
            PUBNUB.publish({             // SEND A MESSAGE.
                channel : "hello_world",
                message : "Hi from PubNub."
            })
 
        }
    })
}
ScriptTest.java:
public class ScriptTest implements EntryPoint {
public void onModuleLoad() {
//add a button to sub to pubnub
Button subButton = new Button("Sub");
//add the event handler for button
subButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
//sub to pubnub
callSub();
}
});
RootPanel.get().add(subButton);
}
public native void callSub() /*-{
//call my wrapper to pubnub
$wnd.subToPubNub();
}-*/;
}
This all works as is.
If you remove the pubnub script from the html file and add it with script injector, it fails. If you add the script to the gwt.xml file, it fails.
Any Ideas?
Can you post your JSNI code?
I bet you are accessing PubNub via the $wnd variable right?
If you put the script tags in your module's xml file the pubnub code will be loaded in the host's page window (you can check with Chrome DeveloperTools).
ScriptInjector by default won't load it there but in the GWT namespace.
So in order to load it into the host's window namespace you have to pass the TOP_WINDOW to the ScriptInjector
ScriptInjector.fromUrl("http://cdn.pubnub.com/pubnub-3.1.js").setCallback(
new Callback<Void, Exception>() {
public void onFailure(Exception reason) {
Window.alert("Script load failed.");
}
public void onSuccess(Void result) {
Window.alert("Script load success.");
}
}).setWindow(ScriptInjector.TOP_WINDOW).inject();

automatic refresh of GWT screen

I am working in GWT in the project.
I have a requirement in my project where I need an automatic refresh of my screen every 5 minutes.
Can somebody please help me?
public class TimerExample implements EntryPoint, ClickListener {
public void onModuleLoad() {
Button b = new Button("Click and wait 5 minutes");
b.addClickListener(this);
RootPanel.get().add(b);
}
public void onClick(Widget sender) {
Timer t = new Timer() {
public void run() {
reloadAll();
}
};
// Schedule the timer to run once in 5 minutes.
t.schedule(5*1000*60);
}
private void reloadAll() {
Window.Location.reload();
}
}
If you use the Activies and Places framework from GWT, you could use the activity-mapper with the 'goTo(samePlace)' method to handle your usecase easily. It's part of the MVP design/pattern.
Refresh every 300 seconds (5 minutes):
<meta http-equiv="refresh" content="300">
Place this meta tag under the head element of your gwt html hosting page.
If you use a JSP rather than a HTML file as the GWT hosting file, you could do this
<%
String refreshInterval = request.getParameter("refreshInterval");
%>
<head>
<meta http-equiv="refresh" content="<%=refreshInterval%>">
</head>

GWT TestCase: Simulating clicking a button on my page

I'm using GWT 2.4 with JUnit 4.8.1. When writing my class that extends GWTTestCase, I want to simulate clicking on a button on the page. Currently, in my onModuleLoad method, this button is only a local field ...
public void onModuleLoad() {
final Button submitButton = Button.wrap(Document.get().getElementById(SUBMIT_BUTTON_ID));
...
// Add a handler to send the name to the server
GetHtmlHandler handler = new GetHtmlHandler();
submitButton.addClickHandler(handler);
How do I simulate clicking on this button from the GWTTestCase? Do I have to expose this button as a public member accessor is there a more elegant way to access it? Here is what I have in my test case so far ...
public class GetHtmlTest extends GWTTestCase {
// Entry point class of the GWT application being tested.
private Productplus_gwt productPlusModule;
#Override
public String getModuleName() {
return "com.myco.clearing.productplus.Productplus_gwt";
}
#Before
public void prepareTests() {
productPlusModule = new Productplus_gwt();
productPlusModule.onModuleLoad();
} // setUp
#Test
public void testSuccessEvent() {
// TODO: Simulate clicking on button
} // testSuccessEvent
}
Thanks, - Dave
It can be as easy as buttonElement.click() (or ButtonElement.as(buttonWidget.getElement()).click(), or ButtonElement.as(Document.get().getElementById(SUBMIT_BUTTON_ID)).click())
But remember that a GWTTestCase doesn't run in your own HTML host page, but an empty one, so you'll first have to insert your button within the page before simulating your module's load.
gwt-test-utils seems to be the perfect framework to answer your need. Instead of inheriting from GWTTestCase, extend the gwt-test-utils GwtTest class and implement your click test with the Browser class, like shown in the getting starting guide :
#Test
public void checkClickOnSendMoreThan4chars() {
// Arrange
Browser.fillText(app.nameField, "World");
// Act
Browser.click(app.sendButton);
// Assert
assertTrue(app.dialogBox.isShowing());
assertEquals("", app.errorLabel.getText());
assertEquals("Hello, World!", app.serverResponseLabel.getHTML());
assertEquals("Remote Procedure Call", app.dialogBox.getText());
}
If you want to keep your button private, you'd be able to retrieve it by introspection. But my advice is to make you view's widgets package protected and to write your unit test in the same package so it could access them. It's more convinent and refactoring-friendly.
gwt-test-utils provide introspection convinence. For example, to retrieve the "dialogBox" field which could have been private, you could have do this :
DialogBox dialogBox = GwtReflectionUtils.getPrivateFieldValue(app, "dialogBox");
But note that using GwtReflectionUtils is not mandatory. gwt-test-utils allows you to use ANY java classes in GWT client side tests, without restriction :)
You can do it like this:
YourComposite view = new YourComposite();
RootPanel.get().add(view);
view.getSubmitButton.getElement().<ButtonElement>cast().click();