Skip to Main Content Skip to Search
Product Documentation

Magic Square Example: Java Developer Tasks

Java Developer

RoleKnowledge BaseResponsibilities

Java developer
  • Little to no MATLAB experience

  • Moderate IT Experience

  • Java expert

  • Minimal access to IT systems

  • Integrates deployed component with the rest of the Java application

  • Integrates deployed MATLAB Figures with the rest of the Java application

The following tasks are usually performed by the Java developer.

Key Tasks for the Java Developer

TaskReference
Ensure you have the needed files from the MATLAB Programmer before proceeding.Gathering Files Needed for Deployment
Test the Java code by using it in a Java application. Compile and run the component to ensure it produces the same results as your MATLAB code.Testing the Java Component in a Java Application
Install the MATLAB Component Runtime (MCR) and update system paths.Installing the MATLAB Compiler Runtime (MCR)
Import classes generated by the MATLAB Builder JA product into existing Java applications.Integrating Java Classes Generated by MATLAB into a Java Application
Use built-in Java class methods to enhance your Java application.Calling Class Methods from Java
Address potential data conversion issues with differing data types.Handle Data Conversion as Needed
Verify your Java application works as expected in your end user's deployment environment.Build and Test

Gathering Files Needed for Deployment

Before beginning, verify you have access to the following files, created by the MATLAB Programmer in Copy the Package You Created (Optional). The following files are required to deploy to users who do not have a copy of MATLAB installed:

You will also want to communicate the location of com.mathworks.toolbox.javabuilder (matlabroot\toolbox\javabuilder\jar\javabuilder.jar). You can browse the API Javadoc for com.mathworks.toolbox.javabuilder from the MATLAB Help.

Testing the Java Component in a Java Application

Before deploying the created component, you need to verify that it can be used in a Java application successfully.

First, create a small Java program that uses the component created for your by the MATLAB Programmer (see Packaging the Magic Square Java Component (Optional)). The example provides a sample Java program that accomplishes this (getmagic.java now in the folder D:\javabuilder_examples\MagicSquareExample\MagicDemoJavaApp).

The program imports the magicsquare package you created with deploytool and the MATLAB Builder JA package (com.mathworks.toolbox.javabuilder) and uses one of the MATLAB Builder JA conversion classes to convert the number passed to the program on the command line into a type that can be accepted by MATLAB, in this case a scalar double value.

The program then creates an instance of class magic, and calls the makesqr method on that object. Note how the MATLAB file becomes a method of the Java class that encapsulates it. As explained in Testing the MATLAB File You Want to Deploy, the makesqr method computes the square using the MATLAB magic function. The source code of getmagic.java follows, for your reference:

/* getmagic.java
 * This file is used as an example for the MATLAB
 * Builder JA product.
 *
 * Copyright 2010 The MathWorks, Inc.
 */

/* Necessary package imports */
import com.mathworks.toolbox.javabuilder.*;
import magicsquare.*;

/*
 * getmagic class computes a magic square of order N. The
 * positive integer N is passed on the command line.
 */
class getmagic
{
   public static void main(String[] args)
   {
      MWNumericArray n = null;   /* Stores input value */
      Object[] result = null;    /* Stores the result */
      magic theMagic = null;     /* Stores magic */
                                 /* class instance */

      try
      {
         /* If no input, exit */
         if (args.length == 0)
         {
            System.out.println("Error: must input a positive 
                integer");
            return;
         }

         /* Convert and print input value*/
         n = new MWNumericArray(Double.valueOf(args[0]),
                                      MWClassID.DOUBLE);

         System.out.println("Magic square of order " + 
                                         n.toString());

         /* Create new magic object */
         theMagic = new magic();

         /* Compute magic square and print result */
         result = theMagic.makesqr(1, n);
         System.out.println(result[0]);
      }
      catch (Exception e)
      {
         System.out.println("Exception: " + e.toString());
      }

      finally
      {
         /* Free native resources */
         MWArray.disposeArray(n);
         MWArray.disposeArray(result);
         if (theMagic != null)
            theMagic.dispose();
      }
   }
}

Ensure your current working folder is set to D:\javabuilder_examples\MagicSquareExample as noted previously in this example. Then, do the following:

Inspect the syntax of the javac compile command on Windows platforms:

%JAVA_HOME%\bin\javac -classpath
      matlabroot\toolbox\javabuilder
                                      \jar\javabuilder.jar;
           .\magicsquare\distrib\magicsquare.jar 
           .\MagicDemoJavaApp\getmagic.java

The components of this command are:

