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>
Related
I want to modify the HTML body tag when I open a Wicket-Bootstrap Modal. What I'm trying to achieve is <body class="modal-open"> instead of <body>
Using Wicket 8 M8 , I have this code:
owsImportDialog = new MyModalBootstrapDialog("owsImportDialog"
, new CompoundPropertyModel<>(new BopOwsTO())) {
#Override
void importOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel) {
appendCloseDialogJavaScript(target);
BopOwsTO owsTo = owsModel.getObject();
try {
importOwsCapabilities(owsTo);
owsViewDialog.header(Model.of("OWS anzeigen"))
.setModel(Model.of(owsTo.getServiceId()));
owsViewDialog.appendShowDialogJavaScript(target);
}
catch (OwsCapsImportException e) {
String localizedMessage = e.getLocalizedMessage();
importAlert.setModelObject(localizedMessage);
importAlert.appendShowDialogJavaScript(target);
error(localizedMessage);
}
finally {
target.appendJavaScript("document.getElementsByTagName('body')[0]" +
".setAttribute('class', 'modal-open');");
// target.appendJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.prependJavaScript("document.body.setAttribute('class', 'modal-open');");
// target.appendJavaScript("alert('Hallo');");
// owsViewDialog is a child of owsView WebMarkupContainer
target.add(owsView, feedback);
}
}
#Override
void saveOws(AjaxRequestTarget target, IModel<BopOwsTO> owsModel)
{ }
#Override
void cancel(AjaxRequestTarget target)
{ }
};
If the line target.appendJavaScript("alert('Hallo');"); is active I actually see the alert window.
I also tried this code in the page class:
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
PackageResourceReference resourceReference = new PackageResourceReference(
getClass(), "../css/BuiOwsPage.css");
CssReferenceHeaderItem cssRef = CssReferenceHeaderItem.forReference(resourceReference);
response.render(cssRef);
response.render(OnLoadHeaderItem
.forScript("document.body.setAttribute('class', 'modal-open');"));
}
But none of my attempts was succesful.
Update
The answer of #martin-g didn't solve the issue.
I'm quite sure that the problem is caused by the sequence of these statements:
{
appendCloseDialogJavaScript(target);
...
try {
owsViewDialog.appendShowDialogJavaScript(target);
....
}
catch { ... }
finally {
target.add(owsView, feedback);
}
}
When this modal is closed because of appendCloseDialogJavaScript() ,
the class modal-open is erased from the class attribute of the <body> .
Then owsViewDialog opens, but modal-open isn't inserted in class, no matter if I append the snippet jQuery(document.body).addClass('modal-open') or not. The missing modal-open means that the page can't be scrolled.
Since Wicket and Bootstrap are used then jQuery is also available. I would recommend you to use jQuery(document.body).addClass('modal-open').
There must be a reason why jQuery has both addClass() and attr()!
I use oracle-adf via xml menu model. Now I want to start download file on one of itemNode and without redirect. I'm tried to define action attribute with method which invokes hidden button's method(this button has inner fileDownloadActionListener) through javascript. But it doesn't work. Is it correct? or there is other way to decide this problem? Or may be it is impossible at all?
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn"
action=" "
visible="false"
clientComponent="true"
partialSubmit="false">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
Item node code:
<itemNode id="userInstructionsDownloadFlow" label="Инструкции пользователя"
focusViewId="#"
action="#{pageFlowScope.vocsReportsRegionController.invokeInstructionDownload}"
partialSubmit="true"
clientComponent="true"/>
Javascript cut:
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
Methods' description:
public void invokeInstructionDownload(){
FacesContext context = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(),
ExtendedRenderKitService.class);
erks.addScript(context, "handleInstructionsDownload();");
}
public void instructionsDownload(FacesContext context,
OutputStream out) throws IOException{
File f = new File("C:\\Users\\apozdnyakov\\Downloads\\Типы_контроля_время.xlsx");
FileInputStream fis;
byte[] b;
try {
fis = new FileInputStream(f);
int n;
while ((n = fis.available()) > 0) {
b = new byte[n];
int result = fis.read(b);
out.write(b, 0, b.length);
if (result == -1)
break;
}
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
}
I think there are a few possible reasons of your problem.
1- handleInstructionsDownload javascript function couldn't find the component, because of hierarchy of the jsf codes. You can add log in javascript function, for understanding that.
function handleInstructionsDownload(event) {
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
if (downloadBtn == null) {
console.log('The component is null!');
}
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If you see this log in javascript console you should control your hierarchy of jsf codes. And you should access to button by true component id.
2- invokeInstructionDownload java method couldn't find or call the javascript handleInstructionsDownload function. You can add log in the first line of the javascript function like that:
function handleInstructionsDownload(event) {
console.log('The js function fired!');
event.preventUserInput();
var source = event.getSource().getParent();
var downloadBtn = source.findComponent("downloadInstructionsBtn");
var actionEvent = new AdfActionEvent(downloadBtn);
actionEvent.preventUserInput();
actionEvent.queue();
}
If there is this log in console, you should change your javascript method calling. But I think your Java method is true :)
3- If these are not solutions of your problem, you can change your calling the hidden button like that.
Hidden button code:
<af:commandButton text="NONE"
id="downloadInstructionsBtn" action=" "
visible="false"
clientComponent="true"
partialSubmit="false"
binding="#{pageFlowScope.vocsReportsRegionController.downloadInstructionsBtn}">
<af:fileDownloadActionListener filename="Инструкции пользователя"
contentType="application/vnd.openxmlformats officedocument.spreadsheetml.sheet"
method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/>
</af:commandButton>
ManagedBean code:
private RichButton downloadInstructionsBtn;
public RichButton getDownloadInstructionsBtn() {
return downloadInstructionsBtn;
}
public void setDownloadInstructionsBtn(RichButton downloadInstructionsBtn) {
this.downloadInstructionsBtn = downloadInstructionsBtn;
}
public void invokeInstructionDownload(){
ActionEvent actionEvent = new ActionEvent((UIComponent) downloadInstructionsBtn);
actionEvent.queue();
}
I'm embedding an applet in a web page and trying to call a function in the applet but get the error "Object doesn't support property or method 'setDestination' when I click the button and the "doit()" function is called. The applet is loaded and on the screen.
Java code (compiled and put into a signed jar named webcam.jar):
import javax.swing.JApplet;
public class MyAppletLauncher extends JApplet {
private JarClassLoader jcl;
public void setDestination()
{
System.out.println("MyAppletLauncher: setdestination!");
System.out.println(url);
}
#Override
public void init() {
jcl = new JarClassLoader();
try {
jcl.initApplet("webcam", this);
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void start() {
jcl.startApplet();
}
#Override
public void stop() {
jcl.stopApplet();
}
#Override
public void destroy() {
jcl.destroyApplet();
}
} // class MyAppletLauncher
Here's the HTML:
<HTML><BODY>
<applet id=cameraapplet name="camerax" code="MyAppletLauncher.class" height="100%" width="100%" archive="webcam.jar">
</applet>
<SCRIPT type="text/javascript">
function doit() {
alert(1);
document.camerax.setDestination(); // Dies on this line
alert(2);
}
</Script>
<input type=button onclick='doit();'>
</BODY></HTML>
Use the applet id to get a reference to the applet object:
document.getElementById("cameraapplet").setDestination();
Note however that the <applet> tag is not supported by HTML5. Read this article on how to use
<embed> or <object> for Java applets.
I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>
i know the question may sound easy to most of you but I am stuck with it.
First of all i like to define what i am trying to achieve.
on eclipse i am running a piece of code that sends some data over specific port, and via html and javascript i am getting those that it's sent and print them on screen.
I have an account from one of free hosting websites.
I want to run my code on that website e.g mywebsite.blahblah.com/...
and from html file on my computer i want to access that website, get those values produced by java code and print them on screen.
I have no idea where to start.
the codes are
java and html
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class GPSServer extends WebSocketServer {
static int port = 9876;
public GPSServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public GPSServer(InetSocketAddress address) {
super(address);
}
public void sendData(String s) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(s);
}
}
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
System.out.println(arg0.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ " connected to the server!");
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
System.out.println(arg0 + " disconnected!");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
arg1.printStackTrace();
if (arg0 != null) {
}
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
System.out.println(arg0 + ": " + arg1);
}
public static Runnable sendData() {
Runnable r = new Runnable() {
#Override
public void run() {
WebSocketImpl.DEBUG = true;
GPSServer server;
try {
server = new GPSServer(GPSServer.port);
server.start();
System.out.println("GPS server started at port: "
+ server.getPort());
double longitude = 39.55;
double latitude = 22.16;
String lng = Double.toString(longitude);
String ltd = Double.toString(latitude);
String all = lng + "-" + ltd;
while (true) {
server.sendData(all);
/*
* server.sendData(Double.toString(longitude));
* System.out.println("longitude sent...");
* server.sendData(Double.toString(latitude));
* System.out.println("latitude sent...");
*/
Thread.sleep(5000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return r;
}
public static void main(String[] args) throws UnknownHostException {
Thread thread = new Thread(GPSServer.sendData());
thread.start();
}
}
--
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
var lat;
var lng;
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9876/echo");
ws.onopen = function()
{
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var partsArray = evt.data.split('-');
lng=partsArray[0];
lat=partsArray[1];
alert(lat);
alert(lng);
};
ws.onclose = function() {
alert("Connection is closed...");
console.log("Connection is closed...");
};
}
else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
<div>
<p id="para"> BASIC HTML!</p>
</div>
</body>
</html>
Thanks!
I'm assuming you're very new to all this web development. I haven't studied your code fully but the basic idea is you need a server side scripting language like JSP(of course JSP because you're using Java Code). I hope you know Javascript's basic idea is to use resources on the client's end, or to load data dynamically. So if you're only concerned with displaying some values from server to the client, you can simple make a servlet which will print your data.
Following MVC pattern,
Controller== Make a servlet which will handle the request made by user(i.e. the link which will show data,basically). Set your Model in this controller once you receive a request(you can decide what to do on GET/POST separately too).
Model== Make an abstract representation(class of Java) holding all your data that is to be displayed.
View== Here you'll receive the model. In other words, this will be your HTML. You can use JSP helpers to customize the view, the basic idea is to control HOW DATA WILL BE SHOWN TO THE USER(hence the name View). HTML will be automatically generated at run-time and passed to the user.
Again, I say I'm assuming you're very new to web development. Please let me know if I haven't understood your question well. Enjoy coding.