Java package: Difference between revisions

From Octave
Jump to navigation Jump to search
No edit summary
m (Remove redundant Category:Packages.)
 
(11 intermediate revisions by 6 users not shown)
Line 1: Line 1:
Octave is an easy to use but powerful environment for mathematical calculations, which can easily be extended by packages. Its features are close to the commercial tool MATLAB so that it can often be used as a replacement. Java on the other hand offers a rich, object oriented and platform independent environment for many applications. The core Java classes can be easily extended by many freely available libraries. This document refers to the package <code>java</code>, which is part of the GNU Octave project. This package allows you to access Java classes from inside Octave. Thus it is possible to use existing class files or complete Java libraries directly from Octave.
Java offers a rich, object oriented, and platform independent environment for many applications. The core Java classes can be easily extended by many freely available libraries. GNU Octave has a java interface that allows access to Java classes from inside Octave. Thus it is possible to use existing class files or complete Java libraries directly from Octave.


This description is based on the Octave package {{Codeline|java-1.2.8}}. The {{Forge|java}} package usually installs its script files (.m) in the directory {{Path|.../share/Octave/packages/java-1.2.8}} and its binary (.oct) files in {{Path|.../libexec/Octave/packages/java-1.2.8}}. You can get help on specific functions in Octave by executing the help command
= Octave 3.8 or later =
with the name of a function from this package:
octave> help javaObject


You can view the whole doc file in Octave by executing the info command with just the word java:
{{Warning|Do not install the java package in Octave version 3.8.0 or later.}}
octave> doc java


