Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB Builder JA   

Deploying a Component with the Magic Square Example

About This Example

In this section, you will step through an example of how a simple M-code function can be transformed into a deployable MATLAB Builder JA component.

The Magic Square example shows you how to create a Java component named magicsquare which contains the magic class, a .jar file, and other files needed to deploy your application.

The class wraps a MATLAB function, makesqr, which computes a magic square. A magic square is a matrix containing any number of rows. These rows, when added horizontally and vertically, equate to the same value. MATLAB contains a function, magic, that can create magic squares of any dimension. In this example, you will work with that function.

Before Running the Magic Square Example

Before running this example, run mbuild -setup and configure your environment. See Select Your C or C++ Compiler with mbuild -setup and Configuring Your Environment .

Magic Square Example: MATLAB Programmer Tasks

The following tasks are usually performed by the MATLAB programmer.

Key Tasks for the MATLAB Programmer

TaskReference
Start the product.Starting the Deployment Tool
Prepare to run the example by copying the MATLAB example files into a work folder.Copying the Example Files
Test the M-code to ensure it is suitable for deployment.Testing the M-File You Want to Deploy
Create a Java package (encapsulating your M-code in a Java class) by running the Build function in deploytool.Creating the Magic Square Java Component
Run the Packaging Tool to bundle your Java component with the additional files you selected.Packaging the Magic Square Java Component (Optional)
Copy the output from the Packaging Tool (the distrib folder).Copy the Package You Created (Optional)

The Magic Square example shows you how to create a Java component (magicsquare), which contains the magic class, a .jar file (which includes the .ctf archive described in How Does the MATLAB Builder JA Product Use JAR Files?), and other files needed to deploy your application. The class encapsulates a MATLAB function, makesqr, which computes a magic square.

The client Java application, getmagic.java converts the array returned by makesqr to a native array and displays it on the screen. When you run the getmagic application from the command line, you can pass the dimension for the magic square as a command-line argument.

Starting the Deployment Tool

The MATLAB Builder JA product is accessed through the Deployment Tool GUI (deploytool) or through the mcc function of the MATLAB Compiler product. deploytool is the GUI front end for mcc, the command that executes MATLAB Compiler software.

This tutorial will use deploytool. If you want to use mcc, see the mcc reference page for complete reference information.

To start this product:

  1. Start MATLAB.

  2. Type deploytool at the MATLAB command prompt. The deploytool GUI opens.

  3. Verify that MATLAB is reading the correct value of JAVA_HOME.

    1. At the MATLAB command prompt, type getenv JAVA_HOME.

    2. The response from MATLAB should be the path name you set to JAVA_HOME in Configuring Your Environment. If not, ensure the JDK that MATLAB is pointing to will be compatible to run this example (at least Java Version 1.5). Consult your system administrator if you are unsure.

Copying the Example Files

Prepare to run the example by copying needed files into your work area as follows:

  1. Navigate to matlabroot\toolbox\javabuilder\Examples\MagicSquareExample. matlabroot is the MATLAB root folder (where MATLAB is installed). To find the value of this variable on your system, type matlabroot at a MATLAB command prompt.

  2. Copy the MagicSquareExample folder to a work area, for example, D:\javabuilder_examples. Avoid using spaces in your folder names, if possible.

  3. Rename the subfolder MagicSquareExample to magic_square. The example files should now reside in D:\javabuilder_examples\magic_square.

  4. Using a system command prompt, navigate to D:\javabuilder_ examples\magic_square by switching to the D: drive and entering cd \javabuilder_examples\magic_square.

Testing the M-File You Want to Deploy

Normally you would first create the M-file you want to deploy. In this example, you will test a precreated M-file (makesqr.m) containing the predefined MATLAB function magic.

  1. Using MATLAB, locate the makesqr.m file at D:\javabuilder_examples\magic_square\MagicDemoComp. The contents of the file are as follows:

    function y = makesqr(x)
    %MAKESQR Magic square of size x.
    %   Y = MAKESQR(X) returns a magic square of size x.
    %   This file is used as an example for the MATLAB 
    %   Builder JA product.
    
    %   Copyright 2001-2008 The MathWorks, Inc.
    
    y = magic(x);
  2. In order to run makesqr, you must ensure that MATLAB can find it. Use the File > Set Path option in MATLAB to add the D:\javabuilder_examples\magic_square\MagicDemoComp folder to the MATLAB search path.

  3. At the MATLAB command prompt, enter makesqr(5) and view the results. The output should appear as follows:

    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

