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 MathW orks, 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
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
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
government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Docu mentation, 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
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Application Deployment Web Example Guide
Page 3
Revision History
March 2008Online onlyNew for MATLAB®Compiler™ Version 4.8 (Release
October 2008Online onlyRevised for MATLAB
R2008a)
R2008b)
March 2009Online onlyRevised for MATLAB
R2009a)
September 2009 Online onlyRevised for MATLAB
R2009b)
March 2010Online onlyRevised for MATLAB
®
Compiler™ Version 4.9 (Release
®
Compiler™ Version 4.10 (Release
®
Compiler™ Version 4.11 (Release
®
Compiler™ Version 4.13 (Release
R2010a)
Page 4
Page 5
1
About This Guid
How to Use This Guide
e
..................................
Contents
1-2
Who Should Use
Commonly Use
Information
MATLAB P rog
Integratio
Front-End
Internal A
Web 101: A
n Experts (Business Service Developer and
Developer)
nalyst
n Introduction to W eb Concepts and
This Guide?
d Software and Preliminary Setup
.....................................
rammer
.............................
..................................
.......................
............................
Termino
2
Why Learn About Web Concepts and Terminology? ...2-2
Basics of Web Processing
HTML Documents and HTTP
Integrating MATLAB Code on the Web Using Java
Servlets
Optimizing Performance of Servlets That Call Your
MATLAB W eb Code
Maintaining Data Integrity Through Proper Scoping
.......................................2-4
...........................2-3
.......................2-3
.............................2-6
1-3
1-4
1-4
1-4
1-5
logy
....2-9
Lifecycle of a Deployed MATLAB Web Application
Introduction
MATLAB Web Application Environment
MATLAB P rogrammer
Business Service Developer
......................................2-16
..............2-18
.............................2-21
.........................2-21
....2-16
v
Page 6
Front-End D eveloper ...............................2-21
Server Administrator
Internal Analyst
End-To-End Developer
..............................2-22
..................................2-22
.............................2-22
MATLAB Programmer Tasks
3
Programming in MATLAB ..........................3-2
Returning Data Types
..............................3-3
Deploying MA TLAB Code with the Builders
..........3-6
Business Service Developer Tasks
4
Working with the Business Service Layer ............4-2
About the Business Service Layer
About the Examples
Creating a DAO for Deploym en t
Initializing a Component
Interacting with a Component
HostingaDAOonaWebServer
Hosting the DAO with a Servlet
Hosting a DAO U sing a Java™ Web Service
Hosting a .NET DAO with ASPX
Hosting a DAO Using a .NET Web Service
...............................4-4
...........................4-6
....................4-2
....................4-6
.......................4-7
.....................4-24
......................4-24
............4-31
.....................4-36
.............4-40
viContents
Page 7
Front-End Developer Tasks
5
Working with the Front-End Layer ..................5-2
About the Front-End Layer
About the Examples
...............................5-4
.........................5-2
Creating a WebFigure on a JSP Page
Creating a WebFigure on an ASPX Page
Working with Static Images
Displaying Complex Data Types Including Arrays and
Matrices
Using Web Services
........................................5-18
................................5-26
........................5-13
................5-6
.............5-10
Server Administrator Tasks
6
Manag
ing a Deployment Server Environment
The Se
An Ove
Inst
Load
Scal
Ensu
rver Administrator’s Role in Deployment
rview of Deployed Applications
alling the MATLAB Compiler Runtime (MCR)
ing the MATLAB Compiler Runtime (MCR)
ing Your Server Environment
ring Fault Tolerance
...........................
................
....................
........
........
......
........
6-2
6-2
6-2
6-3
6-6
6-8
6-9
Deployment
Hot
T
.NE
Ja
Wo
C
............................................
va
............................................
rking with Multiple Versions of the MATLAB
ompiler Runtime (MCR)
...................................
........................
6-1
6-1
6-
-12
6
1
1
11
vii
Page 8
Unsupported Versions of the JVM ...................6-13
Internal Analyst Tasks
7
Working with Content.............................7-2
Example Tasks
....................................7-3
End-to-End Developer Tasks
8
Role of the End-To-End Developer..................8-2
Example: The Magic Square Calculator On the Web
Creating an End-to-End Web Application
Creating a Java Web Application, End-to-End
Creating a .NET Web Application, End-to-End
............8-5
..........8-5
.........8-13
Sources for More Information
A
..8-3
viiiContents
Other Examples...................................A-2
MATLAB
MATLAB
®
Builder JA ..............................A-2
®
Builder NE .............................A-2
Index
Page 9
How to Use This Guide
• “About This Guide” on page 1-2
• “Who Should Use This Guide?” on page 1-3
• “Commonly U sed Software and Preliminary Setup Information” on page 1-4
1
Page 10
1 How to Use This Guide
About This Guide
MATLAB® Compiler™, MATLAB Builder NE™, MATLAB Builder JA™,
and MATLAB Builder EX™ take MATLAB functions and expose them in
alanguage-specificmannerthatcanbedeployedtouserswhodonothave
MATLAB installed.
When deploying a MATLAB application in a Web-based environment, the
number of possible architectural configurations, programm ing languages,
operating systems, W eb servers, and frameworks can be intimidating,
especially if you are new to Web deployment.
The goal of the MATLAB Application Deployment Web Example Guide is to
provide a series of templates demonstrating how to successfully implement
thepossibleconfigurationsavailable in the Web deployment space.
Use this guide to:
• Learn about the components of a Web deployment environment.
1-2
• 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:
- Creating a deployable function
- Hosting the co mponent delivered by the MATLAB Programmer u sing
J2EE and .NET Web technologies
- Displaying complex data types (arrays, matrices) on a Web page
- Enabling scalability through stateless services used with M ATLAB
Builder™ JA or MATLAB Builder NE
• Deploying applications through implementation of SOAP Web services
®
Page 11
Who Should Use This Guide?
Many skill sets are involved in deploying MATLAB® applications.
TheseskillssetsincludetheMATLAB Programmer (usually a scientist
or engineer), a Business Services Developer and Front-E nd Developer
(programmers responsible for interfacing with languages and frameworks
such as Java and .NET, as well as developing Web page content), and the end
user, who consumes the final product.
Since it is sometimes confusing to determine who should perform what task in
a large installation, this guide’s structure is role based. In other words, the
tasks that belong to each role are listed in separate sections or chapter. This
organization enables more novice users to focus only on the tasks related to
their area of expertise and enables advanced users to customize a list of tasks
pertinent to their own area of expertise.
Who Should U se This Guide?
1-3
Page 12
1 How to Use This Guide
Commonly Used Software and Preliminary Setup
Information
In this section...
“MATLAB Programmer” on page 1-4
“Integration Experts (Business Service Developer and Fro nt-End
Developer)” on page 1-4
“Internal Analyst” on page 1-5
MATLAB Programmer
• MATLAB®
• Financial Toolbox
®
• MATLAB
• MATLAB Builder JA
Compiler™
1-4
• MATLAB Builder NE
Note Many of the examples in this guide use the software listed here. It is
notlikelyyouwilluseallofthesoftwarelistedhere.
Integration Experts (Business Service Developer and
Front-End Developer)
• MCR (MATLAB® Compiler™ Runtime)
• Microsoft® Visual Studio™ 2005 or other supported IDE
• Microsoft IIS 5
• Microsoft .NET Framework
• Java™ SDK (Software Developer Kit) 1.5 or later
• Java JRE (Java Runtime Environment) 1.5 or later
Page 13
Commonly Used Software and Preliminary Setup Information
• Apache Tomcat™ 5 Web Server
• Apache Axis2™ Web Services Engine
• PHP server-side hypertext preprocessor 5.2.3 o r later
• NUSOAP PHP class add-in
Internal Analyst
• Microsoft Office™ 2003 or later
• Microsoft Office™ Web Services Toolkit
SoftwareRoles
MATLAB,
Compiler
Business
MATLAB
Programmer
Java
Builder
.NET
Builder
Integration ExpertsEnd UserEnd-to-end User
Business Service
Developer
MCR,
Java web server
(e.g., Tomcat),
Soap server
(e.g., Axis)
MCR, IIS,
Soap server (IIS)
Front End
Developer
Java web server,
home grown apps
(e.g., Excel),
third party apps
(e.g., Siebel)
IIS,
home grown apps
(e.g., Excel),
third party apps
(e.g., Siebel)
External
User
Web browser
(Firefox, IE,
Safari)
Internal
Analyst
Web browser
(Firefox, IE,
Safari)
Excel
General
Developer
MCR, Java web server
(e.g., Tomcat),
Soap server (e.g., Axis),
home grown apps
(e.g., Excel),
third party apps
(e.g., Siebel)
MCR, IIS,
Soap server (IIS),
home grown apps
(e.g., Excel),
third party apps
(e.g., Siebel)
1-5
Page 14
1 How to Use This Guide
1-6
Page 15
Web 101:An Introduction
toWebConceptsand
Terminology
• “Why Learn About Web Concepts and Terminology?” on page 2-2
• “Basics of Web Processing” on page 2-3
• “Lifecycle of a Deployed MATLAB Web Application” on page 2-16
Interest in Web concepts increases proportionally in a business o rga n iza t ion
as the technology become s more vital to the success of that busines s.
To ensure the success of the organization, your team members must
understand basic concepts and terminology relating to Web information
processing. In organizations where resources are limited, Web infrastructure
and deployment tasks are often assumed by a limited number of staff (the
“one-stop-shops” mentioned in Chapter 8, “End-to-End Developer Tasks”). In
such environments, understanding the basics becomes even more vital to
success.
This introduction includes:
• “Basics of Web Processing” on page 2-3 — What happens after a URL is
enteredoraGUIbuttononaWebpageisclicked? Thistopicdetailsthe
basics of Java servlet-based Web processing. You’ll also read about the
hardware and software used in Web architecture, and the terminology that
surrounds Web-basedapplications.
• The Lifecycle of a Deployed M ATLA B
introduces you to the various tiers of infrastructure that comprise
the MATLAB Web deployment environment and the most prominent
deployment roles played
®
Web Application — This topic
2-2
Page 17
Basics of Web Processing
In this section...
“HTML Documents and HTTP” on page 2-3
“Integrating MATLAB Code on the Web Using Java Servlets” on page 2-4
“Optimizing P erformance of Servlets That Call Your MATLAB Web Code”
on page 2-6
“Maintaining Data Integrity Through Proper Scoping” on page 2-9
HTML Documents and HTTP
Web processing take place on some combination of a client, running a Web
browser (such as Microsoft
Web server. HTTP (HyperText Transfer Protocol) is a simple, synchronous
protocol—a client connecting to a server, sending a single command, then
waiting for a response from the server.
Basics of Web Processing
®
Internet Explorer®or Mozilla®Firefox®)anda
In the most basic scenario, the URL specifies the exact document to be
read. A browser using HTTP retrieves the document for display. Most Web
applications, how ever, deal extensively with dynamic, interactive content.
Typically, Web processing is made up of the following workflow:
1 The user enters a URL request, either manually or via a search engine,
in the browser.
2 The browser parses the URL into two parts: one specifying the server and
one specifying a document on the server to be retrieved.
For example, the URL
http://www.mathworks.com/product-list.html
indicates the product-list HTML document on The MathWorks™ server.
3 A browser using HTTP retrieves the document from the server. After
the data is downloaded into the browser, it is parsed and rendered. The
document may refer to other documents (via hyperlinked URLs) w h ich are
similarly processed until the full Web page is rendered.
The servlet ha
issues the
particular se
protocol: it
One of the sim
write a Java
built by MAT
The
and one tha
for what is
creates t
Integrat
1 Overrid
example
API). In
compon
get
doGet c
othebrowser:
e your MATLAB code as follows:
e the default
,class
ent.
s an object that resides on the server. When a servlet is first
erver, it is assigned patterns of URLs which it can process.
s a method on it, called
command for any document matching the pattern assigned to a
rvlet. The
initiates the re ad ing of a document.
plest ways to integrate MATLAB code in a Web contex t is to
servlet, and in its
LAB Builder JA.
ommand is passed two objects: one that represents the request
t represents the response.
needed and use the response object to send back the document it
MyServlet extends HttpServlet (part of the Java Servlets
the
doGet method of MyServlet, you make calls to a deployed
LAB Code on the Web Using Java
doGet. doGet is invoked when a client
get command is one of the most common in the HTTP
doGet method, make calls against an object
doGet must analyze the request object
doGet method provided by the servlet class. For
2-4
In the “De ploy ing a Component withtheMagicSquareExample”,for
example, you instantiate the
(taking care to call the dispose method to release native resource s).
eyourdatatoavirtualfilethatiseither being buffered or being sent
ctly to the client via socket.
dire
The stream output commands in your servlet include the output from
calling the MATLAB function on your component. For example, you might
use the
another type appropriate to your application.
MWArray toString method to convert your MWArraystostringsor
Optimizing Performance of Servlets That Call Your
MATLAB Web Code
doGet is invoked every tim e a get command is received on the server. Thus,
every time a
its
dispose method.
This can quickly impact performance, as it takes time to create an MCR
instance. Y ou can, however, take measures to improve the performance
of your code.
Moving the ownership of the component from the
servlet,soitdoesn’thavetobecreatedand destroyed repeatedly, is a start.
Using HTTPServlet’s init and destroy Methods
HTTPServlet has a set of methods called init and destroy.Theservlet
automatically calls these methods when the servlet is created and destroyed.
get command is received,MagicDemo is instantiated along with
doGet method into the
Page 21
Basics of Web Processing
To take advantage of these methods, you match the scope of
MagicDemoJavaApp to the s cope of the servlet. This renders the lifetime of the
deployed co mponent and its MCR instance as the same as the lifetime of the
servlet. From the first time a user requests a document that matches the
pattern assigned to the servlet, until thetimetheservletisterminatedbyan
administrator, the servlet remains available.
1 Add a property on MyServlet of type magic and instantiate.
Tip As a b est practice, make the instance private. Doing so promotes
data security and integrity.
2 Overload the init method (where you create your servlet).
3 Overload the destroy method (where you issue dispose).
4 Verify your doGet method in your servlet is reentrant—meaning that it
can be ente red simultaneously on multiple threads and processed i n a
thread-safe manner.
Note A Web server that uses servlets to process requests can be termed a
servlet container. The servlet container manages every object scoped to its
class. In this case, the container manages the lifetime of servlets by calling
init and destroy for you. Y ou specify to the container how you want init
and destroy to be executed.
MyServlet.java.
public class MyServlet extends HttpServlet
{
private magic m;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
When working with servlets, you must be extremely a ware of the role scoping
plays in placement of your data.
A scope is a binding of variable to value. In the same scope, a certain name
always refers to a particular binding value.
Every method call generates its own scope. Local variables belong to the
scope of the method invocation.
There are several degrees of scope provided by the Java language:
• Static scope — Bound to the class itself
• Instance scope — Bound to an instance of the class
• Method scope — Bound to local variables tied to a specific method
invocation
When you refer to a variable, the default behavior of the Java compiler is to
first interpret that variable in terms of its most local scope. For example, in
MyOtherServlet.java, note how variables are determined within the scopes
designated by each set of curly braces.
In this example, notice that state which is particular to an individual request
is scoped to the
doGet method itself, rather than the servlet.
To ensure processing is thread-safe, avoid storing data related to state
variables as instance variables on the class itself. Defining too many instance
fields in the class allows state variables to be sh ared by all threads that call
doGet on the same servlet instance. Instead, scope at the method level, using
method parameters, rather than at the class level. This scoping at the method
level also ensures your application scales easily as m ore servers are added.
As discussed in “Optimizing Performance of Servlets That Call Your MATLAB
Web Code” on page 2-6,
document calling
response. However, you may want a different formatted response or you may
want to call
MagicDemoJavaApp with another method to achieve a different
result. To do this, you write
MyServlet takes a request and generates an HTML
MagicDemoJavaApp. This call generates a formatted
myOtherServlet.
Beginbyusingthecodefrom
This time, however, you ins tall
MyServlet as a template for myOtherServlet.
myOtherServlet in the servlet container by
mapping it to another set of URLs.
Clients periodically do
GETs on various URL patterns mapped to each servlet.
While this works well, you can make the process more efficient—note that you
are duplicating work by using two copies of
Because each of the servlets gets their
MagicDemoJavaApp.
init method called separately, each of
these methods initializes a separate MCR instance.
MyOtherServlet.java.
public class MyOtherServlet extends HttpServlet
{
private magic m;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
Context scopes provided by the servlet container can supply convenient
solutions to performance problems such as those described in “Context
Scoping with Serv lets” on page 2-10.
Scopes including multiple servlets are called servlet contexts.Usingaservlet
context, you make the component a shared resource and improve performance
substantially.
1 Obtain the servlet context by calling getServletContext .
2 After you obtain the servlet context, get an attribute (in this case, variables
bound to the servlet context) on the context.
The following logic (shown in
(
MyServlet.java and MyServletContextListener.java), creates a shared
The servlet container also provides a scope that co rresponds to a session
between a particular client and a server. Sin ce HTTP is a very lightweight
protocol and carries no notion of persistence, it follows that session scoping is
particularly useful in retain in g data or state particular to a client. If you have
state that needs to persist across
Single instances of a servlet m ay be used for many clients throughout its
lifetime. Thus,
However, HTTP
response happen within the context of a session between a client and server.
You usually get the
init and destroy have no knowledge of the session context.
request and response objects do, since request and
Session has an API with similar methods to servlet context—setAttribute,
getAttribute, removeAtrribute, and so on. They bind variables that last for
the relationship between a specific client with browser and server.
Sessions usually have time-outs, so they automatically clean up in case the
client doesn’t explicitly log off. This is configurable on the
itself or somewhere in the servlet API.
HTTPSession object
The following logic (shown in
bold type) added to both
MyHttpSessionListener.java and MyServer.java creates your
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.
2-16
The following diagrams depict the supporte d implementation and
architectures available when using MATLAB application deployment
products.
Page 31
Lifecycle of a Deployed MATLAB®Web A ppli c atio n
The fundamental goal of the Application Deployment products (MATLAB
Compiler and the builders) is to enable work that has been accomplished
within MATLAB to be deployed outside the MATLAB environment. This is
accomplished with the MATLAB Compiler R untime (MCR), which is a set of
libraries that runs encrypted MATLAB code.
Page 33
Lifecycle of a Deployed MATLAB®Web A ppli c atio n
In a Web application, the builder products allow integration of the MCR at
the server tier level. This enables end users to execute MATLAB applications
over the Web without installing client software.
WebFigures is a client and server technology that further extends this
capability by enabling end users to interact with a MATLAB figure in
muchthesamewayastheyuseanaxiswithinMATLAB.TheWebFigures
functionality of MATLAB Builder JA and MATLAB Builder NE allows us ers
limited to Web access the ability to dynamically interact with MATLAB
figures.
Creates services out of components
received from the MATLAB programmer
Service consumer responsible for
presentation and usability
No MATLAB experience
External user over the internet
through firewalls
No MATLAB or IT experience
Internal user over the network
Little to no MATLAB or IT experience
Develops model
Uses the builder tools to create a
component that is given to the
business service developer
Creates reusable service that is scalable
Creates front end applications
Customer of the company
User of the site
Employer of the company
User of tools and sites
2-20
General
Developer
End-to-End Developer
MATLAB expert
Creates services out of components
received from the MATLAB programmer
Service consumer responsible for
presentation and usability
Develops model
Uses the builder tools to create a
component that is given to the
business service developer
Creates reusable service that is scalable
Creates front end applications
Page 35
Lifecycle of a Deployed MATLAB®Web A ppli c atio n
MATLAB Programmer
The first phase in a deployed application’s 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.
When MATLAB Builder JA (for Java language) or MATLAB Builder NE
(for Microsoft .NET Framework) is installed along with MATLAB Compiler,
MATLAB functions can be encrypted and wrapped in Java or .NET interfaces.
TheMATLABprogrammertakesthesedeployablecomponentsandgives
them to the business service developer.
Business Service Developer
At this point in the deployment lifecycle, integration is usually required in
order to make the deployed application work with the exis ti ng 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. O nce these services are exposed (either as Web
services or through an API) Front End Developers can connect to them and
use them.
Front-End Developer
Front-end developers are typically responsible f o r user-visible functionality
and know little about under-the-covers implementation. Their primary
concern is the stability and security of the organization’s data within the
confines of a firew all. Once the front-end developers create some mechanism
for exposing the application functionality to the end user, it is up to the end
user to complete the lifecycle by interacting with the application to perform
some task or solve some business problem. External users typically achieve
this through a Web browser.
Server administ
meeting the IT de
outlined in SLA
not know much ab
environments
which computi
can co-exist a
Internal Ana
Internal an
tier direct
a financial
Microsoft
specific t
®
asks not available to their customers.
End-To-E
The end-t
experts
service
vary ove
example
and res
,butarealsoskilledinmanyoftheareasofexpertiseasthebusiness
developer a nd front-end develo per, though their level of expertise may
r thei r many areas of responsibility. To this end, this guide presents
s of comprehensive deployment tasks scoped specifically to the time
ource constraints typically faced by end-to-end developers.
rators are responsible for keeping the servers up and running,
partment’s commitments to the rest of the organization as
agreements. They are not MATLAB experts and may or may
out integrating deployed applications in various computing
. Howev er, they are expert in understanding which versions of
ng environments (JREs and .NET frameworks, for example)
nd run stably in order to achieve the end-user’s desired results.
lyst
alysts may use the Web site or may interact with the business
ly. In this case, an example of a common activity would be when
analyst accesses a business tier Web service and a complex
Excel®model. Or, they access an internal Web site, performing
nd Developer
o-end developers are virtual “one-stop shops.” They are MATLAB
rator
2-22
Page 37
MATLABProgrammer
Tasks
• “Programming in MATLAB” o n page 3-2
• “Deploying MATLAB C ode with the Builders” on page 3-6
3
Page 38
3 MATLAB
®
Programmer Tasks
Programming in MATLAB
MATLAB expert
No IT experience
MATLAB
Programmer
MATLAB is a n i
functions di
Methods may
deploying a
as .NET and J
MATLAB Com
The follow
programm
every way
topics de
For more
documen
Builder
Creati
Virtua
provi
ing examples demonstrate how to perform basic MATLAB
er tasks for de ploy ed applications;theydonotattempttorepresent
a M ATLA B programmer can interface with MATLAB. Upcoming
monstrate how to use various data types in deployed applications.
specific information about an y of th ese data types, see the
tation for the product you are using (MATLAB Compiler, MATLAB
JA, or MATLAB Builder NE)
ng a Deployable MATLAB Function
lly any calculation that you can create in MATLAB can be deployed,
ding it is contained in a function. For example:
No access to IT systems
nterpreted programming environment. You can execute
rectly at the command prompt or throughaneditorinsavedfiles.
be created, having their own unique inputs and outputs. When
MATLAB function to other programming environments, such
ava, you must contain your MATLAB code within functions.
piler does not allow you to use in li n e scripts.
Develops model
Uses the builder tools to create a
component that is given to the
business service developer
3-2
>> 1 + 1
ot be deployed.
cann
ver,
Howe
function result = addSomeNumbers()
result = 1+1;
end
Page 39
Programming in MATLAB
can be deployed, since the calculation now resides in a function.
Taking Inputs into a Function
You typically pass inputs to a function. You can use primitive data type as an
input into a function.
To pass inputs, put them in parentheses. For example:
function result = addSomeNumbers(number1, number2)
result = number1 + number2;
end
Returning Data Types
MATLAB allows many different deployable data types. This section contains
examples of how to work with figures. For an in-depth explanation of how
to work with MATLAB primitive data types, see the MATLAB ExternalInterfaces documentation.
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 “Deploying a Java Co m ponent Over the Web” in the MATLAB Builder
JA User’s Guide or “Deploying a MATLAB Figure Over the Web Using
WebFigures” in the MATLAB Builder NE User’s Guide), the respective
builder marshalls 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. Thisisparticularlyusefulforstreaming 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.
3-3
Page 40
3 MATLAB
®
Programmer Tasks
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.
YoudonotneedtospecifyanyreorientationdatawhenusingWebFigures. 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
Returning a Figure as Data
3-4
This approach is typically used for instances where WebFigures can’t be used,
or in a stateless application.
%We set the figure not to be visible since we are
%streaming the data out
%Notice how you can specify the format of the bytes,
%.net uses unsigned bytes (uint8)
%java uses signed bytes (int 8)
%This function allows you to specify the image format
%such as png, or jpg
function imageByteData = getSurfPeaksImageData(imageFormat)
Sometimes you want the function to change the perspective on an image
before returning it. This can b e accomplished like this:
%We set the figure not to be visible since we are
%streaming the data out
%Notice how you can specify the format of the bytes,
%.net uses unsigned bytes (uint8)
%java uses signed bytes (int 8)
%This function allows you to specify the image format
%such as png, or jpg
function imageData =
Writing the MATLAB code is only the first step when deploying an
application. You must next determine how the application is structured.
Although you might have a large amount of MATLAB code that needs to run
within a component, typically only a small number of entry points need to be
exposed to the calling application. It is best to determine these entry points
and to make sure all inputs and outputs are necessary before deploying a Web
application. ThebestpracticeistoensuretheMATLABfilesthatcontain
methodshavethesamenameastheMATLABfileforallentrypoints.
For examples using the MATLAB Deployment Tool (
“Getting Started” in the MATLAB Builder JA documentation and “Getting
Started” in the MATLAB Builder NE documentation.
ItisalsopossibletousetheMATLAB®Compiler™
components. See the
products for m ore information.
mcc command reference page in any of the builder
deploytool), see
mcc command to build
3-6
Page 43
4
Business Service 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
Page 44
4 Business Service Developer Tasks
Working with the Business Service Layer
In this section...
“About the Business Service Layer” on page 4-2
“About the Examples” on page 4-4
No MATLAB experience
Creates services out of components
Business Service
Developer
received from the MATLAB programmer
About the Bu
Note For c
chapter,
Most soft
busines
access t
Atypic
• Interf
differ
commo
relat
inclu
omprehensive end-to-end implementations of the concepts in this
see Appendix A, “Sources for More Information”.
ware contains a business service layer, which is a set of interfaces,
s objects (and logic to manipulate them), and mechanisms for data
hat run the core business.
al business service layer contains the following sublayers:
aces — Typically the business service layer can implement several
ent interface types which all interact with common data elements and
n business objects, all using the same business logic. Software and
ed services used to access business data from native or Web clients
de:
Creates reusable service that is scalable
siness Service Layer
4-2
- SOAP
- Remo
- HTT
aservlets
- Jav
- JSP
s(forJava)
services
ting interfaces
Pservices
Page 45
Working with the Business Service Layer
- 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 R untime
(MCR).
4-3
Page 46
4 Business Service Developer Tasks
4-4
Elements of the Business Service Layer
About the Examples
Depending on the size and complexity of an implementation some of these
elements can overlap. The examples in this documentation assume direct
communication from the interfaces into the DAO (data access object or
wrapper utility) that you create.
Page 47
Working with the Business Service Layer
All examples in this document are coded as stateless (with the exception of
the M ATLAB 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 se tting. This enables all machines in your Web farm to use the same
session.
4-5
Page 48
4 Business Service Developer Tasks
Creating a DAO for Deployment
To access business objects in .NET and Java environments, you must write a
data access class or classes.
The code in these examples represents what exists within the data access
section of an application since it bridges across MATLAB data and data types
and Java and .NET data types.
Note In these examples, a fake component generated using the M ATLAB
builder products called
imported.
Initializing a Component
Use these examples as a framework for initializing a component.
Java
deploymentExamples is used. Assume it has been
4-6
DeploymentExamples deployment = null;
try
{
deployment = new DeploymentExamples ();
//**************
//Use the deployment code here
//(see examples below)
deployment = new DeploymentExamples.DeploymentExamples();
//******************************
//**Use your deployment code here
//** (See examples below)
//******************************
}
finally
{
deployment.Dispose();
}
Interacting with a Component
You interact with a component by passing inputs to a deployed application
or producing MATLAB output from a deployed application. All of these
examples fit where the comment block resides in “Initializing a Component”
on page 4-6and the same component class is used. The Java and .NE Builder
infrastructure handles data marshalling when passing parameters to a
component. Data conversion rules can be found in the MATLAB builder
documentation. If a specific data type is required, you can use the
objects and pass in the appropriate data type.
MWArray
Converting an Integer to a MATLAB Data Type
Someofthewaystopassinputstoadeployedapplicationsaredemonstrated
in these examples:
Java
intn=3;
MWNumericArray x = new MWNumericArray(n, MWClassID.DOUBLE);
.NET
intn=3;
4-7
Page 50
4 Business Service Developer Tasks
MWNumericArray x = new MWNumericArray(n, true);
Converting Array Data to a MATLAB Data Type
Arrays can be converted to several different MATLAB data types. An example
of converting a String array into a cell array follows:
Java
//Create the array of data
String[] friendsArray1 =
{
"Jordan Robert",
"Mary Smith",
"Stacy Flora",
"Harry Alpert"
};
int numberOfArrayElements1 = friendsArray1.length;
int numberOfArrayColumns1 = 1;
4-8
//Create the MWCellArray to store the data
MWCellArray cellArray1 =
new MWCellArray(
numberOfArrayColumns1,
numberOfArrayElements1);
//Iterate through the array and add the elements to
//the cell array.
for(int i = 1; i<friendsArray1.length+1; i++)
{
cellArray1.set(i, friendsArray1[i-1]);
}
.NET
String[] array =
{
Page 51
"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];
}
Creating a DAO for Deployment
Converting a List to a MATLAB Data Type
A list can be converted to several different MATLAB data type s. An example
of converting a List of Strings into a cell array follows:
Java
//Create a list of data
List friendsList = new LinkedList();
friendsList.add("Jordan Robert");
friendsList.add("Mary Smith");
friendsList.add("Stacy Flora");
friendsList.add("Harry Alpert");
int numberOfListElements = friendsList.size();
int numberOfListColumns = 1;
//Create a MWCellArray to store the data
MWCellArray cellArray2 =
new MWCellArray(
4-9
Page 52
4 Business Service Developer Tasks
//Iterate through the list adding the elements
//to the cell array.
Iterator friendsListItr = friendsList.iterator();
for(int i = 1;friendsListItr.hasNext(); i++)
{
List<String> list = new List<String>();
list.Add("Jordan Robert");
list.Add("Mary Smith");
list.Add("Stacy Flora");
list.Add("Harry Alpert");
numberOfListColumns,
numberOfListElements);
4-10
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++;
}
Page 53
Creating a DAO for Deployment
Converting Name Value Pairs to a MATLAB Data Type
Java (Maps)
It is common to have maps of data (name value pairs). The corresponding
.NET data type is Dictionary. The most similar data type in MATLAB is the
structure. Here is an example where you convert a map of people’s names
into a MATLAB structure.
//First we create a Java HashMap (java.util.HashMap).
Map firendsMap = new HashMap();
friendsList.put( Jordan Robert , new Integer(3386));
friendsList.put( Mary Smith , new Integer(3912));
friendsList.put( Stacy Flora , new Integer(3238));
friendsList.put( Harry Alpert , new Integer(3077));
//Now we set up the MATLAB Structure that we will fill
//with this data.
int numberOfElements = firendsMap.size();
int numberOfColumns = 1;
String[] fieldnames = { name ,phone };
MWStructArray friendsStruct =
new MWStructArray(
numberOfElements,
numberOfColumns,
fieldnames);
//Now we iterate through our map, filling in the structure
char[] charArray = new char[mwCharArray.numberOfElements()];
for(int i = 0; i < charArray.length; i++)
{
char currentChar =
((Character)mwCharArray.get(i+1)).charValue();
charArray[i] = currentChar;
}
}
finally
{
Page 57
Creating a DAO for Deployment
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++)
{
Note This code will not do anything if executed directly. It needs a
response.jsp to produce output.
.NET
For more information about WebFigures, see “Deploying a MATLAB Figure
Over the Web Using WebFigures” in the MATLAB Builder NE User’s Guide.
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.
byte[] byteArray = getByteArrayFromDeployedComponent();
MemoryStream ms = new MemoryStream(myByteArray, 0,
myByteArray.Length);
ms.Write(myByteArray, 0, myByteArray.Length);
return Image.FromStream(ms, true);
}
Page 65
Creating a DAO for Deployment
Getting Image Data from a WebFigure
The following example shows how to get image data from a WebFigure object.
It also shows how to specify the image type and the orientation of the image.
.NET
WebFigure figure =
new WebFigure(deployment.getWebFigure());
WebFigureRenderer renderer =
new WebFigureRenderer();
//Creates a parameter object that can be changed
// to represent a specific WebFigure and its orientation.
//If you dont set any values it uses the defaults for that
// figure (what they were when the figure was created in M).
WebFigureRenderParameters param =
//If you need a byte array that can be streamed out
// of a web page you can use this:
byte[] outputImageAsBytes =
renderer.RenderToEncodedBytes(param);
//If you need a .NET Image (can't be used on the web)
// you can use this code:
Image outputImageAsImage =
renderer.RenderToImage(param);
4-23
Page 66
4 Business Service Developer Tasks
Hosting a DAO on a Web Server
After you construct your DAO, you need to expose the wrapped service(s)
via the Web.
There are many things to consider with regards to exposing the service.
For example, a JSP is not suited for binary streaming since the J2EE
infrastructure already wraps the output stream. In each of the following
sections, some basic concepts that can be used in a realistic system are
demonstrated. Typically, the response is not simply dumped to the output
stream, but instead w rapped in a more complex XML document or Web
service. Using these templates as a guide, you can extend these examples
using similar patterns. For each of these examples, refer to the DAO class
defined in “Creating a DAO for Deployment” on page 4-6. This DAO takes
care of MATLAB specific data conversion and data clean-up tasks.
Hosting the DAO with a Servlet
Note that the DAO is initialized in the init method of the servlet. When you
create and access a component created with the builders, an instance of the
MCR is created that the component communicates with in order to handle
MATLAB tasks. This can incur much overhead if performed every time a user
accesses the servlet. Alternately, byperforminginitializationinthe
method, it is performe d once for all sessions using the servlet. If you w ant to
rebuild e ach time, place the call within a
init
doget method.
4-24
It is also possible that neither of the above approaches will meet your needs
since they initialize once per servlet, rather then once per server. If this is
an issue, use a singleton object that is instantiated in a Context Listener
class (a class that extends
contextInitialized method and a contextDestroyed method which get
called automatically when the server starts or is stopped. This allows all of
your applications to access the singleton and a ccess component objects as
needed.
1 Create a staging folder, if one does not exist, under the folder where your
component resides on your Web server. The DAO must reside in this folder,
in a Java archive file (JAR), on the
2 Initialize the DAO using the following examples as templates:
Note This example allows you to perform similar functionality to
what WebFigures (see “Deploying a Java Component Over the Web”
in the MATLAB Builder JAdocumentation) performs, but in a manual
implementation. It is one of many ways you can implement this
functionality in a stateless manner.
int height = Integer.parseInt(request.getParameter("height"));
int width = Integer.parseInt(request.getParameter("width"));
int elevation =
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
(Web archive) and place it in your Web server’s co m ponent folder.
Note Some Web servers require you to register the application before it is
accessible, usually by referencing the WAR from within the administrator’s
console.
Hosting a DAO Using a Java™ Web Service
More and more companies are hosting services on the Web, often times with
SOAP (Simple Object Acce ss Protocol). This exposes business functions
through simple services. Each of these services performs a specific task.
Since SOAP is an established standard that is supported by many different
languages and third-party applications, it is extremely versatile. You can
use a SOAP Web service directly in Microsoft E xcel with no prior knowledge
of the service’s implementation. Multiple language support makes SOAP
suitable for use with primitive data types.
Although these primitives can be wrapped in a number of complex object
structures, the examples in this section will cover fundamental use cases that
should be the same, regardless of data structure and business objects.
4-31
Page 74
4 Business Service Developer Tasks
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 We b 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.
Setting Up the Root Web Service Class
Since Axis2 supports POJOs (Plain Old Java Objects) you will create a shell
class to contain all the service methods:
package examples;
public class ExamplesWebService
{
//***************************
//**Place service methods here
//**For our examples we will only
//**be taking in and returning
//**primitive values
//***************************
}
4-32
Interacting with the DAO
Some examples of how to use the DAO with various data types follow:
Numeric
public int getInt()
{
Examples examples = new Examples();
int integer = examples.getIntFromMWNumericArray();
examples.dispose();
return integer;
Raw Image Bytes
public byte[] getImageByteArray()
{
Examples examples = new Examples();
byte[] rawImageBytes =
examples.dispose();
return rawImageBytes;
}
Raw Image Bytes with Reorientation
public byte[] reorientAndGetImageByteArray(
int height,
int width,
int elevation,
int rotation,
String imageFormat)
{
Examples examples = new Examples();
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
examples.dispose();
return rawImageBytes;
}
examples.getImageByteArrayFromMWNumericArray();
height,
width,
elevation,
rotation,
imageFormat);
4-34
Deploying the Web Service
1 Create a staging folder, if one does not exist, and copy the Examples DAO
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.
Page 77
Hosting a DAO on a Web Server
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
The services.xml file tells Axis2 which methods to expose, and what
mechanism to u se to expose them.
4 Copy all o f the files into a WAR (Web archive) file and place them in the
axis2 component folder (axis2/WEB-INF/services). Use the java -jar
4-35
Page 78
4 Business Service Developer Tasks
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.
Hosting a .NET DAO with ASPX
Initializing the DAO
Before a DAO can be used, it must be initialized. The basic template to
initialize a .NET DAO looks like this:
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;
4-36
public partial class _Default : System.Web.UI.Page
{
Examples.Examples examples = new Examples.Examples();
//***************************************
//**This is where the examples would be pasted in
//***************************************
//for Examples:
int integer = examples.getIntFromMWNumericArray();
Response.Write("int: " + integer);
examples.dispose();
}
}
Page 79
Hosting a DAO on a Web Server
Interacting with the DAO
Some examples of how to use the DAO with various data types follow:
Numeric
int integer = examples.getIntFromMWNumericArray();
Response.Write("int: " + integer);
// 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 =
YoudeployanASPXusingthePublish functionality in Microsoft® Visual
Studio. Visual Studio puts all of your code, along with any code your project
depends upon, in a folder.
Hosting a DAO Using a .NET Web Service
Setting Up the Root Web Service Class
When creating Web services w ithin .NET, simply create a new Web site (or
use an existing site), and add an item of type
generate the root class in which you place your methods.
Interacting with the DAO
Each of these methods would be placed in the Web service class as methods.
Numeric
Web Service to it. This will
4-40
[WebMethod]
public int getInt()
{
Examples.Examples examples = new Examples.Examples();
int integer = examples.getIntFromMWNumericArray();
examples.dispose();
return integer;
Visual Studio 2005 does all of the work involved with generating Web service
artifacts. Once you’ve created the above methods, just run the service and
you’ll see a tester pag e that shows you the location of the WSDL, and then
allows you to test each method.
4-43
Page 86
4 Business Service Developer Tasks
4-44
Page 87
5
Front-End Developer Tasks
• “Working with the Front-End Layer” on page 5-2
• “Creating a WebFigure on a JSP Page” on page 5-6
• “Creating a WebFigure on an ASPX Page” on page 5-10
• “Working with Static Images” on page 5-13
• “Displaying Complex Data Ty pes Including Arrays and Matrices” on page
5-18
• “Using Web Services” on page 5-26
Page 88
5 Front-End Developer Tasks
WorkingwiththeFront-EndLayer
In this section...
“About the Front-End Layer” on page 5-2
“About the Examples” on page 5-4
Creates front end applications
Front-End
Developer
Service consumer responsible for
presentation and usability
No MATLAB experience
About the Front-End Layer
Note For comprehensive end-to-end implementations of the concepts in this
chapter, see Appendix A, “Sources for More Information”.
In well-designed multi-tier application architectures, the front-end layer
presents data to the end user and validates the user’s input. This is
accomplished by accessing data acquired at lower-level architectural tiers to
the user and taking in user inputs, validating them, and then sending them to
the lower-level tiers for processing.
The data within this layer reside on servers that are almost always outside of
the corporate firewall and therefore, accessible by everyone. Consequently,
security and stability are integral to the front-end layer, and it is important
to isolate implementation details outside of this layer so people cannot
determine how your site is architected.
5-2
A well-designed front-end layer has data access, translation and validation,
and presentation functions separated into individual logical code sections.
This increases an application or Web site’s maintainability since you can
change where the data originates or the format that it arrives in without
changing user-visible code.
A typical front-end layer contains the follow ing sublayers.
Page 89
Work i ng wi th the F r ont -End L aye r
Elements of the Front End Layer
• Data Access — This sublayer pulls data in from middle-tier services like
databases, where access into a deployedapplicationwouldtypicallytake
place. Among the technologies used to transmit data at this sublayer are:
- Remoting interfaces
- SOAP services
5-3
Page 90
5 Front-End Developer Tasks
- XMLoverHTTPprotocol
• Translation/Validation — Data is passed from the data access sublayer
to the translation sublayer and translated into objects used for data
presentation. Since these objects represent what the user sees (rather
than the underlying business logic) t hey are very lightweight and easy to
maintain. This is also where any validation would occur to ensure that
values are in a proper state for processing.
• Presentation — This layer uses the data in the business objects to display
information on a Web site. Any user input actions are validated in the
objects and, if needed, callbacks to themiddlelayeroccurtoretrieve
updates based on the user input.
About the Examples
Dealing with M AT L AB data is, for the most part, no differen t then dealing
with other Web data except for the fact that dynamically generated images
may be involved. The examples in this document are not meant to show how
to build a Web site, but rather to demonstrate what types of building blocks
are neede d to work with M ATLAB data in an existing Web site. Most of these
examples can be integrated directly into larger applications containing JSP,
HTML, or ASPX code.
5-4
Surf Peaks and Magic Square Application Integration
Page 91
Work i ng wi th the F r ont -End L aye r
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 w hich returns a two-dimensional array. It is the front-end layer’s 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-5
Page 92
5 Front-End Developer Tasks
Creating a WebFigure on a JSP Page
There are several ways to use WebFigures on a Web page with Java:
• Return a special HTML string from the servlet which embeds the
WebFigure into a page.
• Using the custom WebFigure tag library directly from the JSP, have the
servlet bind the WebFigure and redirect it to the JSP.
• Generate a string from the middle tier that can be dumped directly onto a
Web page at the front end, embedding all of the WebFigure functionality
and the correct callbacks directly into the front-end page.
In each case, the WebFigure o bject is stored in the Web server’s session. The
Java script that executes the client calls back to the server for updates and,
using the cached WebFigure, new updates are sent back to the client.
Using an HTML String
5-6
This example is very similar to what you can find in “Deploying a Java
Component Over the W eb”, but this example also uses the DAO. The middle
tier code in “Hosting the DAO with a Servlet” on page 4-24 is repeated here:
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",
Page 93
Creating a WebFigure on a JSP Page
new MWHttpSessionBinder(userPlot));
}
Using the WebFigure Tag Library
To use the WebFigure object directly from a JSP page, reference the
webfigures tag library. This creates a WebFigure object with your object’s
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:
Using Embedded HTML
This option is convenient since all of the“heavylifting”isdoneontheserver
and only a string is sent to the front end. In this example, notice how the
servlet is merely referenced and dumps the contents into a Web page frame.
5-7
Page 94
5 Front-End Developer Tasks
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.
To generate this string, run code similar to this on the servlet:
// The argument to the WebFigureHtmlGenerator
// constructor is the URL where the
// WebFigures servlet is mapped (relative to the Web a
// pplication and Servlet context)
WebFigureHtmlGenerator wfHtmlGenerator =
new WebFigureHtmlGenerator("WebFigures",
getServletContext());
String embeddedString;
5-8
try
{
//This generates a string that can be sent to the
// response that represents the WebFigure.
embeddedString =
wfHtmlGenerator.getFigureEmbedString(
There are several ways to use WebFigures on a Web page with .NET:
• Using the
• Using the
WebFigureControl locally in design mode (the easiest approach)
WebFigureControl remotely in design mode
• Returning an HTML string from the ASPX code behind which embeds
the WebFigure into a page.
• Using a
WebFigureControl directly from the ASPX code without utilizing
the designer.
In each case, the WebFigure object is stored in the Web server’s cache. The
JavaScript that executes the client calls back to the server for updates and,
using the cached WebFigure, new updates are sent back to the client. For
more information on these examples, see “Deploying a MATLAB Figure Over
the Web Using WebFig u res”.
For informatio n on how to create the
Studio
®
, see “Quick Start: Implementing a WebFigure”.
WebFigureControl in Microsoft
®
Visual
Using the WebFigureControl Locall y in Design Mode
1 Drag a WebFigureControl from the Microsoft Visual Stud i o Toolbox to
an ASPX page in design mode. This automatically adds a reference to
WebFigureService to your Web site.
2 Edit the code behind the site to attach the figure to the control, as follows:
5-10
gure webFigure =
WebFi
new We
igureControl1.WebFigure = webFigure;
WebF
bFigure(deployment.getWebFigure());
Using the WebFigureControl Remo te ly in Design M ode
1 Drag a WebFigureControl from the Microsoft Visual Studio Toolbox onto
an ASPX page in design mode.
ttheProperties for this figure to point it to a Web site that has
2 Edi
bfigureservice
we
installed and that has attached a WebFigure to the
Page 97
Creating a WebFigure on an ASPX Page
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;
Returning an HTML String from ASPX Cod e to Embed the WebFigure
into a Page.
This example is very similar to what you can find in “Deploying a M ATLAB
Figure Over the Web Using WebFigures”, but this example also uses the
DAO. The middle tier code in “Hosting a .NET DAO with ASPX” on page
4-36 is repeated here:
WebFigure webFigure = new WebFigure(deployment.getWebFigure());
//First we attach the webfigure to one of ASP.NET's caches,
// in this case, the session cache
Session["SessionStateWebFigure"] = webFigure;
//Now 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 =
Using a WebFigureControl Directly from ASPX Code Without Using
the Designer.
To use the WebFigure object directly from an ASPX page, manually write the
code that would otherwise be automatically added to the ASPX page. Writing
the code creates a WebFigure object with your object’s parameters, as in the
following example.
UserPlot is the name of the W eb object that was placed in
There are several options when dealing with images through a component.
YoucansimplysavetheimagefromtheMATLABcodetoadrivesomewhere
using print functionality (the front end references the physical file directly).
This is not ideal since the middle tier is behind the firewall (and the front
end is in front of it), incurring possible security concerns with where the
files reside.
Using Java, you can return a Java image object from MATLAB and use it
directly from the JSP or servlet by saving it to disk or converting it to a byte
stream.
Using a Static Image In a JSP Page
The simplest option is to return a data stream from your MATLAB function as
a byte array — an encoded representation of your image, a common paradigm
used when storing and retrieving images from a database. However, it
is important to consider that only an
data. The most common solution to this issue is to have the
reference a servlet that streams the bytes out through the output stream.
Although direct communication between a presentation object and the middle
tier usually isn’t recommended, in this case it is a good solution. A common
implementation is to designate a server that only serves up images, keeping
data services and image services separate, as shown here:
Image objectsisalmostidenticaltousingHTMLIMG tags. In
ImageUrl (the source of image) to be the ASPX page
created in “Deploying the ASPX” on page 4-40. You can also point to a Java
middle-tier servlet that hosts the image.
<asp:Image
ID="Image1"
5-13
Page 100
5 Front-End Developer Tasks
runat="server"
ImageUrl=
"http://localhost/Examples/Tester.aspx?function=
imageBytesFromMWNumeric" />
Interacting with Images Using JavaScript (for .NET or Java)
Although “Creating a WebFigure on a JSP Page” on page 5-6 is a good solution
for most component models, sometimes a lightweight solution is needed that
you can customize for specific tasks.
JavaScript can be employed to dynamically request new images depending
on user input. Since JavaScript is not Java, it does no t require that Java
Runtime be installed. JavaScript runs in a client’s browser and does not
require a Jav a Web server. You can use this lig htweight implementation
with any of the builders. This example uses the Raw Image Bytes with
Reorientation example in “Hosting a DAO Using a Java™ Web Service” on
page 4-31 and “Hosting the DAO with a Servlet” on page 4-24. It waits for
the user to instigate a m ovement with the mouse (a mouse-drag “event”)
and, when the events occur, calls the server to get a new image of the new
orientation. Thisexample,whilesimple,canbeextendedtodomanyother
types of image interactions.