Example Guide
Example Guide
R2014a
Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com
comp.soft-sys.matlab
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
MATLAB Application Deployment Web Example Guide
COPYRIGHT 20082014 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern
the use, modification, reproduction, release, performance, display, and disclosure of the Program and
Documentation by the federal government (or other entity acquiring for or through the federal government)
and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the
governments needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
March 2008
October 2008
March 2009
September 2009
March 2010
September 2010
April 2011
September 2011
March 2012
September 2012
September 2013
March 2014
Online
Online
Online
Online
Online
Online
Online
Online
Online
Online
Online
Online
only
only
only
only
only
only
only
only
only
only
only
only
Contents
How to Use This Guide
1
The MATLAB Application Deployment Web Example
Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
.......................
1-4
1-5
1-5
1-6
1-7
2
Basics of Web Processing . . . . . . . . . . . . . . . . . . . . . . . . . . .
Web Processing Work Flow . . . . . . . . . . . . . . . . . . . . . . . . .
Integrating MATLAB Code on the Web Using Java
Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Optimizing Performance of Servlets That Call Your
MATLAB Web Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Maintaining Data Integrity Through Proper Scoping . . . .
The Oracle Web Site: Your Ultimate Java Resource . . . . .
2-6
2-9
2-15
2-16
2-16
2-18
2-19
2-20
2-21
2-2
2-2
2-3
Server Administrator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
End User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
End-To-End Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-21
2-22
2-22
3
Programming in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Programming Basics . . . . . . . . . . . . . . . . . . . . . .
Returning MATLAB Data Types . . . . . . . . . . . . . . . . . . . . .
3-2
3-3
3-3
3-6
vi
Contents
4-2
4-2
4-4
4-6
4-6
4-7
4-24
4-24
4-31
4-36
4-40
5
Working with the Front-End Layer . . . . . . . . . . . . . . . . . .
About the Front-End Layer . . . . . . . . . . . . . . . . . . . . . . . . .
About the Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5-2
5-2
5-5
5-7
5-11
5-15
5-20
5-28
6
Managing a Deployment Server Environment . . . . . . . .
The Server Administrators Role in Deployment . . . . . . . .
An Overview of Deployed Applications . . . . . . . . . . . . . . . .
Installing the MATLAB Compiler Runtime (MCR) . . . . . .
Loading the MATLAB Compiler Runtime (MCR) . . . . . . . .
Scaling Your Server Environment . . . . . . . . . . . . . . . . . . . .
Ensuring Fault Tolerance . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-2
6-2
6-3
6-3
6-6
6-8
6-10
Hot Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-12
6-12
6-12
6-13
vii
6-14
7
.............................
7-2
Example Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-3
8
..................
8-2
8-5
8-7
8-7
8-15
A
Other Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Builder JA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Builder NE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
viii
Contents
A-2
A-2
A-2
1
How to Use This Guide
The MATLAB Application Deployment Web Example Guide on page 1-2
Who Should Use This Guide? on page 1-4
Commonly Used Software and Preliminary Setup Information on page 1-5
MATLAB Compiler
http://www.mathworks.com/help/pdf_doc/compiler/index.html.
MATLAB Builder JA
http://www.mathworks.com/help/pdf_doc/javabuilder/index.html
MATLAB Builder NE
http://www.mathworks.com/help/pdf_doc/dotnetbuilder/index.html
Use the MATLAB Application Deployment Web Example Guide to:
Learn about the components of a Web deployment environment.
Review an architectural configuration of a typical Web deployment
implementation and how the components in the configuration work
together.
Reference specific models for performing the most common to the most
complex deployment tasks, such as:
1-2
1-3
1-4
MATLAB Programmer
MATLAB Programmer
Role
MATLAB
programmer
Knowledge Base
Responsibilities
MATLAB expert
No IT experience
No access to IT systems
MATLAB
Financial Toolbox
MATLAB Compiler
MATLAB Builder JA
1-5
MATLAB Builder NE
Note Many of the examples in this guide use the software listed here. It is
not likely you will use all of the software listed here.
Moderate IT Experience
Expert at business logic and
services tier
Java expert
.NET expert
Minimal access to IT systems
Expert at J2EE
Expert at .NET Web
frameworks
Expert at Web services
1-6
Front-end Web
developer
Knowledge Base
Responsibilities
No MATLAB experience
Minimal IT experience
Expert at usability and Web
page design
Minimal access to IT systems
Expert at JSP
Expert at ASPX
End User
End User
Role
Knowledge Base
Responsibilities
No MATLAB experience
1-7
1-8
2
Web 101: An Introduction
to Web Concepts and
Terminology
Basics of Web Processing on page 2-2
Lifecycle of a Deployed MATLAB Web Application on page 2-16
One common scenario is typing a URL into the address bar of your Web
browser. The browser adds a GET to the URL to create the full request.
2 The client sends the request over the wire using HTTP.
2-2
In the case of a Web browser, the verb is typically GET. The server retrieves,
or constructs, the requested HTML page.
8 The server sends a response to the client.
9 The client processes the response.
In the case of a Web browser, the client renders the returned HTML page.
2-3
MyServlet.java
import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.MWArray;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintStream;
2-4
import magicsquare.magic;
/**
* A simple servlet to call MATLAB code.
*/
public class MyServlet extends HttpServlet
{
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
try {
final magic m = new magic();
try {
final Object[] results = m.makesqr(1, (int)(Math.random()
* 7 + 3));
try {
final MWArray firstResult = (MWArray)results[0];
final double[][] square = (double[][])firstResult.toArray();
response.setContentType("text/html");
final PrintStream page =
new PrintStream(response.getOutputStream());
page.println("<html>");
page.println("<head>");
page.println(" <title>Magic Square Web App</title>");
page.println("</head>");
page.println("<body>");
page.println("A magic square of size " + square.length);
page.println("<table border='1' cellpadding='4'>");
for (double[] row : square) {
page.println("<tr>");
for (double column : row) {
page.println("<td>" + column + "</td>");
}
page.println("</tr>");
}
page.println("</table>");
page.println("</body>");
page.println("</html>");
2-5
} finally {
MWArray.disposeArray(results);
}
} finally {
m.dispose();
}
} catch (MWException e) {
throw new ServletException(e);
}
}
}
2-6
MyServlet.java.
public class MyServlet extends HttpServlet
{
private magic m;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
try {
m = new magic();
} catch (MWException e) {
throw new ServletException(e);
}
}
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
2-7
{
try {
final Object[] results = m.makesqr(1, (int)(Math.random() * 7 + 3));
try {
final MWArray firstResult = (MWArray)results[0];
final double[][] square = (double[][])firstResult.toArray();
response.setContentType("text/html");
final PrintStream page =
new PrintStream(response.getOutputStream());
page.println("<html>");
page.println("<head>");
page.println(" <title>Magic Square Web App</title>");
page.println("</head>");
page.println("<body>");
page.println("A magic square of size " + square.length);
page.println("<table border='1' cellpadding='4'>");
for (double[] row : square) {
page.println("<tr>");
for (double column : row) {
page.println("<td>" + column + "</td>");
}
page.println("</tr>");
}
page.println("</table>");
page.println("</body>");
page.println("</html>");
} finally {
MWArray.disposeArray(results);
}
} catch (MWException e) {
throw new ServletException(e);
}
}
@Override
public void destroy() {
m.dispose();
}
}
2-8
2-9
2-10
{
final double[][] square = (double[][])firstResult.toArray();
{
final PrintStream page =
new PrintStream(response.getOutputStream());
page.println("<html>");
page.println("<head>");
page.println("
<title>Magic Square Web App (Other)</title>");
page.println("</head>");
page.println("<body>");
page.println("A magic square of size " + square.length);
page.println("<table border='1' cellpadding='4'>");
{
for (double[] row : square) {
page.println("<tr>");
for (double column : row) {
page.println("<td>" + column + "</td>");
}
page.println("</tr>");
}
}
page.println("</table>");
page.println("</body>");
page.println("</html>");
}
}
} finally {
MWArray.disposeArray(results);
}
} catch (MWException e) {
throw new ServletException(e);
}
}
@Override
public void destroy() {
m.dispose();
}
}
2-11
2-12
2-13
2-14
}
}
MyServer.java.
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
final HttpSession session = request.getSession();
final magic m =
(magic)session.getAttribute
(MyHttpSessionListener.SHARED_MAGIC_INSTANCE);
2-15
Introduction
How does a single piece of MATLAB code become a deployable, portable,
robust, scalable Web application? Through skillful deployment by a number
of people in an organization, each playing distinct and significant roles.
The following diagrams depict the supported implementation and
architectures available when using MATLAB application deployment
products.
2-16
2-17
Load
balancer
Internet
External end user
via browser
(no MCR)
Firewall
Load
balancer
MCR
Firewall
Router
End-to-end
MATLAB programmer
2-18
MATLAB Programmer
MATLAB Programmer
Role
MATLAB
programmer
Knowledge Base
Responsibilities
MATLAB expert
No IT experience
No access to IT systems
The first phase in a deployed applications life begins when code is written
in MATLAB by a MATLAB programmer, whose objective is sharing it with
other people either within or outside of the organization. To accomplish this
objective, the programmer uses MATLAB Compiler. MATLAB Compiler
makes MATLAB code usable by people in vastly different environments who
may not have knowledge of MATLAB or the MATLAB language.
2-19
Middle-Tier Developer
Middle-Tier Developer
Little to no MATLAB
experience
Middle-tier
developer
Moderate IT Experience
Expert at business logic and
services tier
Java expert
.NET expert
Minimal access to IT systems
Expert at J2EE
Expert at .NET Web
frameworks
Expert at Web services
At this point in the deployment lifecycle, integration is usually required in
order to make the deployed application work with the existing applications in
the organization. The Business Services Developer installs these deployable
applications along with the proper version of the MCR, and converts MATLAB
data types to native language data types so they can be used without any
coupling to MATLAB in other tiers of the installation architecture. When the
Java or .NET component is called, it will instantiate the MCR to execute the
underlying MATLAB code. Once these services are exposed (either as Web
services or through an API) Front End Developers can connect to them and
use them.
2-20
Front-end Web
developer
Knowledge Base
Responsibilities
No MATLAB experience
Minimal IT experience
Expert at usability and Web
page design
Minimal access to IT systems
Expert at JSP
Expert at ASPX
Server Administrator
Server Administrator
No MATLAB experience
Server
administrator
IT Expert
Understands server
architectures
Understands language-specific
frameworks and environments
2-21
End User
End User
Role
End user
Knowledge Base
Responsibilities
No MATLAB experience
End users may use the Web site or may interact with the business tier
directly. In this case, an example of a common activity would be when
a financial analyst accesses a business tier Web service and a complex
Microsoft Excel model. Or, they access an internal Web site, performing
specific tasks not available to their customers.
End-To-End Developer
The end-to-end developers are virtual one-stop shops. They are MATLAB
experts, but are also skilled in many of the areas of expertise as the middle-tier
developer and front-end Web developer, though their level of expertise may
vary over their many areas of responsibility. To this end, this guide presents
2-22
2-23
2-24
3
MATLAB Programmer
Tasks
Programming in MATLAB on page 3-2
Deploying MATLAB Code with the Builders on page 3-6
Programming in MATLAB
In this section...
MATLAB Programming Basics on page 3-3
Returning MATLAB Data Types on page 3-3
MATLAB Programmer
Role
MATLAB
programmer
Knowledge Base
Responsibilities
MATLAB expert
No IT experience
No access to IT systems
3-2
Programming in MATLAB
cannot be deployed.
However, the following calculation:
function result = addSomeNumbers()
result = 1+1;
end
3-3
MATLAB Figures
Often, you are dealing with images displayed in a figure window, and not
just string and numerical data. Deployed Web applications can support
figure window data in a number of ways. By using the WebFigures
infrastructure (see About the WebFigures Feature in the MATLAB
Builder JA documentation or WebFigures in the MATLAB Builder NE
documentation), the respective builder marshals the data for you.
Alternatively, you can take a snapshot of what is in the figure window at a
given point and convert that data into the raw image data for a specific image
type. This is particularly useful for streaming the images across the web.
Returning Data from a WebFigure Window
WebFigures is a feature that enables you to embed dynamic MATLAB figures
onto a Web page through a Builder JA or Builder NE component. This concept
can be used with any data in a figure window.
As in the following example, you close the figure before the code is exited so
that the figure does not pop up, or appear later, in the deployed application.
You do not need to specify any reorientation data when using WebFigures. If
the figure is attached to the rest of the infrastructure, it will automatically
pass, resize, and reorient accordingly.
%returns a WebFigure reference containing the
%data from the figure window
function resultWebFigure = getWebFigure
f = figure;
set(f,'Color',[.8,.9,1]);
f = figure('Visible','off');
surf(peaks);
resultWebFigure = webfigure(f);
close(f);
end
3-4
Programming in MATLAB
3-5
3-6
4
Middle-Tier Developer
Tasks
Working with the Business Service Layer on page 4-2
Creating a DAO for Deployment on page 4-6
Hosting a DAO on a Web Server on page 4-24
Moderate IT Experience
Expert at business logic and
services tier
Java expert
.NET expert
Minimal access to IT systems
Expert at J2EE
Expert at .NET Web
frameworks
Expert at Web services
4-2
SOAP services
Remoting interfaces
HTTP services
Java servlets
JSPs (for Java)
ASPX (for .NET)
Business Objects and Logic This is business data expressed in the form
of objects along with the logic to manipulate the objects. This data is loaded
by a combination of inputs from the interfaces and data from the data
access layer.
Data Access This layer links to all lower-level data such as databases,
where access into a deployed application would typically take place.
Your generated component fits into this category, as it can be used as a
mechanism through which to access the MATLAB Compiler Runtime
(MCR).
4-3
4-4
All examples in this document are coded as stateless (with the exception of
the MATLAB Builder JA WebFigures example) and are scalable. Servers
can be added or augmented by a load balancer for performance tuning.
Tip To scale MATLAB Builder NE WebFigures, use the .NET Distributed
Session setting. This enables all machines in your Web farm to use the same
session.
4-5
Initializing a Component
Use these examples as a framework for initializing a component.
Java
DeploymentExamples deployment = null;
try
{
deployment = new DeploymentExamples ();
//**************
//Use the deployment code here
// (see examples below)
//**************
}
catch(MWException mw_ex)
{
mw_ex.printStackTrace();
}
finally
{
deployment.dispose();
}
4-6
.NET
DeploymentExamples.DeploymentExamples deployment = null;
try
{
deployment = new DeploymentExamples.DeploymentExamples();
//******************************
//**Use your deployment code here
//** (See examples below)
//******************************
}
finally
{
deployment.Dispose();
}
.NET
int n = 3;
4-7
.NET
String[] array =
{
4-8
"Jordan Robert",
"Mary Smith",
"Stacy Flora",
"Harry Alpert"
};
int numberOfArrayElements = array.Length;
int numberOfArrayColumns = 1;
MWCellArray cellArray =
new MWCellArray(
numberOfArrayColumns,
numberOfArrayElements);
for (int i = 1; i < array.Length + 1; i++)
{
cellArray[i] = array[i - 1];
}
4-9
numberOfListColumns,
numberOfListElements);
//Iterate through the list adding the elements
//
to the cell array.
Iterator friendsListItr = friendsList.iterator();
for(int i = 1;friendsListItr.hasNext(); i++)
{
String currentFriend = (String)friendsListItr.next();
cellArray2.set(i, currentFriend);
}
.NET
List<String> list = new List<String>();
list.Add("Jordan Robert");
list.Add("Mary Smith");
list.Add("Stacy Flora");
list.Add("Harry Alpert");
int numberOfArrayElements = list.Count;
int numberOfArrayColumns = 1;
MWCellArray cellArray =
new MWCellArray(
numberOfArrayColumns,
numberOfArrayElements);
int i = 1;
foreach (String currentElement in list)
{
cellArray[i] = currentElement;
i++;
}
4-10
4-11
.NET (Dictionaries)
Dictionary<String, int> dictionary =
new Dictionary<String, int>();
dictionary.Add("Jordan Robert", 3386);
dictionary.Add("Mary Smith", 3912);
dictionary.Add("Stacy Flora", 3238);
dictionary.Add("Harry Alpert", 3077);
int numberOfElements = dictionary.Count;
int numberOfColumns = 1;
String[] fieldnames = { "name", "phone" };
MWStructArray output =
new MWStructArray(
numberOfElements,
numberOfColumns,
fieldnames);
int i = 1;
foreach (String currentKey in dictionary.Keys)
{
output[fieldnames[0], i] = currentKey;
output[fieldnames[1], i] = dictionary[currentKey];
i++;
}
4-12
}
finally
{
MWArray.disposeArray(numericArray);
}
.NET
MWNumericArray result = (MWNumericArray)deployment.getNumeric();
int resultInt = result.ToScalarInteger();
.NET
MWCharArray result = (MWCharArray)deployment.getString();
String resultString = result.ToString();
4-13
.NET
MWNumericArray result =
(MWNumericArray)deployment.getNumericArray();
Double[] doubleArray =
(Double[])result.ToVector(MWArrayComponent.Real);
4-14
MWArray.disposeArray(mwCharArray);
}
.NET
// Note that since MWCharArray doesn't have a
//
ToVector method, it is necessary
//
to iterate through and get a single
//
dimension for the output.
//
MWCharArray result =
//
(MWCharArray)deployment.getStringArray();
char[,] resultArray = (char[,])result.ToArray();
char[] outputArray = new char[resultArray.GetLength(1)];
for (int i = 0; i < resultArray.GetLength(1); i++)
{
outputArray[i] = resultArray[0, i];
}
.NET
MWNumericArray result =
4-15
(MWNumericArray)deployment.getByteArray();
byte[] outputByteArray =
(byte[])result.ToVector(MWArrayComponent.Real);
.NET
MWCellArray result = (MWCellArray)deployment.getCellArray();
List<Object> outputList = new List<Object>();
4-16
.NET
MWStructArray result = (MWStructArray)deployment.getStruct();
4-17
4-18
.NET
For more information about WebFigures, see WebFigures in the MATLAB
Builder NE documentation. The first two lines of code will not do anything if
executed directly. It needs a WebFigureControl on a front end page that is
called WebFigureControl1. If you are not using a local WebFigureControl
and want to simply return the WebFigure in the current response object,
use this code, for example:
WebFigure webFigure = new WebFigure(deployment.getWebFigure());
WebFigureControl1.WebFigure = webFigure;
//First, attach the webfigure to one of ASP.NET's caches,
// in this case the session cache
Session["SessionStateWebFigure"] = webFigure;
//Now, use a WebFigure Utility to get an HTML String that
// will display this figure, Notice
// how we reference the name we used when attaching it
// to the cache and we indicate
// that the Attach type is session.
String localEmbedString =
WebFigureServiceUtility.GetHTMLEmbedString(
"SessionStateWebFigure",
WebFigureAttachType.session,
300,
300);
Response.Write(localEmbedString);
4-19
{
Object[] byteImageOutput = null;
MWNumericArray numericImageByteArray = null;
try
{
byteImageOutput =
deployment.getImageDataOrientation(
1,
//Number Of Outputs
500,
//Height
500,
//Width
30,
//Elevation
30,
//Rotation
"png"
//Image Format
);
numericImageByteArray =
(MWNumericArray)byteImageOutput[0];
return numericImageByteArray.getByteData();
}
finally
{
MWArray.disposeArray(byteImageOutput);
}
}
.NET
public byte[] getByteArrayFromDeployedComponent()
{
MWArray width = 500;
MWArray height = 500;
MWArray rotation = 30;
MWArray elevation = 30;
MWArray imageFormat = "png";
MWNumericArray result =
(MWNumericArray)deployment.getImageDataOrientation(
height,
width,
elevation,
4-20
rotation,
imageFormat);
return (byte[])result.ToVector(MWArrayComponent.Real);
}
4-21
byte[] imageByteArray =
getByteArrayFromDeployedComponent()
return ImageIO.read
(new ByteArrayInputStream(imageByteArray));
}
catch(IOException io_ex)
{
io_ex.printStackTrace();
}
}
.NET
public byte[] getByteArrayFromDeployedComponent()
{
MWArray width = 500;
MWArray height = 500;
MWArray rotation = 30;
MWArray elevation = 30;
MWArray imageFormat = "png";
MWNumericArray result =
(MWNumericArray)deployment.getImageDataOrientation(
height,
width,
elevation,
rotation,
imageFormat);
return (byte[])result.ToVector(MWArrayComponent.Real);
}
public Image getImageFromDeployedComponent()
{
byte[] byteArray = getByteArrayFromDeployedComponent();
MemoryStream ms = new MemoryStream(myByteArray, 0,
myByteArray.Length);
ms.Write(myByteArray, 0, myByteArray.Length);
return Image.FromStream(ms, true);
}
4-22
4-23
component resides on your Web server. The DAO must reside in this folder,
in a Java archive file (JAR), on the class path so it can be imported.
2 Initialize the DAO using the following examples as templates:
4-24
java.io.IOException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
javax.servlet.ServletException;
javax.servlet.ServletConfig;
java.util.*;
com.mathworks.toolbox.javabuilder.webfigures.WebFigure;
4-25
Numeric
int integer = examples.getIntFromMWNumericArray();
response.getOutputStream().println("int: " + integer);
String
String string = examples.getStringFromMWCharArray();
response.getOutputStream().println("String: " + string);
Numeric Array
int[] intArray = examples.getIntArrayFromMWNumericArray();
response.getOutputStream().println("Numeric Array: ");
for(int i = 0; i<intArray.length;i++)
{
response.getOutputStream().println("Array index("+ i+"): " +
intArray[i]);
}
4-26
Character Array
char[] charArray = examples.getCharArrayFromMWCharArray();
response.getOutputStream().println("Char Array: ");
for(int i = 0; i<charArray.length;i++)
{
response.getOutputStream().println
("Array index("+ i +"): " +
charArray[i]);
}
Structure To Map
Map map = examples.getMapFromStruct();
response.getOutputStream().println("Structure Array: ");
Iterator mapKeyItr = map.keySet().iterator();
while(mapKeyItr.hasNext())
{
String mapKey = (String)mapKeyItr.next();
Object mapValue = map.get(mapKey);
response.getOutputStream().println("KEY: " + mapKey + "
"VALUE: " + mapValue);
" +
4-27
Byte Array
byte[] byteArray = examples.getByteArrayFromMWNumeric();
response.getOutputStream().println("Byte Array: ");
for(int i = 0; i<byteArray.length;i++)
{
response.getOutputStream().print(byteArray[i]);
}
response.getOutputStream().write(byteArray);
Images (WebFigures)
This example is very similar to examples in the MATLAB Builder JA
documentation, but this example guide code also uses our DAO.
HttpSession session = request.getSession();
WebFigure userPlot =
(WebFigure)session.getAttribute("UserPlot");
// if this is the first time doGet has been called
// for this session,
// create the plot and WebFigure object
if (userPlot== null)
{
userPlot = examples.getWebFigureFromMWJavaObjectRef();
// store the figure in the session context
session.setAttribute("UserPlot", userPlot);
// bind the figure's lifetime to the session
session.setAttribute(
"UserPlotBinder",
new MWHttpSessionBinder(userPlot));
}
WebFigureHtmlGenerator webFigureHtmlGen =
new WebFigureHtmlGenerator( WebFigures ,getServletContext());
4-28
String outputString =
webFigureHtmlGen.getFigureEmbedString(
userPlot,
"UserPlot",
"session",
"700",
"700",
null);
response.getOutputStream().print(outputString);
WebFigure to Bytes
byte[] byteArrayFromWebFigure =
examples.getByteArrayFromWebFigure();
response.getOutputStream().write(byteArrayFromWebFigure);
4-29
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
height,
width,
elevation,
rotation,
imageFormat);
response.getOutputStream().write(rawImageBytes);
3 Inside the staging folder you created at the start of this procedure, create a
WEB-INF folder.
4 Inside the WEB-INF folder, create two additional folders:
classes
lib
5 Place all of the class files (including the DAO created in Creating a DAO
for Deployment on page 4-6) into the class folder within the appropriate
package folders that exist.
6 Copy the component JAR file into the lib folder.
7 Create a web.xml file in the WEB-INF folder.
This file provides the Web server with a valid path into your code and
defines the entry point into that code. Use this template as an example:
Example of a web.xml File Used in a Java Servlet Component
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD
Web Application 2.3//EN"
"http://www.Oracle.com/servers/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ExamplesServlet
</servlet-name>
<servlet-class>examples.ExamplesServlet
</servlet-class>
</servlet>
4-30
<servlet-mapping>
<servlet-name>ExamplesServlet</servlet-name>
<url-pattern>/ExamplesServlet</url-pattern>
</servlet-mapping>
</web-app>
The following URL accesses this servlet with the configuration described
above:
http://localhost:8080/Examples/ExamplesServlet
Note the Examples string in the URL, since the JAR is named
Examples.jar. Using this string sets up the correct server context and is a
customizable attribute within the console of many Web servers.
8 Using the java -jar command, bundle the folders you created into a WAR
4-31
In this section, you will learn how to create basic Java objects that handle
business logic, while Apache Axis2 performs the mechanics involved with
turning the logic a Web service and exposing it. Alternatively, you can start
by using WSDL (Web Service Definition Language the definition of your
service) and generate Java from that. Afterward you can customize the Java
with your business logic, or change the WSDL manually in a number of other
ways to meet your needs.
4-32
String
public String getString()
{
Examples examples = new Examples();
String string = examples.getStringFromMWCharArray();
examples.dispose();
return string;
}
Numeric Array
public int[] getIntArray()
{
Examples examples = new Examples();
int[] intArray = examples.getIntArrayFromMWNumericArray();
examples.dispose();
return intArray;
}
Character Array
public char[] getCharArray()
{
Examples examples = new Examples();
char[] charArray = examples.getCharArrayFromMWCharArray();
examples.dispose();
return charArray;
}
Byte Array
public byte[] getByteArray()
{
Examples examples = new Examples();
byte[] byteArray = examples.getByteArrayFromMWNumeric();
examples.dispose();
return byteArray;
}
4-33
class created in Creating a DAO for Deployment on page 4-6 and the
Web service class created in Setting Up the Root Web Service Class on
page 4-32into it.
4-34
2 Create a lib folder and copy your deployed component into it.
3 Create a meta-inf folder and, inside it, create a services.xml file with
these contents:
<service>
<parameter name="ServiceClass"
locked="false">examples.ExamplesWebService</parameter>
<operation name="getInt">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getString">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getIntArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getCharArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getByteArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getImageByteArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
</service>
The services.xml file tells Axis2 which methods to expose, and what
mechanism to use to expose them.
4 Copy all of the files into a WAR (Web archive) file and place them in the
4-35
command but give the output file an .aar extension rather than a .jar
extension.
5 You should now see your service running in the Axis console. From the
console, note the URL for the WSDL file. You will use this URL in other
applications to communicate with your Web service.
System;
System.Data;
System.Configuration;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
4-36
String
String stringResult = examples.getStringFromMWCharArray();
Response.Write("String: " + stringResult);
Double Array
double[] doubleArray =
examples.getDoubleArrayFromMWNumericArray();
Response.Write("Double Array: ");
for (int i = 0; i < doubleArray.Length; i++)
{
Response.Write("Array index(" + i + "): " + doubleArray[i]);
}
Character Array
char[] charArray = examples.getCharArrayFromMWCharArray();
Response.Write("Char Array: ");
for (int i = 0; i < charArray.Length; i++)
{
Response.Write("Array index("+ i +"): " + charArray[i]);
}
4-37
Structure
Dictionary<Object, Object> dictionary =
examples.getDictionaryFromStruct();
Response.Write("Structure Array: ");
foreach (Object currentKey in dictionary.Keys)
{
Response.Write("Key: " + currentKey + "
Value: " +
dictionary[currentKey]);
}
Byte Array
byte[] byteArray = examples.getByteArrayFromMWNumericArray();
Response.Write("Byte Array: ");
for (int i = 0; i < byteArray.Length; i++)
{
Response.Write(byteArray[i]);
}
Response.BinaryWrite(byteArray);
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray();
Response.BinaryWrite(rawImageBytes);
4-38
WebFigure
// In this example, we use a WebFigure Utility to get an HTML
// String that
// will display this figure, Notice
// how we reference the name we used when attaching it to the
// cache and we indicate
// that the Attach type is session.
String localEmbedString =
WebFigureServiceUtility.GetHTMLEmbedString(
"SessionStateWebFigure",
WebFigureAttachType.session,
300,
300);
Response.Write(localEmbedString);
4-39
String
[WebMethod]
public String getString()
{
Examples.Examples examples = new Examples.Examples();
String stringResult = examples.getStringFromMWCharArray();
examples.dispose();
return stringResult;
}
4-40
Double Array
[WebMethod]
public double[] getDoubleArray()
{
Examples.Examples examples = new Examples.Examples();
double[] doubleArray =
examples.getDoubleArrayFromMWNumericArray();
examples.dispose();
return doubleArray;
}
Double Matrix
Since .NET Web services cant support multidimensional arrays, convert what
is returned from MATLAB Builder NE into a jagged array, as follows:
[WebMethod]
public double[][] getDoubleMatrix(int argMagic)
{
Examples.ExamplesImpl examples =
new Examples.ExamplesImpl();
double[,] doubleMatrix =
examples.getDoubleMatrixFromMWNumericArray(argMagic);
int arraySize = (int)doubleMatrix.GetUpperBound(0) + 1;
double[][] outputMatrix = new double[arraySize][];
int upperOuter = i < (int)doubleMatrix.GetUpperBound(0) + 1;
for (int i = 0; upperOuter ; i++)
{
double[] subArray = new double[arraySize];
int upperInner = (int)doubleMatrix.GetUpperBound(1) + 1;
for(int j = 0; j < upperInner; j++)
{
subArray[j] = doubleMatrix[i, j];
}
outputMatrix[i] = subArray;
4-41
}
examples.dispose();
return outputMatrix;
}
Character Array
[WebMethod]
public char[] getCharArray()
{
Examples.Examples examples = new Examples.Examples();
char[] charArray = examples.getCharArrayFromMWCharArray();
examples.dispose();
return charArray;
}
Byte Array
[WebMethod]
public byte[] getByteArray()
{
Examples.Examples examples = new Examples.Examples();
byte[] byteArray = examples.getByteArrayFromMWNumericArray();
examples.dispose();
return byteArray;
}
4-42
4-43
4-44
5
Front-End Web Developer
Tasks
Working with the Front-End Layer on page 5-2
Creating a WebFigure on a JSP Page on page 5-7
Creating a WebFigure on an ASPX Page on page 5-11
Working with Static Images on page 5-15
Displaying Complex Data Types Including Arrays and Matrices on page
5-20
Using Web Services on page 5-28
Front-end Web
developer
Knowledge Base
Responsibilities
No MATLAB experience
Minimal IT experience
Expert at usability and Web
page design
Minimal access to IT systems
Expert at JSP
Expert at ASPX
5-2
5-3
Data Access This sublayer pulls data in from middle-tier services like
databases, where access into a deployed application would typically take
place. Among the technologies used to transmit data at this sublayer are:
5-4
Remoting interfaces
SOAP services
5-5
The following two templates show how you can integrate applications built
with MATLAB products into a larger application. In each case, there is a
small area in the interface where your applications exist after the user enters
input (if only a mouse click).
In the left template, it is possible to have a simple IMG tag, where the src=
is a servlet from the middle tier that dumps out the image data. It is also
possible to use an interactive AJAX component embedded in a subframe, or to
use embedded WebFigures.
In the right template, clicking the Go button triggers the page to validate that
the value in the input box is valid, and then sends that data to the middle tier
service which returns a two-dimensional array. It is the front-end layers job
to format this data and present it properly.
In the examples that follow, these concepts are simplified and focus on how
the communication occurs within the middle layer, and how some typical data
translations are performed.
5-6
5-7
new MWHttpSessionBinder(userPlot));
}
When using this approach, the only other code needed on the servlet is a
redirect back to the JSP that the above code resides on. In this example, this
code is contained in response.jsp. The servlet code would look like this:
RequestDispatcher dispatcher =
request.getRequestDispatcher("/response.jsp");
dispatcher.forward(request, response);
5-8
Tip This technique can be used regardless of the transfer protocol or location
of the front end or back end. Since a simple string is being sent, you can
code the front-end in a number of ways, adapting nicely to a SOAP transfer,
for example.
<iframe
src ="http://localhost:8080/Examples/ExamplesServlet?
function=webFigureEmbedded"
width="590"
height="480">
</iframe>
5-9
5-10
C#:
using MyComponent;
using MathWorks.MATLAB.NET.WebFigures;
5-11
Visual Basic:
Imports MyComponent
Imports MathWorks.MATLAB.NET.WebFigures
cache. This can either be done using code as shown below or by using the
Properties window in the designer.
//This is the name that was used on the server
// when attaching the WebFigure
WebFigureControl1.Name = "UserPlot";
//By not setting this value it will try and use
// the current web site for all redirection calls
WebFigureControl1.Root = "";
//If you didn't set this or if it was set to unknown
// this would instruct the WebFigureService to look
// through the diferent caches for a WebFigure with
// this specific name.
WebFigureControl1.Scope = WebFigureAttachType.session;
5-12
5-13
<cc1:WebFigureControl
ID="WebFigureControl1"
runat="server"
Height="328px"
Width="399px"
Root=""
Scope="session"
Name="UserPlot"
/>
5-14
5-15
ID="Image1"
runat="server"
ImageUrl=
"http://localhost/Examples/Tester.aspx?function=
imageBytesFromMWNumeric" />
5-16
function getParam(name)
{
var start=location.search.indexOf("?"+name+"=");
if (start<0) start=location.search.indexOf("&"+name+"=");
if (start<0) return '';
start += name.length+2;
var end=location.search.indexOf("&",start)-1;
if (end<0) end=location.search.length;
var result='';
for(var i=start;i<=end;i++) {
var c=location.search.charAt(i);
result=result+(c=='+'?' ':c);
}
return unescape(result);
}
function updateView()
{
var urlStr = getParam("url") +"&" +
"imageFormat=png" + "&" +
"rotation=" + rotationDegree + "&" +
"elevation=" + elevationDegree + "&" +
"width=" + contentBox.clientWidth + "&" +
"height=" + contentBox.clientHeight;
var requestedImage =
document.getElementById('currentImage');
requestedImage.src = urlStr;
requestedImage.style.visibility = 'visible';
}
5-17
function stopDragging(updateX,updateY)
{
rotationDegree +=
Math.round(((startDragX updateX)/2)%360);
elevationDegree +=
Math.round(-(startDragY updateY)/2);
updateView();
}
</script>
</head>
<body onresize='updateView();'>
<form name=exf1>
X Drag <input type=text name=x value="0">
Y Drag <input type=text name=y value="0">
</form>
<div style='position:absolute; background:
url("matlab.gif"); left:0; right:0;
width:100%; height:100%;'>
<img style="visibility: hidden; position:absolute;
width:100%; height:100%; left:0;
top:0" src="matlab.gif"
id="currentImage">
</div>
<div id='contentBox'
style='position:absolute; background:
url("transparent_pixel.gif");
left:0; top:0; background-color:
<%= request.getParameter("color") %>;
width:100%; height:100%; overflow:hidden;'
onmousedown="mouseisdown = true; startDragX=event.clientX;
startDragY=event.clientY;"
onmouseup="mouseisdown =
false;stopDragging(event.clientX, event.clientY);
document.exf1.x.value=0; document.exf1.y.value=0;"
5-18
onmousemove="if(mouseisdown)
{document.exf1.x.value=event.clientX-startDragX;
document.exf1.y.value=event.clientY-startDragY;}">
</div>
<script type="text/javascript">
updateView();
</script>
</body>
</html>
5-19
5-20
array of data. Assuming you have a label on the ASPX page called MatrixLbl,
here is the code to output the matrix:
int size = 5;
double[][] magicSquare = getMagicSquare(size);
String temp = "";
temp +="<table border=0 cellpadding=4
cellspacing=4 style='margin: 16px;'>";
for (int i = 0; i < size; i++)
{
temp += "<tr>";
for (int j = 0; j < size; j++)
{
temp += "<td>" + magicSquare[i][j] + "</td>";
}
temp += "</tr>";
}
MatrixLbl.Text = temp;
5-21
Note If you are using Handle Graphics functions with ASP.NET, you may
need to enable interaction between IIS and the desktop. For information
about how to accomplish this, see the related workaround in the Diagnostic
Messages section of the MATLAB Builder NE Users Guide.
5-22
1 Start Visual Studio and configure the data source with the wizard.
2 Choose the business class that contains your methods for the object.
5-23
5-24
3 Select the method that returns a data table containing the data to display.
5-25
4 Since the method requires an input, bind it to the control that contains the
5-26
Note If you are using Handle Graphics functions with ASP.NET, you may
need to enable interaction between IIS and the desktop. For information
about how to accomplish this, see the related workaround in the Diagnostic
Messages section of the MATLAB Builder NE Users Guide.
5-27
server type).
5-28
You should be able to use any SOAP add-in. However, note that the call
syntax may change slightly. Consult the add-in documentation for further
information.
Displaying Web Services Images and Data in .NET
In Working with the Business Service Layer, you exposed several methods
as SOAP Web services. To use these methods from the front end, add a
reference to them in your Visual Studio project by adding a Web Reference:
1 In Visual Studio, right-click the project name and select Add Web
Reference.
2 In the URL field, enter the path to your WSDL.
3 Click Go. The resulting dialog resembles this.
5-29
5 To use any of the methods, instantiate the Web service by executing code
similar to:
localhost.ExamplesWebService webService =
new localhost.ExamplesWebService();
6 Access any of the methods on the Web service as you would any other .NET
5-30
6
Server Administrator Tasks
Managing a Deployment Server Environment on page 6-2
Hot Deployment on page 6-12
Working with Multiple Versions of the MATLAB Compiler Runtime
(MCR) on page 6-13
Unsupported Versions of the JVM on page 6-14
IT Expert
Understands server
architectures
Understands language-specific
frameworks and environments
6-2
It provides different methods of dealing with common issues that can affect
stability and performance.
In this figure, you can see how the MCR (a large native code base) exists
within the outer process of the frameworks. This coexistence can cause issues,
as illustrated later in this chapter.
6-3
6-4
6-5
.NET
In ASP.NET Web applications, create a Global Assembly Cache (Global.asax)
using this code:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
myComponent.MyComponent comp =
new myComponent.MyComponent();
}
</script>
For more information about the Global.asax file, see Using Global Assembly
Cache (Global.asax) to Create WebFigures at Server Start-Up.
Note You do not need to dispose of the component. With MATLAB Builder
NE, you utilize the garbage collector to clean up these objects, even though
they reference native components.
6-6
Java
In a J2EE server, you write a ContextListener class that contains code the
server automatically runs when you install or remove the application.
1 Utilize the class by placing the following code in your web.xml file:
<listener>
<listener-class>myContextListenerClass</listener-class>
</listener>
2 Place this code in your class:
import javax.servlet.*;
public final class myContextListener
implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
// This method is called when the application
//
is first deployed in the server
//Instantiate the deployed component,
// this will trigger the MCR to be started
event.getServletContext().setAttribute
(
"myComponent",
new myComponent.MyComponent());
}
public void contextDestroyed(ServletContextEvent event)
{
// This method is called when the application
//
is shut down on the server
myComponent.MyComponent myComp =
event.getServletContext().
getAttribute("myComponent");
if(myComp != null)
{
//
Dispose of the object when the
6-7
//
server is shut down
//
since it utilizes native resources
//
that the garbage
//
collector won't clean up.
myComp.dispose();
}
}
}
Calculation Scaling
Calculation scaling involves increasing computer resources to scale and
improve performance for a specific calculation. In MATLAB, the Parallel
Computing Toolbox enables your MATLAB code to use features built into
the MATLAB Language. These features tie into a profile and enable your
functions to run in parallel. Parallel processing can drastically speed up the
execution of a function.
There are multiple strategies towards make your applications scalableone
is done by writing your MATLAB code to scale to a parallel computing
algorithm. You may ultimately have calculation scaling as well as Session
Scaling on page 6-8 to optimize performance.
Session Scaling
Session scaling involves enabling the maximum number of users while
minimizing performance degradation.
Many session scaling issues arise because the MCR is single threaded. A
single-threaded application prevents two users from doing work that involves
the MCR at the same time. One user must wait for the other to finish before
continuing. This wait can prove to be substantial if one user is performing a
resource-intensive task while the other is attempting a quick calculation.
6-8
6-9
Remote Scaling
6-10
auto-conversion frees you from running an MCR where the client process
executes, yielding a robust more application.
6-11
Hot Deployment
Hot Deployment entails replacing running application source code on-the-fly.
The server automatically migrates end users to this new code without the
user experiencing an outage.
.NET
MATLAB Builder NE supports Hot Deployment of deployed components in
either:
The WebDev server (the version of IIS built into Microsoft Visual Studio)
IIS itself
Java
Support for Hot Deployment in MATLAB Builder JA is not available at this
time.
6-12
6-13
6-14
7
End User Tasks
Working with Content on page 7-2
Example Tasks on page 7-3
End user
7-2
Knowledge Base
Responsibilities
No MATLAB experience
Example Tasks
Example Tasks
The example in this section consumes the Web service created in Deploying
the Web Service on page 4-34. With this type of application, you can use the
same Web service to display many different front ends. You can use data
stored in Microsoft Excel and pass it to a Web service to generate dynamic
data-driven images.
Microsoft Excel Web Service Client Standalone Application
To construct a Microsoft Excel interface to the Web service:
1 Download and install the Microsoft Office Web Service Toolkit from
the Web service call and load the graphic. At this stage, the window looks
like this.
7-3
6 Double-click the Command Button button and the VBA editor starts.
7 Select Tools > Web Service References.
Note The Web Service References option is available only if you install
the Microsoft Office Web Service Toolkit.
8 In Web Service URL, type the WSDL that was referenced in Using Web
7-4
Example Tasks
9 Click Search to query the Web service. The result resembles this.
10 Select the appropriate service in the Search Results pane and click Add
7-5
12 Click the command to display the following in the graphics pane of your
worksheet.
Tip You may need to close Microsoft Excel and reopen it to see the graphic.
7-6
8
End-to-End Developer
Tasks
Role of the End-To-End Developer on page 8-2
Magic Square Calculator On the Web on page 8-5
Creating an End-to-End Web Application on page 8-7
MATLAB
programmer
Knowledge Base
Responsibilities
MATLAB expert
No IT experience
No access to IT systems
8-2
Middle-Tier Developer
Little to no MATLAB
experience
Middle-tier
developer
Moderate IT Experience
Expert at business logic and
services tier
Java expert
.NET expert
Minimal access to IT systems
Expert at J2EE
Expert at .NET Web
frameworks
Expert at Web services
Front-End Web Developer
Role
Front-end Web
developer
Knowledge Base
Responsibilities
No MATLAB experience
Minimal IT experience
Expert at usability and Web
page design
Minimal access to IT systems
Expert at JSP
Expert at ASPX
8-3
Server Administrator
No MATLAB experience
Server
administrator
IT Expert
Understands server
architectures
Understands language-specific
frameworks and environments
End User
Role
End user
8-4
Knowledge Base
Responsibilities
No MATLAB experience
getMagicWebFigure.m:
function figureOutput = getMagicWebFigure(x)
f = figure;
magicOutput = magic(x);
surf(magicOutput);
set(gcf,'Color',[1,1,1])
figureOutput = webfigure(f);
close(f);
end
The Magic Square Calculator application, when built, looks like this.
8-5
8-6
request comes in, calling the MATLAB function that returns the matrix,
the MATLAB function returns the WebFigure. The servlet then binds the
WebFigure to the application cache of the server and produces HTML that
displays the WebFigure and finally, the matrix.
The following procedure gives you an option to build your example Web
component or download it from MATLAB Central. To download the example,
go to Building Your Example Component on page 8-7.
Exchange at http://www.mathworks.com/matlabcentral/fileexchange.
Once you open the file exchange, search for Java Web Example Guide
End To End Chapter.
8-7
2 Extract the JavaEndToEnd.zip file into a working folder where you can
startup.bat.
4 Copy javabuilder.jar to the tomcat/common/libs folder.
5 Once Tomcat starts successfully, drag the JavaEndToEnd.war file into the
http://localhost:8080/JavaEndToEnd/MagicSquare/ExamplesPage.jsp.
matches the version used by the MCR. See the MATLAB Compiler Users
Guide reference pages for details on the mcrversion command.
2 Ensure you have Tomcat 5 or later on your system (other J2EE Web
servers can work also, but the steps in this document have been tested
with Tomcat).
3 Ensure the version of the MCR you have installed is the same version as
the MCR running with MATLAB when the application was built. If you
are unsure, check with your MATLAB programmer or whoever initially
deployed the component.
4 Make note of the folder where the MCR is installed. It will be used later
Note This code uses an image resource and a cascading style sheet
resource that is included if you download the code from MATLAB Central
as in Building Your Example Component on page 8-7.
8-8
<html>
<head>
<title>Calculation Services</title>
<%
//This section of code determines if the user has entered
// a number for the square size, if they have it overlays
// the default size which is 5.
String sizeStr = request.getParameter("size");
int size = 5;
if(sizeStr!=null && sizeStr.length()>0)
{
size = Integer.parseInt(sizeStr);
}
%>
<link rel="Stylesheet" type="text/css"
media=all href="./StyleSheet.css" />
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form method="get">
<div style="text-align: center">
<table width="760" cellpadding="0" cellspacing="0">
<tr>
<td><img src="header_bg.jpg"
alt="Header Image Not Found"
width="779" height="72" /></td>
</tr>
</table>
<br />
<h1> Calculation Services</h1>
Calculate Magic Square
<br>
Size:
<input type="text" name="size" size="8" value="<%=size%>" >
<br>
8-9
objXHR.open('GET','MagicSquare?size=<%=size%>',false);
objXHR.send(null);
//Display the result of the servlet on the page
document.writeln(objXHR.responseText);
</script>
<br>
</div>
8-10
</form>
</body>
</html>
Note This code requires that the generated component created earlier and
javabuilder.jar must be on the classpath in order to compile.
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import examples.*;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigure;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigureHtmlGenerator;
import com.mathworks.toolbox.javabuilder.MWJavaObjectRef;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import com.mathworks.toolbox.javabuilder.MWException;
public class MagicSquareServlet extends HttpServlet
{
private MagicCalc calc;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try
{
//We initialize the deployed component in the init
// method so it doesn't get initialized with each request
calc = new MagicCalc();
}
catch(MWException e)
{
e.printStackTrace();
8-11
}
}
public void destroy()
{
super.destroy();
if(calc!=null)
{
//When the servlet gets disposed you can clean
// up the deployed component reference as well.
calc.dispose();
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//If no size has been provided, return.
String sizeStr = request.getParameter("size");
if(sizeStr==null || sizeStr.length()==0)
return;
//Convert the input parameter size to an MWArray
//
8-12
8-13
buffer.append("<BR>");
//Step through the matrix and output it to an HTML Table
buffer.append("<TABLE >");
for (double[] row : square)
{
buffer.append("<TR>");
for (double value : row)
{
buffer.append("<TH>");
buffer.append(new Double(value).intValue());
}
}
buffer.append("</TABLE>");
buffer.append("<BR>");
matlabroot/toolbox/javabuilder/jar/javabuilder.jar) to the
webapp/WEB-INF/lib folder.
8 Since you are compiling a servlet which has J2EE dependencies, copy
servlet-api.jar (the J2EE JAR file that comes with Tomcat) to the
current working folder. This file is usually located in the Tomcat common
lib folder (a J2EE JAR file can work as well).
9 From the root of your Projects folder we need to build the component with
8-14
10 Copy it from your working folder to the Web applications lib folder by
typing:
xcopy /Y .\scratch\examples.jar .\webapp\WEB-INF\lib
11 Rebuild the servlet by typing the following command:
cd webapp
jar -cvf ..\JavaEndToEnd.war .
cd ..
Visual Studio. See the MATLAB Builder NE system requirements for a list
of supported framework versions.
8-15
2 Ensure the version of the MCR you have installed is the same version as
the MCR running with MATLAB when the application was built. If you
are unsure, check with your MATLAB programmer or whoever initially
deployed the components. See the MATLAB Compiler Users Guide
reference pages for details on the mcrversion command.
3 Make note of the folder where the MCR is installed. It will be used later
//
8-16
double[,] magicSquare =
(double[,])output.ToArray(MWArrayComponent.Real);
//Create an empty data table to put the matrix data in.
DataTable table = new DataTable();
//Since we know its a square add as many
//
8-17
Version=2.8.1.0, Culture=neutral,
PublicKeyToken=e1d84a0da19db86f"
Namespace="MathWorks.MATLAB.NET.WebFigures.Service"
TagPrefix="cc1" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Calculation Services</title>
<link rel="Stylesheet" type="text/css"
media=all href="./StyleSheet.css" />
<link href="StyleSheet.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center">
<table width="760" cellpadding="0"
cellspacing="0">
<tr>
<td>
<img
src="header_bg.jpg"
alt="Header Image Not Found"
width="779"
height="72" /></td>
</tr>
</table>
<br />
<h1> Calculation Services</h1>
<asp:Label
ID="Label3"
runat="server"
Text="Calculate Magic Square">
</asp:Label>
8-18
<br />
<asp:Label
ID="Label4"
runat="server"
Text="Size: ">
</asp:Label>
<asp:TextBox
ID="TextBox3"
runat="server"
Width="61px">
5
</asp:TextBox>
<br />
<asp:Button
ID="Button2"
runat="server"
OnClick="Button2_Click"
Text="Calculate" />
<br />
<br />
<cc1:WebFigureControl
ID="WebFigureControl1"
runat="server"
Height="330px"
Width="330px" />
<br />
<br />
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
SelectMethod="getMagicSquare"
TypeName="MagicSquare">
<SelectParameters>
<asp:ControlParameter
8-19
ControlID="TextBox3"
DefaultValue="5"
Name="size"
PropertyName="Text"
Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="ObjectDataSource1"
ShowHeader="False">
</asp:GridView>
</div>
</form>
</body>
</html>
6 Create the code behind the ASPX page:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Examples;
using MathWorks.MATLAB.NET.WebFigures;
using MathWorks.MATLAB.NET.Arrays;
public partial class _Default : System.Web.UI.Page
{
private MagicCalc calc = new MagicCalc();
protected void Page_Load(object sender, EventArgs e)
{
MWArray input = Int32.Parse(TextBox3.Text);
WebFigureControl1.WebFigure =
8-20
new WebFigure(calc.getMagicWebFigure(input));
}
protected void
{
MWArray input = Int32.Parse(TextBox3.Text);
WebFigureControl1.WebFigure =
new WebFigure(calc.getMagicWebFigure(input));
ObjectDataSource1.Select();
}
}
mcc -W "dotnet:Examples,MagicCalc,0.0,private"
-d ".\mcode\output" -T "link:lib"
-v
"class{MagicCalc:.\mcode\getMagic.m,
.\mcode\getMagicWebFigure.m}"
any errors or issues adding it, delete it and add a new reference to the DLL
you built in the WebSite\mcode\output folder.
8-21
local IIS server starts and opens your page inside of it.
8-22
A
Sources for More
Information
Other Examples
Use these links for more information on other Web examples of possible
interest:
MATLAB Builder JA
Other examples using MATLAB Builder JA include:
Black-Scholes
MATLAB Central Black-Scholes Web Application for Java
WebFigures
MATLAB Builder JA WebFigures Varargs Application
MATLAB Builder NE
Other examples using MATLAB Builder NE include:
Black-Scholes
MATLAB Central Black-Scholes Web Application for .NET
A-2