Mathworks MATLAB APPLICATION DEPLOYMENT Web Example Guide

Page 1
MATLAB®Applicati
Web Example Guide
on Deployment
Page 2
How to Contact The MathWorks
www.mathworks. comp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html T echnical Support
suggest@mathworks.com Product enhancement suggestions bugs@mathwo doc@mathworks.com Documentation error reports service@mathworks.com Order status, license renewals, passcodes info@mathwo
com
rks.com
rks.com
Bug reports
Sales, prici
ng, and general information
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
© COPYRIGHT 2008–20 10 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 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 2008 Online only New for MATLAB®Compiler™ Version 4.8 (Release
October 2008 Online only Revised for MATLAB
R2008a)
R2008b)
March 2009 Online only Revised for MATLAB
R2009a)
September 2009 Online only Revised for MATLAB
R2009b)
March 2010 Online only Revised 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
vi Contents
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
viii Contents
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
Software Roles
MATLAB, Compiler
Business
MATLAB
Programmer
Java Builder
.NET Builder
Integration Experts End User End-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 to Web Concepts and 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
2
Page 16
2 Web101: AnIntroductiontoWebConceptsandTerminology
Why Learn About Web Concepts and Terminology?
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.
2-3
Page 18
2 Web101: AnIntroductiontoWebConceptsandTerminology
Integrating MAT Servlets
A Java™ servlet i placed on a Web s
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).
2 Writecodetorespondtotheclientrequest. Atminimum,youmustatleast
set the content type (HTML, for example).
3 Writ
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
MagicDemoJavaApp component inside doGet
Page 19
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;
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 magicm=newmagic();
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'>");
Basics of Web Processing
2-5
Page 20
2 Web101: AnIntroductiontoWebConceptsandTerminology
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);
}
} finally {
m.dispose();
}
} catch (MWException e) {
throw new ServletException(e);
}
}
}
2-6
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 {
try {
m = new magic();
2-7
Page 22
2 Web101: AnIntroductiontoWebConceptsandTerminology
} catch (MWException e) {
throw new ServletException(e);
}
}
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
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);
}
2-8
Page 23
Basics of Web Processing
}
@Override
public void destroy() {
m.dispose();
}
}
Maintaining Data Integrity Through Proper Scoping
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.
2-9
Page 24
2 Web101: AnIntroductiontoWebConceptsandTerminology
Context Scoping with Servlets
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 {
try {
m = new magic();
} catch (MWException e) {
throw new ServletException(e);
}
}
2-10
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
try {
Page 25
final Object[] results = m.makesqr(1, (int)(Math.random() * 10 + 11));
try {
final MWArray firstResult = (MWArray)results[0];
response.setContentType("text/html");
{
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);
}
}
Basics of Web Processing
@Override
public void destroy() {
2-11
Page 26
2 Web101: AnIntroductiontoWebConceptsandTerminology
m.dispose();
}
}
Improving Performance with Servlet Contexts
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
bold type) added to each serv let
MagicDemoInstance:
MyServletContextListener.java.
import magicsquare.magic;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
import com.mathworks.toolbox.javabuilder.MWException;
public class MyServletContextListener implements ServletContextListener {
static final String SHARED_MAGIC_INSTANCE = "SharedMagicInstance";
public void contextInitialized(final ServletContextEvent event) {
final ServletContext context = event.getServletContext();
try {
final magicm=newmagic();
2-12
Page 27
context.setAttribute(SHARED_MAGIC_INSTANCE, m);
} catch (MWException e) {
context.log("Error creating magicsquare.magic", e);
}
}
public void contextDestroyed(final ServletContextEvent event) {
final ServletContext context = event.getServletContext();
final magic m = (magic)context.getAttribute(SHARED_MAGIC_INSTANCE);
m.dispose();
}
}
Code Excerpt from MyServlet.java.
@Override
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws ServletException, IOException
{
final HttpSession session = request.getSession();
final ServletContext context = session.getServletContext();
final magic m =
Basics of Web Processing
(magic)context.getAttribute(MyServletContextListener.SHARED_MAGIC_INSTANCE);
Session Scoping with Servlets
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
HTTPSession object from the request.
requests, the proper context is the Session.
2-13
Page 28
2 Web101: AnIntroductiontoWebConceptsandTerminology
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
MATLAB component at the
session scope.
MyHttpSessionListener.java.
import magicsquare.magic;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import com.mathworks.toolbox.javabuilder.MWException;
public class MyHttpSessionListener implements HttpSessionListener {
static final String SHARED_MAGIC_INSTANCE = "SharedMagicInstance";
public void sessionCreated(final HttpSessionEvent event) {
final HttpSession session = event.getSession();
try {
final magicm=newmagic();
session.setAttribute(SHARED_MAGIC_INSTANCE, m);
} catch (MWException e) {
session.getServletContext().log("Error creating magicsquare.magic", e);
}
}
2-14
public void sessionDestroyed(final HttpSessionEvent event) {
final HttpSession context = event.getSession();
final magic m = (magic)context.getAttribute(SHARED_MAGIC_INSTANCE);
m.dispose();
}
Page 29
Basics of Web Processing
}
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
Page 30
2 Web101: AnIntroductiontoWebConceptsandTerminology
Lifecycle of a Deployed MATLAB Web Application
In this section...
“Introduction” on page 2-16
“MATLAB Web Application Environment” on page 2-18
“MATLAB Programmer” on page 2-21
“Business Service Developer” on page 2-21
“Front-End Developer” on page 2-21
“Server Administrator” on page 2-22
“Internal Analyst” on page 2-22
“End-To-End Developer” on page 2-22
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.
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
Deployed Application Tier Interactions
2-17
Page 32
2 Web101: AnIntroductiontoWebConceptsandTerminology
Multi-tier large implementation
Front end tier servers
Middle tier servers
External end user
via browser
(no MCR)
Firewall
Internet
Load
balancer
External facing web
servers (no MCR)
Internal end user
via browser
(no MCR)
Single-tier small implementation
Internal end user
via browser (no MCR)
Internal facing
web server
(behind firewall)
Firewall
Router
Load
balancer
Front end and
middle tier servers
MCR
MCR
MCR
2-18
Internal end user
via browser (no MCR)
End-to-end
MATLAB programmer
MATLAB Web Application Environment
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.
2-19
Page 34
2 Web101: AnIntroductiontoWebConceptsandTerminology
Role ResponsibilitiesKnowledge Base
MATLAB
Business
Programmer
Business Service
Developer
Integration Experts
Front End
Developer
External
User
End User
Internal
Analyst
MATLAB expert
No IT experience
No access to IT systems
No MATLAB experience
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.
2-21
Page 36
2 Web101: AnIntroductiontoWebConceptsandTerminology
Server Administ
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
MATLAB Programmer 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 External Interfaces 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)
f = figure; surf(peaks); set(f, `Visible', `off'); imageByteData = figToImStream(f, imageFormat, `uint8'); close(f);
end
Page 41
Programming in MATLAB
Reorienting a Figure andReturningItasData
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 =
getImageDataOrientation(width, height, rotation,
elevation, imageFormat) f = figure(`Position', [0, 0, width, height]); surf(peaks); view([rotation, elevation]); set(f, `Visible', `off'); imageData = figToImStream (f, imageFormat, `uint8'); close(f);
end
3-5
Page 42
3 MATLAB
®
Programmer Tasks
Deploying MATLAB Code with the Builders
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)
//************** } catch(MWException mw_ex) {
mw_ex.printStackTrace(); } finally {
deployment.dispose(); }
Page 49
Creating a DAO for Deployment
.NET
DeploymentExamples.DeploymentExamples deployment = null; try {
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++) {
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");
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
Iterator friendsMapItr = friendsMap.keySet().iterator(); for(int i = 1; friendsMapItr.hasNext(); i++) {
String key = (String)friendsMapItr.next(); friendsStruct.set(fieldnames[0], i,
new MWCharArray(key));
friendsStruct.set(fieldnames[1], i (Integer)
friendsMap.get(key));
}
4-11
Page 54
4 Business Service Developer Tasks
.NET (Dictionaries)
Dictionary<String, int> dictionary =
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(
int i = 1; foreach (String currentKey in dictionary.Keys) {
output[fieldnames[0], i] = currentKey; output[fieldnames[1], i] = dictionary[currentKey]; i++;
}
new Dictionary<String, int>();
numberOfElements,
numberOfColumns,
fieldnames);
4-12
Getting MATLAB Numerics from a Deployed Application
This code resides in the try block for an initialized component (se e “Initializing a Component” on page 4-6).
Java
Object[] numericOutput = null; MWNumericArray numericArray = null; try {
numericOutput = deployment.getNumeric(1); numericArray = (MWNumericArray)numericOutput[0]; int i = numericArray;
Page 55
Creating a DAO for Deployment
} finally {
MWArray.disposeArray(numericArray);
}
.NET
MWNumericArray result = (MWNumericArray)deployment.getNumeric(); int resultInt = result.ToScalarInteger();
Getting MATLAB Strings from a Deployed Application
Java
Object[] stringOutput = null; MWCharArray stringArray = null; try {
stringOutput = deployment.getString(1); stringArray = (MWCharArray) stringOutput [0];
String s = stringArray; } finally {
MWArray.disposeArray(stringArray); }
.NET
MWCharArray result = (MWCharArray)deployment.getString(); String resultString = result.ToString();
Getting MATLAB Numeric Arrays from a Component
Java
Object[] numericArrayOutput = null;
4-13
Page 56
4 Business Service Developer Tasks
MWNumericArray numericArray1 = null; try {
numericArrayOutput = deployment.getNumericArray(1);
numericArray1 = (MWNumericArray)numericArrayOutput[0];
int[] array = numericArray1.getIntData(); } finally {
MWArray.disposeArray(numericArray1); }
.NET
MWNumericArray result =
Double[] doubleArray =
(MWNumericArray)deployment.getNumericArray();
(Double[])result.ToVector(MWArrayComponent.Real);
4-14
Getting Character Arrays from a Component
Java
Object[] stringArrayOutput = null MWCharArray mwCharArray = null; try {
stringArrayOutput = deployment.getStringArray(1);
mwCharArray = ((MWCharArray)stringArrayOutput[0];
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++) {
outputArray[i] = resultArray[0, i]; }
Getting Byte Arrays from a Component
Java
Object[] byteOutput = null; MWNumericArray numericByteArray = null;
try {
byteOutput = deployment.getByteArray(1);
numericByteArray = (MWNumericArray)byteOutput[0];
byte[] byteArray = numericByteArray.getByteData(); } finally {
MWArray.disposeArray(numericByteArray); }
.NET
MWNumericArray result =
4-15
Page 58
4 Business Service Developer Tasks
byte[] outputByteArray =
Getting Cell Arrays from a Component
Java
This example shows how to iterate through a cell array and put the elements into a list or an array:
Object[] cellArrayOutput = null; MWCellArray cellArray = null; try {
cellArrayOutput = deployment.getCellArray();
cellArray = (MWCellArray)cellArrayOutput[0];
List listOfCells = new LinkedList();
Object[] arrayOfCells =
(MWNumericArray)deployment.getByteArray();
(byte[])result.ToVector(MWArrayComponent.Real);
new Object[cellArray.numberOfElements()];
4-16
for(int i = 0; i < cellArray.numberOfElements(); i++)
{
Object currentCell = cellArray.getCell(i + 1);
listOfCells.add(currentCell); arrayOfCells[i] currentCell;
} } finally {
MWArray.disposeArray(cellArray); }
.NET
MWCellArray result = (MWCellArray)deployment.getCellArray();
List<Object> outputList = new List<Object>();
Page 59
Creating a DAO for Deployment
Object[] outputArray = new Object[result.NumberOfElements]; for (int i = 0; i < result.NumberOfElements; i++) {
outputArray[i] = result[i + 1];
outputList.Add(result[i + 1]); }
Getting Structures from a Component
Java
Object[] structureOutput = deployment.getStruct(1); MWStructArray structureArray =
(MWStructArray)structureOutput[0];
try {
Object[] structureOutput = deployment.getStruct(1);
structureArray = (MWStructArray)structureOutput[0];
Map mapOfStruct = new HashMap();
for(int i = 0; i < structureArray.fieldName().length(); i++)
{
String keyName = structureArray.fieldNames()[i]; Object value = structureArray.getField(i + 1);
mapOfStruct.put(keyName, value);
} } finally {
MWArray.disposeArray(structureArray); }
.NET
MWStructArray result = (MWStructArray)deployment.getStruct();
4-17
Page 60
4 Business Service Developer Tasks
Dictionary<Object, Object> output =
for (int i = 0; i < result.FieldNames.Length; i++) {
output.Add(result.FieldNames[i],
result.GetField(result.FieldNames[i])); }
Getting a WebFigure from a Component and Attaching It to aPage
Java
For more information about WebFigures, see “Deploying a Java Component Over the Web” in the MATLAB Builder JA User’s Guide.
Object[] webFigureOutput = null; MWJavaObjectRef webFigureReference = null;
new Dictionary<Object, Object>();
4-18
try {
webFigureOutput = deployment.getWebFigure(1);
webFigureReference = (MWJavaObjectRef)webFigureOutput[0];
WebFigure f = (WebFigure)webFigureReference.get(); } finally {
MWArray.disposeArray(webFigureOutput);
MWArray.disposeArray(webFigureReference); }
//forward the request to the View layer (response.jsp) RequestDispatcher dispatcher =
request.getRequestDispatcher( /response.jsp ); dispatcher.forward(request, response);
Page 61
Creating a DAO for Deployment
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.
String localEmbedString =
WebFigureServiceUtility.GetHTMLEmbedString(
"SessionStateWebFigure", WebFigureAttachType.session, 300,
300);
Response.Write(localEmbedString);
Getting Encoded Image Bytes from an Image in a Component
Java
public byte[] getByteArrayFromDeployedComponent()
4-19
Page 62
4 Business Service Developer Tasks
{
}
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); }
4-20
.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,
Page 63
imageFormat);
return (byte[])result.ToVector(MWArrayComponent.Real);
}
GettingaBufferedImageinaComponent
Java
public byte[] getByteArrayFromDeployedComponent() {
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
);
Creating a DAO for Deployment
numericImageByteArray = (MWNumericArray)byteImageOutput[0];
return numericImageByteArray.getByteData(); } finally {
MWArray.disposeArray(byteImageOutput); }
}
public BufferedImage getBufferedImageFromDeployedComponent() {
try {
byte[] imageByteArray = getByteArrayFromDeployedComponent()
return ImageIO.read(new ByteArrayInputStream(imageByteArray));
4-21
Page 64
4 Business Service Developer Tasks
}
.NET
public byte[] getByteArrayFromDeployedComponent() {
}
} catch(IOException io_ex) {
io_ex.printStackTrace(); }
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);
4-22
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);
}
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 =
new WebFigureRenderParameters(figure);
param.Rotation = 30; param.Elevation = 30; param.Width = 500; param.Height = 500;
//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:
ServletContextListener). This class has a
class path so it can b e imported.
Page 67
Hosting a DAO on a Web Server
Initializing the DAO for a Servlet
package examples;
import java.io.IOException; 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.util.*; import com.mathworks.toolbox.javabuilder.webfigures.WebFigure;
public class ExamplesServlet extends HttpServlet {
Examples examples = null;
public void init(ServletConfig config) throws
ServletException
{
super.init(config);
try {
examples = new Examples();
} catch(Exception e) {
e.printStackTrace();
}
}
public void destroy() {
super.destroy(); examples.dispose();
}
protected void doGet(final HttpServletRequest request,
HttpServletResponse response)
4-25
Page 68
4 Business Service Developer Tasks
throws ServletException, IOException {
try {
//***********************************
//**All code using the DAO would go here
//**Any of the below examples can be pasted here
//***********************************
int integer = examples.getIntFromMWNumericArray();
response.getOutputStream().println("int: " + integer);
} catch(Exception e) {
e.printStackTrace();
response.getOutputStream().println("ERROR "+
e.getMessage());
}
}
}
4-26
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]);
}
Page 69
Hosting a DAO on a Web Server
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]);
}
Cell Array To Array
Object[] array = examples.getArrayFromCellArray(); for(int i = 0; i < array.length; i++) {
response.getOutputStream().println("Array index("+ i+"): " +
array[i]);
}
Cell Array To List
List list = examples.getListFromCellArray(); Iterator listItr = list.iterator(); while(listItr.hasNext()) {
response.getOutputStream().println("List Item: " +
listItr.next());
}
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
Page 70
4 Business Service Developer Tasks
Byte Array
Images (WebFigures)
This example is very similar to “Deploying a Java Component Over the Web”, but this example also uses our DAO.
}
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);
HttpSession session = request.getSession();
WebFigure userPlot =
(WebFigure)session.getAttribute("UserPlot");
4-28
// 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());
Page 71
Hosting a DAO on a Web Server
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);
Raw Image Bytes
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray();
response.getOutputStream().write(rawImageBytes);
Raw Image Bytes with Reorientation
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 =
Integer.parseInt(request.getParameter("elevation"));
int rotation =
Integer.parseInt(request.getParameter("rotation"));
String imageFormat = request.getParameter("imageFormat");
4-29
Page 72
4 Business Service Developer Tasks
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 package folders that exist.
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
height, width, elevation, rotation, imageFormat);
response.getOutputStream().write(rawImageBytes);
class folder within the appropriate
4-30
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://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ExamplesServlet
</servlet-name>
<servlet-class>examples.ExamplesServlet
</servlet-class>
Page 73
Hosting a DAO on a Web Server
</servlet> <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
(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;
}
Page 75
Hosting a DAO on a Web Server
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
Page 76
4 Business Service Developer Tasks
Raw Image Bytes
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
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 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 {
protected void Page_Load(object sender, EventArgs e) {
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);
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]);
}
Cell Array to Array
Object[] array = examples.getArrayFromCellArray(); for (int i = 0; i < array.Length; i++) {
Response.Write("Array index("+ i+"): " + array[i]);
4-37
Page 80
4 Business Service Developer Tasks
}
Cell Array to List
List<Object> list = examples.getListFromCellArray(); foreach (Object currentObj in list) {
Response.Write("List Item: " + currentObj);
}
Structure
Dictionary<Object, Object> dictionary =
examples.getDictionaryFromStruct(); Response.Write("Structure Array: "); foreach (Object currentKey in dictionary.Keys) {
Response.Write("Key: " + currentKey + " Value: " +
}
dictionary[currentKey]);
4-38
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);
Raw Image Bytes
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray(); Response.BinaryWrite(rawImageBytes);
Page 81
Hosting a DAO on a Web Server
Raw Image Bytes with Reorientation
Note This example allows you to perform similar functionality to what
WebFigures performs, but in a manual implementation. It is one of many ways you can implement this functionality in a stateless manner.
int height = Convert.ToInt32(Request.Params.Get("height")); int width = Convert.ToInt32(Request.Params.Get("width")); int elevation =
Convert.ToInt32(Request.Params.Get("elevation")); int rotation = Convert.ToInt32(Request.Params.Get("rotation")); String imageFormat = Request.Params.Get("imageFormat"); byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
height, width, elevation, rotation, imageFormat);
Response.BinaryWrite(rawImageBytes);
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
Page 82
4 Business Service Developer Tasks
Deploying the ASPX
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;
}
String
[WebMethod] public String getString() {
Examples.Examples examples = new Examples.Examples(); String stringResult = examples.getStringFromMWCharArray(); examples.dispose(); return stringResult;
}
Page 83
Hosting a DAO on a Web Server
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 can’t 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
Page 84
4 Business Service Developer Tasks
}
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
Raw Image Bytes
[WebMethod] public byte[] getImageByteArray() {
Examples.Examples examples = new Examples.Examples(); byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray(); examples.dispose(); return rawImageBytes;
}
Page 85
Hosting a DAO on a Web Server
Raw Image Bytes with Reorientation
[WebMethod] public byte[] getImageByteArrayWithOrientation(
int height, int width, int elevation, int rotation, String imageFormat)
{
Examples.Examples examples = new Examples.Examples(); byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
height, width, elevation, rotation,
imageFormat); examples.dispose(); return rawImageBytes;
}
Deploying the Web Service
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
parameters. The
UserPlot isthenameoftheWebobjectthatyouplacedin
thecachebythemiddletier.
Note HostthemiddletierandtheJSPonthesameserver.
<%@ taglib prefix="wf"
uri="http://www.mathworks.com/builderja/webfigures.tld" %>
< wf:web-figure
name="UserPlot" scope="session" root="WebFigures" width="100%" height="100%"/>
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
RequestDispatcher dispatcher = request.getRequestDispatcher("/response.jsp"); dispatcher.forward(request, response);
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.
<iframe
src ="http://localhost:8080/Examples/ExamplesServlet?
function=webFigureEmbedded" width="590" height="480">
</iframe>
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(
userPlot, "UserPlot", "session", null, null,
null)); } catch(MWException mwe) {
Page 95
Creating a WebFigure on a JSP Page
throw new Exception(); }
response.getOutputStream().println(embeddedString);
5-9
Page 96
5 Front-End Developer Tasks
Creating a WebFigure on an ASPX Page
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 =
WebFigureServiceUtility.GetHTMLEmbedString(
"SessionStateWebFigure", WebFigureAttachType.session,
5-11
Page 98
5 Front-End Developer Tasks
300,
300);
Response.Write(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
thecachebythemiddletier.
<%@ Register Assembly="WebFiguresService, Version=2.8.1.0,
Culture=neutral, PublicKeyToken=e1d84a0da19db86f"
Namespace="MathWorks.MATLAB.NET.WebFigures.Service"
TagPrefix="cc1" %>
<cc1:WebFigureControl
ID="WebFigureControl1" runat="server" Height="328px" Width="399px" Root="" Scope="session" Name="UserPlot" />
5-12
Page 99
Working with Static Images
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:
Working with Static Images
IMG tag’s source can be set, not it’s
IMG tag’s source
<img src="http://localhost:
8080/Examples/ExamplesServlet?function= imageBytesFromMWNumeric" alt="MATLAB IMAGE" />
Using a Static Image in a ASPX Page
Using ASPX this case, simply set the
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.
5-14
<iframe
src ="DynamicFigure.html?url=
http://localhost:8080/Examples/ExamplesServlet?function=
imageBytesFromMWNumericWithOrientation" width="700" height="700">
</iframe>
DynamicFigure.html
is an AJAX application that takes in a parameter (the
base function that returns an image) and accepts different orientation values:
<%@ page contentType=
"text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored ="false"%> <html>
<head>
<title>AJAX Figure Manipulation</title>
Loading...