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 wrapped 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. 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, by performing initialization in the init method,
it is performed once for all sessions using the servlet. If you want
to rebuild each time, place the call within a doget method.
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 ServletContextListener).
This class has a 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 access component objects as needed.
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 class path
so it can be imported.
Initialize the DAO using the following examples as
templates:
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)
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());
}
}
}
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]);
}
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);
}
Byte Array
byte[] byteArray = examples.getByteArrayFromMWNumeric();
response.getOutputStream().println("Byte Array: ");
for(int i = 0; i<byteArray.length;i++)
{
response.getOutputStream().print(byteArray[i]);
}
response.getOutputStream().write(byteArray);
Images (WebFigures)
This example is very similar to Deploying a Java Component Over the Web, but this
example also uses our DAO.
HttpSession session = request.getSession();
WebFigure userPlot =
(WebFigure)session.getAttribute("UserPlot");
// if this is the first time doGet has been called
// for this session,
// create the plot and WebFigure object
if (userPlot== null)
{
userPlot = examples.getWebFigureFromMWJavaObjectRef();
// store the figure in the session context
session.setAttribute("UserPlot", userPlot);
// bind the figure's lifetime to the session
session.setAttribute(
"UserPlotBinder",
new MWHttpSessionBinder(userPlot));
}
WebFigureHtmlGenerator webFigureHtmlGen =
new WebFigureHtmlGenerator("WebFigures",getServletContext());
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");
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArrayWithOrientation(
height,
width,
elevation,
rotation,
imageFormat);
response.getOutputStream().write(rawImageBytes);
Inside the staging folder you created at the start
of this procedure, create a WEB-INF folder.
Inside the WEB-INF folder, create
two additional folders:
Place all of the class files (including the DAO created
in Creating a DAO for Deployment)
into the class folder within the appropriate package
folders that exist.
Copy the component JAR file into the lib folder.
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>
</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.
Using the java -jar command, bundle
the folders you created into a WAR (Web archive) and place it in your
Web server's component 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. |
Back to Top
Hosting a DAO Using
a Java™ Web Service
More and more companies are hosting services on the Web, often
times with SOAP (Simple
Object Access 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 Excel 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.
In this section, you will learn how to create basic Java objects
that handle business logic, while Apache Axis2 performs the mechanics
involved with turning the logic a Web service and exposing it. Alternatively,
you can start by using WSDL (Web Service Definition Language —
the definition of your service) and generate Java from that. Afterward
you can customize the Java with your business logic, or change the
WSDL manually in a number of other ways to meet your needs.
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
//***************************
}
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;
}
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;
}
Raw Image Bytes
Raw Image Bytes
public byte[] getImageByteArray()
{
Examples examples = new Examples();
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray();
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(
height,
width,
elevation,
rotation,
imageFormat);
examples.dispose();
return rawImageBytes;
}
Deploying the Web Service
Create a staging folder, if one does not exist, and
copy the Examples DAO class created in Creating a DAO for Deployment and the
Web service class created in Setting Up the Root Web Service Classinto it.
Create a lib folder and copy
your deployed component into it.
Create a meta-inf folder and, inside
it, create a services.xml file with these contents:
<service>
<parameter name="ServiceClass"
locked="false">examples.ExamplesWebService</parameter>
<operation name="getInt">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getString">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getIntArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getCharArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getByteArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
<operation name="getImageByteArray">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</operation>
</service>
The services.xml file tells Axis2 which methods
to expose, and what mechanism to use to expose them.
Copy all of the files into a WAR (Web archive) file
and place them in the axis2 component folder (axis2/WEB-INF/services).
Use the java -jar command but give the output file
an .aar extension rather than a .jar extension.
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.
Back to Top
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;
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();
}
}
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]);
}
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]);
}
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);
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);
Deploying the ASPX
You deploy an ASPX using the Publish functionality
in Microsoft® Visual Studio. Visual Studio puts all of your code,
along with any code your project depends upon, in a folder.
Back to Top
Hosting a DAO Using
a .NET Web Service
Setting Up the Root Web Service Class
When creating Web services within .NET, simply create a new
Web site (or use an existing site), and add an item of type Web
Service to it. This will 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
[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;
}
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;
}
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;
}
Raw Image Bytes
[WebMethod]
public byte[] getImageByteArray()
{
Examples.Examples examples = new Examples.Examples();
byte[] rawImageBytes =
examples.getImageByteArrayFromMWNumericArray();
examples.dispose();
return rawImageBytes;
}
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 page that shows
you the location of the WSDL, and then allows you to test each method.
Back to Top
 | Creating a DAO for Deployment | | Front-End Developer Tasks |  |
Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
Get the Interactive Kit