Call a java function from matlab script - java

I'm trying to call a java function from a Matlab script, I tried all the solutions put in the website but I didn't get an issue.
My class is simple:
package testMatlabInterface;
public class TestFunction
{
private double value;
public TestFunction()
{
value=0;
}
public double Add(double v)
{
value += v;
return value;
}
public static void main(String args[])
{
}
}
So I put .java file (also .class) in my workingspace C:\scriptsMatlab and I added this path to javaclasspath of Matlab, but when I try to call the function , it tells me that there's no class with this name in javaclasspath of Matlab.
EDIT:
Here's the version of java that Matlab uses:
Java 1.6.0_17-b04 with Sun Microsystems Inc. Java HotSpot(TM) Client VM mixed mode
And this is the version on jdk which I used to compile my class :
But when I try to execute this commande from matlab
>> javaaddpath 'C:\scriptsMatlab'
>> obj = TestFunction
it tells me:
Undefined function or variable 'TestFunction'.

Option 1
Check if same JRE/JDK is being used to compile your JAVA file. Execute on Matlab:
version -java
Compie your MyFunction.java with same jdk as above , and locate your MyFunction.class
Locate your Matlab classpath.txt. Type following into matlab cmd.
which classpath.txt
Open your classpath.txt as administrator.Add the full path for the directory with the MyFunction.class to the end of the 'classpath.txt' file as a single line and save the file.
Restart Matlab.
To run in Matlab . Create object of MyFunction.
obj = MyFunction
To run main() method in matlab.
javaMethod('main', obj, '')
Option 2
Follow Steps 1-2.
Execute following command in Matlab
JAVAADDPATH PATH/to/Directoryof MyFunction.class.
No need to restart Matlab here.
Just run using
obj = MyFunction;
javaMethod('main', obj);
From MathWorks :
javaMethod(MethodName,JavaObj,x1,...,xN) calls the method in the class of the Java® object array with the signature matching the arguments x1,...,xN.
javaMethod(StaticMethodName,ClassName,x1,...,xN) calls the static method in class ClassName.

Related

How to run a java jar file and get store the output in shell script variables