  1. When you run getmagic, you pass an input argument to Java representing the dimension for the magic square. In this example, the value for the dimension is 5. Run getmagic by entering one of the following java commands at the command prompt. When entering these commands, ensure they are entered as one continuous command. On Windows systems, the semicolon (;) is a concatenation character. On UNIX systems, the colon (:) is a concatenation character.

    • On Windows platforms:

      %JAVA_HOME%\bin\java
       -classpath 
      .\MagicDemoJavaApp;matlabroot\toolbox\javabuilder\jar\javabuilder.jar; .\magicsquare\distrib\magicsquare.jar
      getmagic 5
    • On UNIX platforms:

      $JAVA_HOME/bin/java
       -classpath 
      ./MagicDemoJavaApp:matlabroot/toolbox/javabuilder/jar/javabuilder.jar: ./magicsquare/distrib/magicsquare.jar
      getmagic 5

    Inspect the syntax of the java command on Windows platforms:

    %JAVA_HOME%\bin\java
     -classpath 
    .\MagicDemoJavaApp;matlabroot\toolbox\javabuilder\jar\javabuilder.jar; .\magicsquare\distrib\magicsquare.jar
    getmagic 5

      Note   If you are running on the Mac 64-bit platform, you must add the -d64 flag in the Java command. See Limitations and Restrictions for more specific information.

    The components of this command are:

    • %JAVA_HOME%\bin\java — Using this command invokes the java run time explicitly from the MATLAB JRE.

    • -classpath — Using this argument allows Java to access the packages and other files you need to run your application.

    • .\MagicDemoJavaApp; — The location of getmagic.class. The semicolon concatenates this file location with the following file location, so Java can find the files needed to run your program.

    • matlabroot\toolbox\javabuilder\jar\javabuilder.jar; — The location of the MATLAB Builder JA package file (com.mathworks.toolbox.javabuilder). The semicolon concatenates this file location with the following file location, so Java can find the files needed to run your program.

    • .\magicsquare\distrib\magicsquare.jar — The location of the magicsquare package file you created with deploytool.

    • getmagic 5 — Invokes the compiled getmagic application with the command-line argument 5.

  2. Verify the program output. If the program ran successfully, a magic square of order 5 will print, matching the output of the MATLAB function you ran in Testing the MATLAB File You Want to Deploy, as follows:

    Magic square of order 5
    
    17 24  1  8 15
    23  5  7 14 16
     4  6 13 20 22
    10 12 19 21  3
    11 18 25  2  9

Using mcrroot to Test Against the MCR

To test directly against the MCR, substitute mcrroot for matlabroot, where mcrroot is the location where the MCR is installed on your system. An example of an MCR root location is D:\Applications\MATLAB\MATLAB_Compiler_Runtime\MCR_version_number. Remember to double-quote all parts of the java command path arguments that contain spaces.

Installing the MATLAB Compiler Runtime (MCR)

On target computers without MATLAB, install the MCR, if it is not already present on the deployment machine.

MATLAB Compiler Runtime (MCR) and the MCR Installer

The MATLAB Compiler Runtime (MCR) is an execution engine made up of the same shared libraries MATLAB uses to enable the execution of MATLAB files on systems without an installed version of MATLAB.

In order to deploy a component, you package the MCR along with it. Before you utilize the MCR on a system without MATLAB, run the MCR Installer.

The installer does the following:

  1. Installs the MCR (if not already installed on the target machine)

  2. Installs the component assembly in the folder from which the installer is run

  3. Copies the MWArray assembly to the Global Assembly Cache (GAC), as part of installing the MCR

MCR Prerequisites

  1. Since installing the MCR requires write access to the system registry, ensure you have administrator privileges to run the MCR Installer.

  2. The version of the MCR that runs your application on the target computer must be compatible with the version of MATLAB Compiler that built the component.

