JSObject.getWindow(this); always throws an exception - java

I'm cutting my teeth on some Java/JavaScript coding and I seem to have hit a wall. I'm trying to pass agruments from Java to JavaScript but no matter what I do "JSObject jso = JSObject.getWindow(this);" always throws an exception. I've done some searching and can't find any solutions. I stole the code below from a website (http://www.codejava.net/java-se/applet/liveconnect-the-api-for-communication-between-java-applet-and-javascript) and don't see any errors in either the JavaScript or the Java and both files compile correctly.
I've added plugin.jar to by buildpath and made sure that the jfxrt.jar is not in the build path. I thought something could possibly be wrong with the plugin.jar in jre7 so I tried jre6 but was getting the same error. The code I'm using is as follows.
Java Code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;
public class TestApplet extends JApplet {
private JButton button = new JButton("Call Javascript");
private JLabel label = new JLabel();
public void init() {
getContentPane().setLayout(new BorderLayout());
getContentPane().add(button, BorderLayout.NORTH);
getContentPane().add(label, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Thread runner = new Thread(new Runnable() {
public void run() {
try {
testLiveConnect();
} catch (JSException jse) {
// Error
jse.printStackTrace();
}
}
});
runner.start();
}
});
}
private void testLiveConnect() throws JSException {
JSObject jso = JSObject.getWindow(this);
// call Javascript's method foo() with no argument
String result = (String) jso.call("foo", null);
label.setText(result);
// delay 2 seconds to see the result
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// call Javascript's method foo() with two arguments
result = (String) jso.call("bar", new String[] {"Alice", "Alisa"});
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// execute a Javascript expression
String expression = "alert('Hi, I am from Javascript.');";
jso.eval(expression);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of a named member from Javascript
result = (String) jso.getMember("coop");
label.setText(result);
try { Thread.sleep(2000); } catch (InterruptedException ie) {};
// get value of an indexed member from Javascript
result = (String) jso.getSlot(1);
label.setText(result);
}
}
JavaScript Code:
<html>
<head>
<title>LiveConnect - Java-Javascript communnication demo</title>
</head>
<body>
<center>
<applet id="testApplet"
code="TestApplet.class"
width="200" height="80"
>
</applet>
</center>
</body>
<script type="text/javascript">
var coop = "Ooops!";
this[1] = "Slot 1";
function foo() {
return "This is from foo()";
}
function bar(firstName, lastName) {
return "Greeting " + firstName + " " + lastName + "!";
}
</script>
</html>
Exception Thrown:
netscape.javascript.JSException
at netscape.javascript.JSObject.getWindow(Unknown Source)
at test.TestApplet.testLiveConnect(TestApplet.java:34)
at test.TestApplet.access$0(TestApplet.java:33)
at test.TestApplet$1$1.run(TestApplet.java:22)
at java.lang.Thread.run(Unknown Source)

This drove me nuts once upon a time. Java7 apparently comes with 2 jars that include different implementations of this same class. jfxrt.jar and plugin.jar
I solved issues with these by simply removing jfxrt.jar from my classpath. You'll have to dig for how to do that for your build system. In Intellij, you can go to:
File -> Project Structure -> SDKs
Then, on the classpath tab, highlight jfxrt.jar and click '-'
ETA: I found the answer that originally helped me that has a bit more info: https://stackoverflow.com/a/14156602/1057157

I had the same problem and solved it simply by changing the following line:
JSObject jso = JSObject.getWindow(this);
to:
JSObject jso = JSObject.getWindow((Applet)this);

Related

Jumping to another class using a JButton