Note on calling Octave from Java: the java package is designed for calling Java from Octave. If you want to call Octave from Java, you might want to use a library like [http://kenai.com/projects/javaOctave javaOctave] or [http://jopas.sourceforge.net joPas].  
GNU Octave 3.8.0 incorporated the Octave Forge java package so the package is no longer necessary. If the package is installed, it will shadow the core functions making the java interface unreliable.


=FAQ=
However, even for these versions, Octave needs to have been built with java support. Check it like so:
==How to distinguish between Octave and Matlab?==
Octave and Matlab are very similar, but handle Java slightly differently. Therefore it may be necessary to [[Compatibility#Are_we_running_octave.3F|detect the environment]] and use the appropriate functions.


==How to make Java classes available to Octave?==
  >> (str2num(strtok(version(), '.')) > 4 && __octave_config_info__("JAVA")) || octave_config_info ("features").JAVA
Java finds classes by searching a {{Codeline|classpath}}. This is a list of Java archive files and/or directories containing class files. In Octave and Matlab the {{Codeline|classpath}} is composed of two parts:
  ans =  1
*the static {{Codeline|classpath}} is initialized once at startup of the JVM, and;
*the dynamic {{Codeline|classpath}} which can be modified at runtime.


Octave searches the static {{Codeline|classpath}} first, then the dynamic {{Codeline|classpath}}. Classes appearing in the static as well as in the dynamic {{Codeline|classpath}} will therefore be found in the static {{Codeline|classpath}} and loaded from this location.
If your installation of Octave does not have java support, it needs to be rebuilt from source. See the pages specific to your Operating System for further details.


Classes which shall be used regularly or must be available to all users should be added to the static {{Codeline|classpath}}. The static {{Codeline|classpath}} is populated once from the contents of a plain text file named {{Path|classpath.txt}} when the Java Virtual Machine starts. This file contains one line for each individual {{Codeline|classpath}} to be added to the static {{Codeline|classpath}}. These lines can identify single class files, directories containing class files or Java archives with complete class file hierarchies. Comment lines starting with a {{Codeline|#}} or a {{Codeline|%}} character are ignored.
== Documentation ==


The search rules for the file {{Path|classpath.txt}} are:
See the [http://www.gnu.org/software/octave/doc/interpreter/Java-Interface.html Java Interface] section of the Octave manual.
*First, Octave searches for the file {{Path|classpath.txt}} in your home directory, If such a file is found, it is read and defines the initial static {{Codeline|classpath}}. Thus it is possible to build an initial static {{Codeline|classpath}} on a "per user" basis.
*Next, Octave looks for another file {{Path|classpath.txt}} in the package installation directory. This is where {{Path|javaclasspath.m}} resides, usually something like
:<pre>...\share\Octave\packages\java-1.2.8.</pre>
:you can find this directory by executing the command {{Codeline|pkg list}}. If this file exists, its contents is also appended to the static {{Codeline|classpath}}. Note that the archives and class directories defined in this file will affect all users.


Classes which are used only by a specific script should be placed in the dynamic {{Codeline|classpath}}. This portion of the {{Codeline|classpath}} can be modified at runtime using the {{Codeline|javaaddpath}} and {{Codeline|javarmpath}} functions. Example:
= Legacy versions -- Octave 3.6 and older =
octave> base_path = "C:/Octave/java_files";
octave> % add two JARchives to the dynamic classpath
octave> javaaddpath ([base_path, "/someclasses.jar"]);
octave> javaaddpath ([base_path, "/moreclasses.jar"]);
octave> % check the dynamic classpath
octave> p = javaclasspath;
octave> disp (p{1});
  C:/Octave/java_files/someclasses.jar
octave> disp (p{2});
  C:/Octave/java_files/moreclasses.jar
octave> % remove the first element from the classpath
octave> javarmpath ([base_path, "/someclasses.jar"]);
octave> p = javaclasspath;
octave> disp (p{1});
  C:/Octave/java_files/moreclasses.jar
octave> % provoke an error
octave> disp (p{2});
  error: A(I): Index exceeds matrix dimension.


Another way to add files to the dynamic {{Codeline|classpath}} exclusively for your user account is to use the file {{Path|.octaverc}} which is stored in your home directory. All Octave commands in this file are executed each time you start a new instance of Octave. The following example adds the directory {{Path|~/octave}} to Octave’s search path and the archive {{Path|myclasses.jar}} in this directory to the Java search path.
Older versions of Octave did not have a native java interface.  Instead, the Octave Forge java package was required.  This needed to be installed separately via {{Codeline|pkg}}.  To install, download the [http://octave.sourceforge.net/java/index.html java package] and install it with {{Codeline|pkg install path-to-java.tar.gz}}


{{File|octaverc|<pre>
addpath ("~/octave");
javaaddpath ("~/octave/myclasses.jar");</pre>}}


== How to create an instance of a Java class? ==
[[Category:Octave Forge]]
If your code shall work under Octave as well as Matlab you should use the function {{Codeline|javaObject}} to create Java objects. The function {{Codeline|java_new}} is Octave specific and does not exist in the Matlab environment. Using [[Compatibility#Are_we_running_octave.3F|{{Codeline|is_octave()}}]] to distinguish between environments
 
if (is_octave)
  Passenger = java_new ('package.FirstClass', row, seat);    % works only in Octave
else
  Passenger = javaObject ('package.FirstClass', row, seat);  % actually works in both Octave and matlab
end
 
==How can I handle memory limitations?==
In order to execute Java code Octave creates a Java Virtual Machine (JVM). Such a JVM allocates a fixed amount of initial memory and may expand this pool up to a fixed maximum memory limit. The default values depend on the Java version (see {{Codeline|help javamem}}). The memory pool is shared by all Java objects running in the JVM. This strict memory limit is intended mainly to avoid that runaway applications inside web browsers or in enterprise servers can consume all memory and crash the system. When the maximum memory limit is hit, Java code will throw exceptions so that applications will fail or behave unexpectedly.
 
In Octave as well as in Matlab, you can specify options for the creation of the JVM inside a file named {{Path|java.opts}}. This is a text file where you can enter lines containing {{Codeline|-X}} and {{Codeline|-D}} options handed to the JVM during initialization.
 
In Octave, the Java options file must be located in the directory where {{Path|javaclasspath.m}} resides, i.e. the package installation directory, usually something like {{Path|...\share\Octave\packages\java-1.2.8}}. You can find this directory by executing {{Codeline|pkg list}}.
 
In Matlab, the options file goes into the {{Path|MATLABROOT/bin/ARCH}} directory or in your personal Matlab startup directory (can be determined by a {{Codeline|pwd}} command). MATLABROOT is the Matlab root directory and ARCH is your system architecture, which you find by issuing the commands {{Codeline|matlabroot}} respectively {{Codeline|computer('arch')}}.
 
The {{Codeline|-X}} options allow you to increase the maximum amount of memory available to the JVM to 256 Megabytes by adding the following line to the {{java.opts}} file:{{File|java.opts|<pre>-Xmx256m</pre>}}
 
The maximum possible amount of memory depends on your system. On a Windows system with 2 Gigabytes main memory you should be able to set this maximum to about 1 Gigabyte.
 
If your application requires a large amount of memory from the beginning, you can also specify the initial amount of memory allocated to the JVM. Adding the following line to the {{Path|java.opts}} file starts the JVM with 64 Megabytes of initial memory:{{File|java.opts|<pre>-Xms64m</pre>}}
 
For more details on the available {{Codeline|-X}} options of your Java Virtual Machine issue the command {{Codeline|java -X}} at the operating system command prompt and consult the Java documentation.
 
The {{Codeline|-D}} options can be used to define system properties which can then be used by Java
classes inside Octave. System properties can be retrieved by using the {{Codeline|getProperty()}}
methods of the {{Codeline|java.lang.System}} class. The following example line defines the property
{{Codeline|MyProperty}} and assigns it the string {{Codeline|12.34}}.
-DMyProperty=12.34
The value of this property can then be retrieved as a string by a Java object or in Octave:
octave> javaMethod("java.lang.System", "getProperty", "MyProperty");
  ans = 12.34
 
==How to install the java package in Octave?==
===Uninstall the currently installed package java===
Check whether the java package is already installed by issuing the {{Codeline|pkg list}} command:
octave> pkg list
  Package Name | Version | Installation directory
--------------+---------+-----------------------
        java *|  1.2.8 | /home/octavio/octave/java-1.2.8
 
If the java package appears in the list you must uninstall it first by issuing the command
octave> pkg uninstall java
octave> pkg list
 
Now the java package should not be listed anymore. If you have used the java package during the current session of Octave, you have to exit and restart Octave before you can uninstall the package. This is because the system keeps certain libraries in memory after they have been loaded once.
 
===Make sure that the build environment is configured properly===
The installation process requires that the environment variable {{Codeline|JAVA_HOME}} points to the Java Development Kit (JDK) on your computer.
*A JDK is only needed when '''installing''' the Java package. For just running Octave with Java, a JRE (Java Runtime Environment) will suffice.
*Note that JDK is not equal to JRE. The JDK home directory contains subdirectories with include, library and executable files which are required to compile the java package. These files are not part of the JRE, so you definitely need the JDK.
*Do not use backslashes but ordinary slashes in the path. Set the environment variable {{Codeline|JAVA_HOME}} according to your local JDK installation. Please adapt the path in the following examples according to the JDK installation on your system. If you are using a Windows system that might be:
:<pre>octave> setenv ("JAVA_HOME", "C:/Program Files/Java/jdk1.6.0_33");</pre>
:On Linux systems the location of the Java JDK varies from distro to distro. The command to set JAVA_HOME could look like:
:<pre>octave> setenv ("JAVA_HOME", "/usr/local/jdk1.6.0_33");</pre>
:or maybe something like (on e.g., Mageia, Fedora and Ubuntu):
:<pre>octave> setenv ("JAVA_HOME", "/usr/lib/jvm/java-1.7.0-openjdk.i386");</pre>
:If you are on Linux and can't find out what JAVA_HOME should look like, the following trick may help.
:Start a shell and issue the command:
: which javac
:Usually this gives you a symlink, indicated by a "->", e.g.,
: lrwxrwxrwx 1 root root 21 Apr 28 21:00 /usr/bin/javac -> /etc/alternatives/javac*
:Now just follow the targets (to the right of the "->") until you arrive at the real file:
: ls -l /etc/alternatives/javac
: lrwxrwxrwx 1 root root 44 Jul 17 23:41 /etc/alternatives/javac -> /usr/lib/jvm/java-1.7.0-openjdk.i386/bin/jar*
: ls -l /usr/lib/jvm/java-1.7.0-openjdk.i386/bin/jar*
: -rwxr-xr-x 1 root root 3832 Jun 23 03:11 /usr/lib/jvm/java-1.7.0-openjdk.i386/bin/javac*
:(The "real file doesn't have "l" file attribute and is probably only writable by root.)
:Once you get there, JAVA_HOME should be set to the full path of the executable excluding the "/bin/javac" part (i.e., "/usr/lib/jvm/java-1.7.0-openjdk.i386").
:Note, that on all systems you must use the forward slash {{Codeline|/}} as the separator, not the backslash {{Codeline|\}}. If on a Windows system the environment variable {{Codeline|JAVA_HOME}} is already defined using the backslash, you can easily change this by issuing the following Octave command before starting the installation:
:<pre>octave> setenv ("JAVA_HOME", strrep (getenv ("JAVA_HOME"), '\', '/'))</pre>
*The Java executables (especially the Java compiler, javac or javac.exe, and the Java archiver, jar or jar.exe) should be in the PATH. On Linux they're often symlinked to from /usr/bin (see above) but on Windows that is usually not the case. To that end, during installation of the Java package version 1.2.9+ a file "preinstall.m" is run; preinstall.m takes care of required settings, provided the JAVA_HOME environment variable has been set properly.
:If you insist on manually adding the Java executables path to the Windows PATH, do as follows:
:Check if by any chance the executables are in the PATH by issuing the Octave command:
:<pre>octave> system ('javac -version 2> nul')</pre>
:If this returns zero you're OK. If it doesn't return zero (i.e., the command "javac -version" doesn't return normally), the command:
:<pre>octave> setenv ("PATH", [ getenv("JAVA_HOME"), filesep, "bin", pathsep, getenv("PATH") ])</pre>
:should do the trick (watch out that 'getenv("JAVA_HOME")' and 'getenv("PATH")' contain no spaces). Better don't fiddle with the Windows PATH through the Control Panel etc. The above procedure (the same that preinstall.m invokes) only adapts the PATH for the current Octave session and ensures that the Java executables you need are first in the PATH, before any others on your system. Again: provided you've setup JAVA_HOME correctly.
 
===Compile and install the package in Octave===
[[Octave-Forge#Installing_packages|Install the package]] from octave-forge.
 
Note:
On Windows (MinGW) systems the Java package can be (slightly) miscompiled; until now errors have only been reported when using Java Swing stuff. To fix this, the following compiler flags have to be added:
 
-Wl,--kill,-at    to the $(MKOCTFILE) in the Makefile
 
see:
[http://sourceforge.net/mailarchive/forum.php?thread_name=CAB-99LuCbL3u0LmZuAmneRb_0G8pjmyha9viFpncMnjC%3DeBxJA%40mail.gmail.com&forum_name=octave-dev]
(scroll down a bit for the relevant postings)
 
 
On Linux 64-bit systems, the libjvm.so library is installed only in <JAVA_HOME>/jre/lib/<ARCH>/server/ because the <JAVA_HOME>/jre/lib/<ARCH>/client/ folder is not available. This will lead to runtime execution errors because the library is not found.
 
There are two solutions:
* install the java package as is and create a symlink named ''server'' in <JAVA_HOME>/jre/lib/<ARCH>/ pointing to the ''client'' folder;
* patch the java package as indicated in [http://savannah.gnu.org/bugs/?39065 libjvm detection on 64 bit systems for java package] and then install it, no further modifications are needed
 
===Test the java package installation===
The following code creates a Java string object, which however is automatically converted
to an Octave string:
octave> s = javaObject ("java.lang.String", "Hello OctaveString")
  s = Hello OctaveString
 
Note that the java package automatically transforms the Java String object to an Octave
string. This means that you cannot apply Java String methods to the result.
 
This "auto boxing" scheme seems to be implemented for the following Java classes:
*{{Codeline|java.lang.Integer}}
*{{Codeline|java.lang.Double}}
*{{Codeline|java.lang.Boolean}}
*{{Codeline|java.lang.String}}
 
If you instead create an object for which no "auto-boxing" is implemented, {{Codeline|javaObject}}
returns the genuine Java object:
octave> v = javaObject ("java.util.Vector")
  v =
    <Java object: java.util.Vector>
octave> v.add(12);
octave> v.get(0)
  ans = 12
 
If you have created such a Java object, you can apply all methods of the Java class to
the returned object. Note also that for some objects you must specify an initializer:
% not:
octave> d = javaObject ("java.lang.Double")
  error: [java] java.lang.NoSuchMethodException: java.lang.Double
% but:
octave> d = javaObject ("java.lang.Double", 12.34)
  d = 12.340
 
==Which TEX symbols are implemented in the dialog functions?==
The dialog functions contain a translation table for TEX like symbol codes. Thus messages
and labels can be tailored to show some common mathematical symbols or Greek characters.
No further TEX formatting codes are supported. The characters are translated to their
Unicode equivalent. However, not all characters may be displayable on your system. This
depends on the font used by the Java system on your computer.
 
Each TEX symbol code must be terminated by a space character to make it distinguishable from
the surrounding text. Therefore the string {{Codeline|\alpha &#61;12.0}} will produce the
desired result, whereas {{Codeline|\alpha&#61;12.0}} would produce the literal text {{Codeline|\alpha&#61;12.0}}.
 
[[Category:Octave-Forge]]

Latest revision as of 11:15, 10 June 2019

Java offers a rich, object oriented, and platform independent environment for many applications. The core Java classes can be easily extended by many freely available libraries. GNU Octave has a java interface that allows access to Java classes from inside Octave. Thus it is possible to use existing class files or complete Java libraries directly from Octave.

Octave 3.8 or later[edit]

Warning icon.svg
Do not install the java package in Octave version 3.8.0 or later.

GNU Octave 3.8.0 incorporated the Octave Forge java package so the package is no longer necessary. If the package is installed, it will shadow the core functions making the java interface unreliable.

However, even for these versions, Octave needs to have been built with java support. Check it like so:

 >> (str2num(strtok(version(), '.')) > 4 && __octave_config_info__("JAVA")) || octave_config_info ("features").JAVA
 ans =  1

If your installation of Octave does not have java support, it needs to be rebuilt from source. See the pages specific to your Operating System for further details.

Documentation[edit]

See the Java Interface section of the Octave manual.

Legacy versions -- Octave 3.6 and older[edit]

Older versions of Octave did not have a native java interface. Instead, the Octave Forge java package was required. This needed to be installed separately via pkg. To install, download the java package and install it with pkg install path-to-java.tar.gz