I have a java class, which has 3 methods and each method returns a String. I exported the .jar file out of that Java project. When I run the jar file from git bast using the command ./script1.sh, I get the output in the command window. My question is, how can I assign those values to the three variable that are in the script1.sh file. If I type echo ${"Source_branch"}, i should get output as "XXX_Source_Branch".
Here is my Java code :
package com.main;
public class Engine {
public static void main(String[] args) {
try {
getSourceBranch();
getDestinationBranch();
getDestEnv();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getSourceBranch() {
return "XXX_Source_Branch";
}
public static String getDestinationBranch() {
return "XXX_Dest_Branch";
}
public static String getDestEnv() {
return "XXX_Dest_Env";
}
}
The name of the jar file is Engine.jar.
And my script file is
runjar.sh
java -jar Engine.jar
Source_branch
Destination_brnach
Destination_env
pass data from java to bash
If you want to save data from java to the overlaying String, you will need to print that to System.out and read them from the shell.
Java code:
System.out.println("your source branch")
System.out.println("your destination branch")
Shell code
out="$(java -jar Engine.jar)"
sBranch="$(echo "$out"|sed -n '1p' /dev/stdin)"
destBranch="$(echo "$out"|sed -n '2p' /dev/stdin)"
pass data from bash to java
If you hard-code the Strings, java will just use the Strings. If you want to change that, you will need to modify your java code.
option 1 - arguments
If you want to pass the strings in the script using java -jar Engine.jar Source_branch Destination_brnach Destination_env, you can use them in your main method with the args parameter.
For example, you can print the first String in your main method using
System.out.println(args[0]);
If you do that, please test if args.length is greater than the highest argument you are accessing.
option 2 - System properties
If you want to get parameters without accessing args(independent of your main method), you will need to use System properties.
At first, change the script to be like that:
java -jar -DSource_branch=yourSourceBranch -DDestination_branch=yourDestinationBranch -DDestination_env=yourDestinationEnv
Engine.jar
Note that -D. That indicates that you are passing System properties. The syntax for this is -D<key>=<value> and it should be located between java and -jar.
Also, you will need to use System.getProperty() to access it from anywhere in your code.
For example:
public static String getSourceBranch() {
return System.getProperty("Source_Branch");
}
Create a .sh file with any file editor, like-
$> vi runJar.sh
Then, paste the below script ,
#!/bin/sh
java -jar Engine.jar
After saving the file, give execution permission -
$> chmod +x runJar.sh
Then run using
$> ./runJar.sh
Make sure the jar file and shell script file are in the same directory.

call dll objects in java application

i have a c# dll file which contains a specific class that i need to use in some java application.
this is how i use it in my c# program:
using Lemmatizer; // this comes from my dll
private void Test(string inputText) {
output = (new StemmingTools()).LemmatizeText(inputText, LevelOfLemmatizer.First, false);
// StemmingTools class placed in the dll
}
how can i use the LemmatizeText function in my java program ?
i already used the jna library but it fails with instantiate the StemmingTools object from the dll.

Classpath seems correct but JVM still could not find or load main class

I am relatively new to programming and java and am trying to learn how to create a user-defined package from the command-line. I get the following: Error: Could not find or load main class TestPhone. I've reviewed posts on this type of error including the well-commented post here. The post lists 4 steps that the JVM goes through to run a java program:
Search for the compiled version of the class.
Load the class.
Check that the class has a main method with signature static void main(String[]).
Call that method passing it the command line arguments as a String[].
Apparently, my JVM can't find my TestPhone.class for some reason I am yet to figure out. Here's my directory structure:
My classpath is set as follows:
My classes contain simple codes from Mala Gupta to test accessibility of class variables:
package mobile;
class Phone {
static boolean softKeyboard = true;
}
package mobile;
class TestPhone {
public static void main (String[] args) {
Phone.softKeyboard = false;
Phone p1 = new Phone();
Phone p2 = new Phone();
System.out.println(p1.softKeyboard);
System.out.println(p2.softKeyboard);
p1.softKeyboard = true;
System.out.println(p1.softKeyboard);
System.out.println(p2.softKeyboard);
}
}
Any idea why it doesn't find my classes? Many thanks.
System specs:
Java version 1.8.0
Javac 1.8.0
Win 7 on 32-bit OS
The java application launcher, java, expects the fully qualified name of the class, mobile.TestPhone. The ../mobile directory need not be in the classpath.
You are in the myJavaProject folder in cmd.
Try to go to c:\myJavaProject\mobile then it should work because your class is in mobile not in
myJavaProject folder

MATLAB java classes

I'm having difficulty using a java package in MATLAB
Firstly I add my .jar to the dynamic path:
filename = fullfile(pwd,'Compiled','SpectrometerInterface.jar');
ls(filename)
javaaddpath(filename);
The ls returns SpectrometerInterface.jar confirming the files existence, and javaclasspath confirms it is indeed added.
Then when I request an object, using either
obj = javaObject('com.jellymatter.spectrometerinterface.UDPSpectrometer');
or
obj = com.jellymatter.spectrometerinterface.UDPSpectrometer()
it says the class cannot be found. It is definitely in the correct directory within the .jar, and a reduced version of my class is as follows
package com.jellymatter.spectrometerinterface;
public class UDPSpectrometer {
private UDPInterface inter = null;
public UDPSpectrometer(){
/* Nothing here */
}
public void connect(String addr, int p1, int p2) throws CommunicationException{
...
}
public double[] get() throws CommunicationException, SpectrometerNotCalibratedException {
...
}
}
Any suggestions?
Edit: The Diagnosis
MATLAB's Java virtual machine was to low a version (JRE 1.5) for the compiled java (JDK 1.7).
Edit: Solutions
I solved it by compiling using JDK 1.5, but, also, one could upgrade the JVM in MATLAB.
Please take a look at this and set your classpath.txt

class file for javax.serverlet.GenericServlet not found

I have stuck in the class->header file for couple days!
I have tried on jni on Client by http://netbeans.org/kb/docs/cnd/beginning-jni-linux.html and http://ringlord.com/jni-howto.html. And it succeeded in return "hello JNI C++" from JNI's (.cpp)file. Here are my steps:
create native function and in client.java
clean &build this client.java on Netbeans IDE, then result a client.class file
javah –jni [package].[classname]
create a dynamic library C++ project as first reference does, and put client.h into source file, and put some hello code into (.cpp)file ---> It works!
However, I tried to do the same thing on the servlet side and it's not working
Servlet.java->Servlet.class : ok!
Servlet.class->Servlet.h: fail!!!!
Error : cannot access javax.servlet.GenericServlet
class file for javax.servlet.GenericServlet not found
The following are solutions I have found and tried so far,
check the package name
sudo gedit /etc/profile,sudo gedit .bashrc, sudo /etc/environment; add JAVA_HOME & CLASSPATH on them, and source them to update, then echo $JAVA_HOME, echo $CLASSPATH to verify
download servlet-api-6.0.14.jar & servlet-api-5.0.16.jar from http://www.jarfinder.com/index.php/java/info/javax.servlet.GenericServlet
,and add above two (.jar) by netbeans IDE->server->property->libraries->Add JAR
Please tell me how to figure it out this issue, thank you very much!!Btw, I am using hessianServlet
NativeWrapper.java (you run javah only on this class)
class NativeWrapper {
// either
static {
System.loadLibrary("MyOpenCVNative");
}
// or
public NativeWrapper() {
System.loadLibrary("MyOpenCVNative");
}
public native void callNative();
}
MyServlet.java
class MyServlet extends javax.servlet.GenericServlet {
private NativeWrapper nativeWrapper = new NativeWrapper();
public void someServletMethod() {
nativeWrapper.callNative();
}
}

Categories