I have the below code where I made a simple GUI. I would like Button2 to navigate to class 'Project2', which should start another piece of code. Just to note, in its current state, 'Project2' has no GUI, though I intend to add one soon. Anyway, this 'code jump' which I used by adding: String[] args = {};
Project2.main(args);
is not working, as the IDE says 'IOException must be caught or thrown'. I know how this works, though I am not sure how to implement it in the program.
Thanks in advance!
You can try to use dynamic class loading for your program. Below you can find lambda, which calls main method from com.stackoverflow.ExternalCaller class.
If you do not like to use lambda, you can create a simple anonymous class.
button.addActionListener(s -> {
try {
Class<?> externalCaller = Class.forName("com.stackoverflow.ExternalCaller");
Method main = externalCaller.getDeclaredMethod("main", new Class[]{String[].class});
main.invoke(null, new Object[]{new String[0]});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
});
ExternalCaller class in its turn looks something like that:
package com.stackoverflow;
public class ExternalCaller {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
In result once you click on the button you will get Hello World output in console.
If you would like to work with external jars etc. please look on Process class. Quick example:
Process proc = Runtime.getRuntime().exec("java -jar External.jar");
Or even more on fork/exec. You can read From Runtime.exec() to ProcessBuilder for more details.
Hope this will help. Good luck.
In most of the IDE's, when you right-click on the Button2 in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
And write this code in the selected method to switch classes:
this.setVisible(false); //turns off the visibility of the current class
outputClass out = new outputClass(); //creating the object of the class you want to redirect to
out.setVisible(true);//turns on the visibility of the class you want to redirect to

Selection of data from Yahoo search bar using csselector fails

package p111;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yahoo_c {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Above is the code.
When i run this, execution goes until "pizza" being entered into yahoo search.Later with no error message in console execution terminates.
The error image is
Please help resolve this issue.Am trying to select pizza delivery from list.
You can try Name instead of path as the yahoo search has a name for selenium to work with. Please let know if Xpath is must for you to work then i will change my code.
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.name("p"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
}
Or you can use the same by ID
public static void main(String [] arg){
WebDriver wi = new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement yahooSearch= wi.findElement(By.id("UHSearchBox"));
yahooSearch.sendKeys("pizza");
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("wait ended");
}
String sl = wi.findElement(By.cssSelector("[id^='yui_3_12_0_1_14']")).getText();
System.out.println(sl);
}
The option you are trying to click is a link in <a> anchor tag.. you can simply use By.linkText if you are specific on the link.
driver.findElement(By.linkText("pizza delivery")).click();
Problem is that you are sendKeys, even though the pizza is typed but the drop-down list does not appears because sendKeys is not equivalent of typing through keyboard. Work around is simple. You need to perform a keyboard action after writing "pizza".
// type pizza
wi.findElement(By.xpath("//[#id='UHSearchBox']")).sendKeys("pizza");
// now perform keyboard action (of pressing space key)
wi.findElement(By.xpath("String")).SendKeys(Keys.Space);
// now click on the pizza delivery link
wi.findElement(By.linkText("pizza delivery")).click();
Try above code in your project, after adding proper wait and with correct element locators.
Try this xpath //*[contains(text(),'pizza delivery')]
It'll work! :)
Check this in firepath and make sure you get only one node with the locator.

Displaying streams in DIV

I am running some terminal(or command prompt) commands through my servlet as below
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] command =
{
"zsh"
};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), response.getOutputStream())).start();
new Thread(new SyncPipe(p.getInputStream(), response.getOutputStream())).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("source ./taxenv/bin/activate");
stdin.println("python runner.py");
stdin.close();
int returnCode = 0;
try {
returnCode = p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("Return code = " + returnCode);
}
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1; )
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
This is displaying the result after executing terminal commands in a new window, I want to avoid that and pass these stream values back to JSP page and display the same in a div.
How to do that?
Static import
First of all, you can define a scriplet with <%= and %> like explained here and here.
Instead of copying the whole code, you can statically import the .jsp page like so:
<%# include file="YourPage.jsp" %>
Link.
To call the page at runtime instead of at the server-side you do:
<jsp:include page="YourPage.jsp"/>
But this doesn't yield a huge advantage over static importing.
Link
You can also declare your function and then use it throughout your webpage by using <%! and %> like shown here.
If you do any of the methods above, your function will (can) be imported only when the page initially loads (server-side). (To be absolutely correct, <jsp:include is called at runtime in theory but in practice it simulates a request without actually making a complete round-trip: server > browser > server > browser).
Dynamic import
For dynamic importing or loading, you have to resort to jQuery (JavaScript) to load your JSP page client-side.
Please refer to this question: How do I inject another JSP page into a <div> when clicking a link?
You could simply do:
function changeContent() {
$('#content').load('YourPage.jsp');
}
You can find other examples here:
Display another jsp content in current jsp page upon a hyperlink click
CodeRanch
To quote the answer from the last link:
That's something to do with Ajax, Jquery can do that. You can use javascript getElementByID or use Jquery's build_in $("sub_banner") syntax to change the div's content.

java.lang.reflect.InvocationTargetException whilst locally running an applet (no server)

