java.lang.runtimeexception java.lang.reflect.invocationtargetexception - java

I have a Javascript program that call a Java program via Applet with the following command inside the Applet:
script.code = "InJava.class";
It was necessary to make a change in the Java program, and now it creates two classes: InJava.class and InJava$1.class
Now, when I run the program in Javascript, the program does not answer anything.
If I change the statement to:
script.code = "InJava$1.class"
It returns the following error:
runtimeexceptionjava.lang.reflect.invocationtargetexception
How must I stated in the Javascript program?
Must I change something in my Java program?
The Java program is below:
Java Program
public void sayHello() throws IOException {
java.io.FileInputStream fis = AccessController.doPrivileged(new PrivilegedAction<FileInputStream>() {
public FileInputStream run() {
try {
return new FileInputStream(parametro);
} catch (IOException e) {
String retorno_exc = e.toString();
}
return null;
}
});

Related

Desktop.getDesktop().open(file) on Ubuntu not working

I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

PigServer script execution

I have a java code that generates pig script. I am wondering if there is option to execute that script directly within the java code. I found there is a option to embed pig script execution inside java code using PigServer class.
The problem is that I'm using AvroStorage to store the results and the class contains method Store() that apparently uses file storage.
Is there any way how to execute my pig script using AvroStorage inside JAVA using PigServer class?
Its generic code from their DOC, they use pigServer.store("D", "myoutput"); but instead of the file i need to call AvroStorage.
public class WordCount {
public static void main(String[] args) {
PigServer pigServer = new PigServer();
try {
pigServer.registerJar("/mylocation/tokenize.jar");
runMyQuery(pigServer, "myinput.txt";
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void runMyQuery(PigServer pigServer, String inputFile) throws IOException {
pigServer.registerQuery("A = load '" + inputFile + "' using TextLoader();");
pigServer.registerQuery("B = foreach A generate flatten(tokenize($0));");
pigServer.registerQuery("C = group B by $1;");
pigServer.registerQuery("D = foreach C generate flatten(group), COUNT(B.$0);");
pigServer.store("D", "myoutput");
}
}

Calling Perl script from Java (JAX-WS in Eclipse)

I have a JAX-WS webservice that receives a string as parameter, calls a Perl script, and returns the string converted to upper case. It is running on Tomcat 8 (localhost on Eclipse).
When I type from the console:
curl -X POST --data "mystring=HelloWorld" http://localhost:8080/MyServices/api/generatePath
Everything works except for the Perl call. On the debugger I see that line is executed, but apparently nothing happens (not even errors). If I run perl /home/me/workspace/match.pl from the console it works perfectly. The path of the match.pl file is correct.
In addition, process.exitValue() return 2.
#Path("/")
public class MyServices {
#POST
#Path("/generatePath")
#Produces(MediaType.APPLICATION_JSON)
public Response generatePathService(
#FormParam("mystring") String myString) {
Process process = null;
try {
process = Runtime.getRuntime().exec("perl /home/me/workspace/match.pl --lang en");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Response.status(200).entity(myString.toUpperCase()).build();
}
}
I got similar stuff some time ago. The solution for me was to 'accept' the output of the program. Something like this:
Process p = Runtime.getRuntime().exec(cmd);
final InputStream is = p.getInputStream();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (is.available() != 0) {
is.read();
}
} catch (IOException ex) {
}
}
}).start();
You should also try to get the error stream with p.getErrorStream(). An alternative could be to change your perl program in that way that there is nothing printed to standard out or error out.
Or you call a shell script and redirect the output to dev/null (someting like ´blabla>/dev/null`.

invoke methods in a windows service made by winrun4j

I made a windows service from a jar file using WinRun4J, so far it's very basic.
package org.boris.winrun4j.test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import org.boris.winrun4j.Service;
import org.boris.winrun4j.ServiceException;
public class ServiceWrite implements Service
{
private volatile boolean shutdown = false;
public int serviceMain(String[] args) throws ServiceException {
int count = 0;
while (!shutdown) {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
try {
FileWriter fstream = new FileWriter("result.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Counts: " + count);
out.close();
} catch (Exception e){
}
count++;
}
return 0;
}
public int serviceRequest(int control) throws ServiceException {
switch (control) {
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
shutdown = true;
break;
}
return 0;
}
}
When the service is started it just keeps writing every couple of seconds to result.txt located in the root folder.. (Just for trying out WinRun4J)
Now my question is, can I do a method in the service jar, like this
public void write(String s){
//Write some string s to result.txt
}
And then invoke this method from a different java file on the system, i.e
java WriteToFile SomeString
Where WriteToFile is supposed to invoke write with some argument.
Is it possible? if so, how ?
The overall purpose of this is to have a service running where I can invoke methods via a GUI.
to "invoke methods via a GUI", you can't do it with WinRun4J.
in general rule, a Windows Service can't have a GUI for security reason (except for special cases).
However, there are other tools to create a windows service from a Java application, with which it will be possible to have a service with GUI and able to interact with the Desktop.

Call a java applet method via javascript

How can I call a function when a specific event occurs in my java Applet ?
In my Javascript I has the following code, that always return a empty value.
$(function () {
alert(document.applets[0].returnClientId());
});
I need to call this alert, just when a specific method is executed. To be more specific, the method called identify, that exists in my java Applet.
The identify method, exists in my Util.class, that don't extends from JApplet.
My FormMain.class extends from JApplet and I call some methods (including the identify method) from this Util.class.
UPDATE: My Java Code
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String returnClientId() {
return getClientid();
}
public void identify() {
try {
fingerprintSDK.prepareForIdentification(this.template);
ResultSet rs = identifyStmt.executeQuery();
while (rs.next()) {
byte[] templateBuffer = rs.getBytes("template");
Template referenceTemplate = new Template(templateBuffer);
boolean matched = fingerprintSDK.identify(referenceTemplate);
if (matched) {
// ui is my FormMain instance
ui.showImage(GrFingerJava.getBiometricImage(template,
fingerprint, fingerprintSDK));
ui.writeLog("Found. Client = "
+ rs.getString("Name"));
ui.setClienteid(rs.getString("Cliente_Id"));
ui.disableTemplate();
return;
}
}
ui.writeLog("Not Found.");
ui.enableTemplate();
} catch (SQLException e) {
ui.writeLog(e.getMessage());
} catch (GrFingerJavaException e) {
ui.writeLog(e.getMessage());
}
}
The Identify method is executed just when my User put the finger in the biometric device.
Someone has some idea ?
Suppose you have the following JS function
function foo(client) {
alert(client);
}
you'll modify your Utils.java as follows
public void identify() {
// the rest of your code
String id = rs.getString("Cliente_Id");
ui.setClienteid(id);
// call the Javascript function
JSObject.getWindow(ui).eval(String.format("foo(%s)", id));
}
Invoking Javascript code from an Applet
Java to Javascript communication (Official Oracle docs)
To compile the code using netscape.javascript.* package you need the $JAVA_HOME/jre/lib/plugin.jar. See here
In order to call JavaScript, Java code uses the
netscape.javascript.JSObject and netscape.javascript.JSException
classes. Since the release of Java 2, Standard Edition version 1.4,
these classes are provided in the jar file jre/lib/plugin.jar within
either the Java Development Kit or Java Runtime Environment. If you
reference these JavaScript classes, you will need to add plugin.jar to
your compilation classpath. This can be done through your Java IDE, if
you use one, or by passing the -classpath command-line argument to the
Java compiler javac.
At run-time, the Java Plug-In automatically makes these classes
available to applets, so no changes to the applet or how it is set up
are necessary.

Categories

Resources