Creating the Magic Square Java Component

You create the Magic Square Java application by using the Deployment Tool GUI to build a Java class that wraps around the sample M-code discussed in Testing the M-File You Want to Deploy.

Use the following information as you work through this example using the instructions in Building the Java Component:

Project Namemagicsquare
Class Namemagic
File to compilemakesqr.m

What Happens in the Build Process.  

To create a component, the builder does the following:

  1. Generates Java code to implement your component. The files are as follows:

    myclass.javaContains a Java class with methods encapsulating the M-functions specified in the project for that class.
    mycomponentMCR.javaContains the CTF decryption keys and code to initialize the MCR for the component.

  2. Compiles the Java code produced in step 1.

  3. Generates /distrib and /src subfolders.

  4. Invokes the Jar utility to package the Java class files it has created into a Java archive file (mycomponent.jar).

Anatomy of a MATLAB Builder JA Project.   A builder project contains information about the files and settings needed by the MATLAB Builder JA product to create a deployable Java component. A project specifies information about classes and methods, including the MATLAB functions to be included.

Classes and Methods .  

The builder transforms MATLAB functions that are specified in the component's project to methods belonging to a Java class.

When creating a component, you must provide one or more class names as well as a component name. The class name denotes the name of the class that encapsulates MATLAB functions.

To access the features and operations provided by the MATLAB functions, instantiate the Java class generated by the builder, and then call the methods that encapsulate the MATLAB functions.

Naming Conventions.  

Typically you should specify names for components and classes that will be clear to programmers who use your components. For example, if you are encapsulating many MATLAB functions, it helps to determine a scheme of function categories and to create a separate class for each category. Also, the name of each class should be descriptive of what the class does.

Valid characters are any alpha or numeric characters, as well as the underscore (_) character.

Packaging the Magic Square Java Component (Optional)

Bundling the Java component with additional files into a JAR file that can be distributed to users is called packaging. You will perform this step using the packaging function of deploytool. Alternately, copy the contents of the distrib folder and the MCR Installer to a local folder of your choice. If you are creating a shared component and want to include additional code with the component, you must perform this step.

  1. On the Package tab, add the MATLAB Compiler Runtime (the MCR) by clicking Add MCR.

  2. Next, add others files useful for end users. The readme.txt file contains important information about others files useful for end users. To package additional files or folders, click Add file/directories, select the file or folder you want to package, and click Open.

  3. In the Deployment Tool, click the Packaging button ( ).

  4. After packaging, the package resides in the distrib subfolder. On Windows, the package is a self-extracting executable. On platforms other than Windows, it is a .zip file. Verify that the contents of the distrib folder contains the files you specified.

What Happens in the Packaging Process?.   The packaging process creates a self-extracting executable (on Windows platforms) or a .zip file (on platforms other than Windows). The package contains at least the following:

How Does the MATLAB Builder JA Product Use JAR Files?.  

As of R2007b, the MATLAB Builder JA product now embeds the CTF archive within the generated JAR file, by default. This offers convenient deployment of a single output file since all encrypted M-file data is now contained within this Java archive.

For information on how to produce a separate CTF archive and JAR file (the default behavior prior to R2007b), see Using MCR Component Cache and MWComponentOptions and learn how to use the MWCtfExtractLocation.EXTRACT_TO_COMPONENT_DIR value with the ExtractLocation option of MWComponentOptions.

Copy the Package You Created (Optional)

Copy the package that you created from the distrib folder to the local folder of your choice or send them directly to the Java programmer..

Magic Square Example: Java Programmer Tasks

The following tasks are usually performed by the Java programmer.

Key Tasks for the Java Programmer

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 M-code.Creating the Magic Square Java Component
Archive and distribute the output to end users.Distributing the Component to End Users
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:

See Packaging the Magic Square Java Component (Optional) for more information about these files. 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\magic_square\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 M-file becomes a method of the Java class that encapsulates it. As explained in Testing the M-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 2008 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\magic_square 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 system command prompt:

    • 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 Mac or Solaris 64-bit platforms, 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.java. 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 M-function you ran in Testing the M-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_Component_Runtime\MCR_version_number. Remember to double-quote all parts of the java command path arguments that contain spaces.

Distributing the Component to End Users

If you bundled the component as a self-extracting executable, paste it in a folder on the development machine, and run it. If you are using a .zip file bundled with WinZip, unzip and extract the contents to the development machine.

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.

  


Recommended Products

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

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