I'm trying to load an applet on a simple HTML page that I've written (I also wrote the applet) but it throws an InvocationTargetException every time. The applet works when I run it in Eclipse, but I can't get it to work on the webpage.
HTML:
<html>
<center>
<applet archive = "OneMove.jar" code = "main.TheApplet.class" width = "1000" height = "500"></applet>
</center>
</html>
TheApplet.class:
package main;
import java.awt.BorderLayout;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
public class TheApplet extends JApplet {
private static final long serialVersionUID = 7088647188194272265L;
protected Display display0 = new Display();
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setLayout(new BorderLayout());
add(display0);
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
e.getCause();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start() {
display0.start();
}
public void stop() {
display0.stop();
}
}
If there's any other piece of code you need from me, just ask and I will post.
Need an answer sooner rather than later, too:p
Thanks all!
If you compiled you applet with jdk 1.6 you must use jre 6 for browser.

FileNotFoundException error occurs and file content is not read [duplicate]

I am getting a FileNotFoundException while running code.
my filname is filecontent.java...
Definition: I want to create a program having 4 TextFields and 4 TextAreas. If one types the name of the file in TextField, then its content should be shown in corresponding TextArea.
Error :
Exception e : java.io.FileNotFoundException :
My Code :
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class filecontent extends Frame implements ActionListener
{
TextField t[]=new TextField[4];
TextArea ta[]=new TextArea[4];
Button submit,exit=new Button("Exit");
Panel p1;
filecontent()
{
setGUI();
setRegister();
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e : "+ioe);
}
setTitle("FileData");
setVisible(true);
setSize(300,300);
setLocation(500,200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent we)
{ System.exit(0); }
});
}
void setGUI()
{
p1=new Panel();
p1.setLayout(new GridLayout(5,4,10,10));
for(int i=0;i<4;i++)
{
t[i]=new TextField(10);
ta[i]=new TextArea();
p1.add(t[i]);
p1.add(ta[i]);
}
submit=new Button("Submit");
p1.add(submit);
p1.add(exit);
}
void setRegister()
{
submit.addActionListener(this);
exit.addActionListener(this);
}
void showfile() throws java.io.IOException
{
FileReader fin[]=new FileReader[4];
FileReader fn=new FileReader("filecontent.java");
BufferedReader br[]=new BufferedReader[4];
for(int i=0;i<4;i++)
{
fin[i]=new FileReader(t[i].getText());
}
int cnt=1;
String s;
fn=fin[0];
br[0]=new BufferedReader(fn);
while(cnt<=4)
{
if((s=br[cnt-1].readLine())!=null)
{
ta[cnt-1].append(s+"");
}
else
{
fin[cnt-1].close();
cnt++;
fn=fin[cnt-1];
br[cnt-1]=new BufferedReader(fn);
ta[cnt-1].setText("");
}
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try{
showfile();
}
catch(IOException ioe)
{
System.out.println("Exception e"+ioe);
}
}
else if(ae.getSource()==exit)
{
System.exit(0);
}
}
public static void main(String ar[])
{
new filecontent();
}
}
You don't have a NullPointerException. You have a FileNotFoundException. As the name of this exceptions says this is because a file you try to open isn't found.
The first file access that fails is this one:
FileReader fn=new FileReader("filecontent.java");
If your java file is located within a src (or any other) folder of your project you have to add the folder. E.g. src/filecontent.java
Some other notes:
By convention java class names start with upper case letters
Your variable names t, ta, p1, etc. can be confusing. Why not use textFields, textAreas, panel?
I think you will run into an ArrayIndexOutOfBoundsException in this line while(cnt<=4)
. Array indices start with 0 and end with n - 1 (=3 in your case)
It can help debuging to print out the stacktrace in your catch block: ioe.printStackTrace(). This gives you the exact line number where your code fails
Your exception may have come from this line
FileReader fn=new FileReader("filecontent.java");
I think you should use a full path, not just a file name.
First of all, why don't you use FileDialog instead of textField for the file. Secondly, you are using relative path so for your program to work, the file filecontent.java must be in the same place as your .class file
When reading a file in java the syntax for filepath varies system to system. So you should apply the path according to the operating system you are using.
Also for your code the file filecontent.java should be in the same directory.
Based on your comments, the answer is that the file appears as a.txt in explorer but is actually a.txt.txt Showing file extensions in explorer avoids this issue/confusion.
When you use a file path it is relative to the working directory, i.e. where the application was run. Not where the source code can be found. If you don't know what your working directory is, you should use a full path name.

Categories

Resources