  3. Avoid installing the MCR in MATLAB installation directories.

Adding the MCR Installer To Your Deployment Package

Include the MCR in your deployment by using the Deployment Tool.

On the Package tab of the deploytool interface, click Add MCR.

Testing with the MCR

When you test with the MCR, keep in mind that the MCR is an instance of MATLAB. Given this, it is not possible to load the MCR into MATLAB.

For example, if you build a generic COM component with the Deployment Tool from MATLAB Builder NE, you generate a DLL.

If you then try to test the component with an application such as actxserver, which loads its process into MATLAB, you are effectively loading the MCR into MATLAB, producing an error such as this:

mwsamp.mymagic(3,[],[]) 
??? Invoke Error, Dispatch Exception: 
Source: tmw1.Class1.1_0 
Description: MCR instance is not available 

Therefore, understand the behaviors of third-party processes before attempting to test them with the MCR.

If you are uncertain about the behavior of these processes, contact your developer or systems administrator.

MCR Installation and Setting System Paths

To install the MCR, perform the following tasks on the target machines:

  1. If you added the MCR during packaging, open the package to locate the installer. Otherwise, run the command mcrinstaller to display the locations where you can download the installer.

  2. If you are running on a platform other than Windows, set the system paths on the target machine. Setting the paths enables your application to find the MCR.

    Windows paths are set automatically. On Linux and Mac, you can use the run script to set paths. See Using Run Script to Set MCR Paths in the appendix Using MATLAB Compiler on UNIX in the MATLAB Compiler User's Guide for more information.

Integrating Java Classes Generated by MATLAB into a Java Application

If you are implementing your Java component on a computer other than the one on which it was built:

  1. Install the MATLAB Compiler Runtime on the target system. See Deployment Process in the MATLAB Compiler documentation.

  2. Consult the Javadoc for information on classes generated by MATLAB classes.  Reference the Javadoc from the MATLAB Builder JA Product Roadmap.

  3. To integrate the Java class generated by MATLAB Builder JA,software both the component and the MWArray API need to be imported in the Java code. Import the MATLAB libraries and the component classes into your code with the Java import function. For example:

    import com.mathworks.toolbox.javabuilder.*;
    import componentname.classname; or import componentname.*;

    For more information, see Programming.

  4. As with all Java classes, you must use the new function to create an instance of a class. To create an object (theMagic) from the magic class, the example application uses the following code:

    theMagic = new magic();
    

    For more information, see Programming.

  5. To conserve system resources and optimize performance, it is good practice to get in the habit of destroying any instances of classes that are no longer needed. For example, to dispose of the object theMagic, use the following code:

    theMagic.dispose();
    /* Make it eligible for garbage collection */
    theMagic = null;

    For more information, see Programming, in particular, Using the dispose Method.

Calling Class Methods from Java

After you have instantiated the class, you can call a class method as you would with any Java object. In the Magic Square example, the makesqr method is called as shown:

result = theMagic.makesqr(1, n);

Here n is an instance of an MWArray class. Note that the first argument expresses number of outputs (1) and succeeding arguments represent inputs (n).

See the following code fragment for the declaration of n:

n = new MWNumericArray(Double.valueOf(args[0], 
                                 MWClassID.DOUBLE);

Handle Data Conversion as Needed

When you invoke a method on a builder component, the input parameters received by the method must be in the MATLAB internal array format. You can either (manually) convert them yourself within the calling program, or pass the parameters as Java data types.

How MATLAB Builder JA Handles Data

To enable Java applications to exchange data with MATLAB methods they invoke, the builder provides an API, which is implemented as the com.mathworks.toolbox.javabuilder.MWArray package. This package provides a set of data conversion classes derived from the abstract class, MWArray. Each class represents a MATLAB data type.

For more detailed information on data handling within the product and programming with the MWArray package, see the com.mathworks.toolbox.javabuilder.MWArray Javadoc and About the MATLAB Builder JA API.

Build and Test

Build and test the Java application as you would any application in your end user's environment. Build on what you've created by working with additional classes and methods.

After you create and distribute the initial application, you will want to continue to enhance it. Details about some of the more common tasks you will perform as you develop your application are listed in the chapters described in Next Steps.

Running a 64-Bit Mac Application

Before you run a 64-bit Macintosh application, you need to use the Macintosh Application Launcher. See Running Your 64-Bit Mac Application in the MATLAB Compiler User's Guide for more information.

See Using MATLAB Compiler on UNIX in the MATLAB Compiler User's Guide for complete information about building, deploying, and testing UNIX applications with MATLAB Compiler.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS