Mathematica 9 is now available
8.6 Example MSP Scripts

Documentation8. Classic webMathematica Technology

 

8.6 Example MSP Scripts

These are a collection of sample MSP scripts, each of which will demonstrate some detail or feature. The sources for all these examples are included in the Mathematica MSP application in the directory MSPScripts/Examples.

8.6.1 A Beginning: Hello.msp

If you installed webMathematica as described previously, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Hello. (You may have some other URL for accessing your server.)

This example evaluates the Date[] function of Mathematica. The result changes each time the page is accessed, demonstrating that this really is a dynamic process. The server sees the request for Hello and searches for an MSP called Hello.msp. The source for this page is in MSPScripts/Examples/Hello.msp.

<html>
<head>
<title>Hello World (MSP)</title>
</head>
<body>
<h1>Hello World (MSP)</h1>
<h4>Date[]</h4>
<%Mathlet Date::usage %>
<p>Its current value is:</p>
<%Mathlet Date[] %>
</body>
</html>

This is standard HTML, except for the two Mathlet tags <%Mathlet expr %>. Mathematica replaces each Mathlet with the result of evaluating and formatting its contents. This builds a new HTML document, which is then returned to the client.

Of course, this example is not interesting, because the user is not doing anything other than retrieving a page. For interactive behavior, a user needs to send input values with the request. The next example, Variables.msp, discusses this further.

8.6.2 Working with Variables: Variables.msp

If you installed webMathematica as described earlier, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Variables. (You may have some other URL for accessing your server.) It demonstrates how variables are connected to input values. The source for this page is in MSPScripts/Examples/Variables.msp.

<html>
<head>
<title>Assigning Variables</title>
</head>
<body>
<h1>Assigning Variables</h1>
<form action="Variables" method="post">
Enter something:
<input type="text" name="input" size="10">
<br>
<%Mathlet $$input %>
<br>
<input type="submit" name="submitButton" value="Evaluate">
</form>
</body>
</html>

This page is more elaborate because it contains form and input elements. These are important ways for allowing interaction from the client.

A form element is a block of HTML that may contain input elements. A form may be activated with an input of type submit; this sends the name and value associated with each input tag to the server. Here, the opening tag of the form element contains two attributes. The action attribute refers to a URL that is accessed when the form is activated. In this case, it is a relative URL that refers to the original Variables script. The method attribute tells the browser what HTTP method to use—in this case, a post method. (It is very common to use post methods.)

This example has two input tags: the first allows the user of the page to enter text, and the second specifies a button that, when pressed, will submit the form. When the form is submitted, it will send information from input elements to the URL specified by the action attribute (in this case, the same MSP). Information entered by the user is sent to a Mathematica kernel and assigned to a Mathematica symbol. The name of the symbol is given by prepending $$ to the value of the name attribute. Here the name attribute is input, and the Mathematica symbol $$input is assigned to the contents of the input element.

The first time the page is accessed there is no value for $$input. When a value is entered in the text field and the Evaluate button pressed, the text is displayed. Note that the value is a Mathematica string—if you enter an input such as "5+7", no computation is actually done. If you want the input to be interpreted and evaluated by Mathematica, you need to use one of the MSP functions.

You can distinguish between Mathematica symbols that get definitions from the server versus other symbols because the former all receive a $$ prefix. This is necessary to make sure that symbols from the server, such as those from an image map, do not collide with regular Mathematica symbols.

8.6.3 Using MSP Functions: Expand.msp

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Expand. (You may have some other URL for accessing your server.) It allows a polynomial and an exponent to be entered. When the submit button is pressed, the polynomial is raised to the power and expanded, and an HTML page that contains the result is returned. The source for this page is in MSPScripts/Examples/Expand.msp.

<html>
<head>
<title>Expanding Polynomials</title>
</head>
<body>
<h1>Expanding Polynomials</h1>
<form action="Expand" method="post">
Enter a polynomial (e.g. x+y):
<input type="text" name="expr" size="10">
Enter a positive integer (e.g. 4):
<input type="text" name="num" size="3">
<br>
<%Mathlet
MSPBlock[{$$expr, $$num},
Expand[$$expr^$$num]] %>
<br>
<input type="submit" name="submitButton" value="Evaluate">
</form>
</body>
</html>

This page contains form and input tags as described in the previous example. Additionally, the Mathlets refer to Mathematica functions that are not in standard usage.

When the form is submitted, the server connects to a Mathematica kernel, in which two symbols, $$expr and $$num, are assigned to the text from the two input elements. If no text is entered, the symbols will not have any definition.

Mathematica now evaluates the Mathlet. The MSPBlock command is a programming construct, which here inspects two variables, $$expr and $$num. If either of these has no value, MSPBlock returns a null string, which is why the first time you access the page, you do not see a result. The values of both variables are then interpreted by Mathematica. If successful, the results of interpretation are substituted into the second argument or body of MSPBlock. In this example, all instances of $$expr are substituted with the parsed value of $$expr, and the same is done for $$num. The result is then evaluated, formatted, and placed in the HTML page, which is returned to the client.

Interpretation of the variables by Mathematica can fail in two ways: the input might not be valid Mathematica input (for example, f[}), or it might be some dangerous input (such as ReadList["/etc/passwd"]). In both cases, the inputs are rejected and an error message generated. This demonstrates some of the security features of the system, which the Security section documents in detail.

8.6.4 Graphics: Plot.msp

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Plot. (You may have some other URL for accessing your server.) It allows the user to enter a function to be plotted. The source for this page is in MSPScripts/Examples/Plot.msp.

<html>
<head>
<title>Plot</title>
</head>
<body>
<h1>Plot</h1>
<form action="Plot" method="post">
Enter a function:
<input type="text" name="fun" size="24"
value="<%Mathlet MSPValue[ $$fun, "Sin[x]^2"] %>">
Enter a number:
<input type="text" name="x1" size="24"
value="<%Mathlet MSPValue[ $$x1, "10"] %>">
<br/>
<%Mathlet
MSPBlock[{$$fun, $$x1},
MSPShow[Plot[$$fun, {x, 0, $$x1}]]] %>
<hr/>
<input type="submit" name="btnSubmit" value="Evaluate">
</form>
</body>
</html>

In this example, the two text input elements use Mathlets to fill in values when the page is first requested. It is often useful to suggest input and also to preserve input that was previously entered. These use MSPValue, which returns the value of the variable in the first argument, or the second argument if the variable has no value. This demonstrates a new use of a Mathlet: to provide inline expansion for a quoted attribute value. Mathlets are evaluated completely out of context for the syntax of the page, and can go anywhere, supplying any part of the text of the page.

The third Mathlet then evaluates. The MSPBlock makes sure that both $$fun and $$x1 have valid values, which are used in the Plot command. MSPShow saves an image on the server and returns the necessary HTML to refer to this image. You may wish to use the View Source option of your browser to see how the page refers to the image. The image uses a GIF format; it is possible to save images in other formats, such as JPEG, by setting a third argument. The MSP Function Reference section documents this feature.

8.6.5 Typeset Images: Integrate.msp

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Integrate. (You may have some other URL for accessing your server.) It allows the user to enter a function to be integrated. The result is then formatted by the typesetting system and saved as an image. The source for this page is in MSPScripts/Examples/Integrate.msp.

<%Mathlet
   integrand = Null;
   If[ MSPValueQ[ $$expr],
      integrand = MSPToExpression[ $$expr]] ;
%>

<html>
<head>
<title>Integration</title>
</head>
<body>
<h1>Integrate a function</h1>
<form action="Integrate" method="post">Input:
<br>
<input type="text" name="expr" size="24"
value="<%Mathlet MSPValue[ $$expr, "Sin[x]^2"] %>">
<br/>
<%Mathlet
If[ integrand =!= Null, MSPFormat[Integrate[integrand, x], StandardForm] %>
<br/>
<input type="submit" name="btnSubmit" value="Evaluate">
</form>
</body>
</html>

In this example, a Mathlet integrates an expression and uses MSPFormat to format the result with StandardForm. This generates an image and returns a reference to the image. For this to work, it is necessary to use the Mathematica front end.

The example also demonstrates the use of page scoped variables with MSPToExpression. This is an alternative to the use of MSPBlock that is a bit more complicated but also more expressive. The page variable integrand is initialized to Null, and later, if its value has been modified, the integration is carried out. It is assigned to the interpreted value of $$expr only if this input variable actually has a value. Note that if an error, such as a security error, is encountered in interpreting $$expr, an exception will be thrown and integrand will not be assigned to a new value. An alternative to scoping a variable to a page is to scope to a session, which is possible with MSPSessionVariable.

8.6.6 Live 3D Plotting: Plot3DLive.msp

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Plot3DLive. (You may have some other URL for accessing your server.) It allows the user to enter a function to be plotted by the LiveGraphics3D applet. The source for this page is in MSPScripts/Examples/Plot3DLive.msp.

<html>
<head>
<title>Live 3D Plotting</title>
</head>
<%Mathlet $ImageBackground = "#ffffff"; $ImageSize = {300, 300}; %>
<body bgcolor = "#ffffff">
<h1>Live 3D Plotting</h1>
<form action="Plot3DLive" method="post">
Plot3D of
<input type="text" name="fun" size="22" value =
"<%Mathlet MSPValue[ $$fun, "Sin[x y]^2"] %>">
<br/>
x from:
<input type="text" name="x0" size="10" value =
"<%Mathlet MSPValue[ $$x0, "-2"] %>">
to:
<input type="text" name="x1" size="10" value =
"<%Mathlet MSPValue[ $$x1, "2"] %>">
<br/>
y from:
<input type="text" name="y0" size="10" value =
"<%Mathlet MSPValue[ $$y0, "-2"] %>">
to:
<input type="text" name="y1" size="10" value =
"<%Mathlet MSPValue[ $$y1, "2"] %>">
<br/>
Number of points to plot:
<input type="text" name="pts" size="5" value =
"<%Mathlet MSPValue[ $$pts, "20"] %>">
<br/>
<%Mathlet
    MSPBlock[ {$$fun, $$x0, $$x1, $$y0, $$y1, $$pts},
         MSPLive3D[
            Plot3D[$$fun, {x, $$x0, $$x1}, {y, $$y0, $$y1},
PlotPoints -> $$pts]]] %>
<br/>
<input type="submit" name="btnSubmit" value="Evaluate">
</form>
</body>
</html>

This example uses a number of Mathlets to set up parameters. The last Mathlet takes the values of these parameters and uses them in a call to Plot3D. The result of this is used by MSPLive3D to call the LiveGraphics3D applet. This gives a real-time rotation of the three-dimensional graphics object.

8.6.7 Returning General Content: Content.msp

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/Content. (You may have some other URL for accessing your server.)

All of the examples up to this point return HTML to the browser, but the web can work with general content involving many different formats. MSPReturn is provided to allow an MSP script to return arbitrary content. Here is an example that demonstrates how different formats can be returned. The source is in MSPScripts/Examples/Content.msp and MSPScripts/Examples/Content.m.

First, here is the source of the MSP script.

<html>
<head>
<title>General Content</title>
</head>
<body bgcolor="#ffffff">
<h1>General Content</h1>
<form action="Content" method="post">
<p>
This example generates a notebook, converts it into a specific format and returns
that format.
</p>
<%Mathlet
    If[ MSPValueQ[ $$button],
       Get[ "Content.m"];
       MSPReturn @@ GeneralContent[ $$button]] %>
<br>
<input type="Submit" name="button" value="Notebook">
<input type="Submit" name="button" value="PostScript">
<input type="Submit" name="button" value="GIF">
</form>
</body>
</html>

Here is the Mathematica source.

MakeNotebook[] :=
UseFrontEnd[
Module[ {nb, nbobj},
nb = NotebookCreate[] ;
NotebookWrite[ nb, Cell[ "A Dynamically Created Notebook", "Title"]] ;
NotebookWrite[ nb,
Cell[ "Converted to " <> $$button, "Subtitle"]] ;
NotebookWrite[ nb, Cell[ "The date is " <> ToString[ Date[]], "Text"]] ;
nbobj = NotebookGet[ nb] ;
NotebookClose[ nb] ;
nbobj]]


GeneralContent[ fmt_] :=
Module[ {nbobj},
nbobj = MakeNotebook[] ;
UseFrontEnd[
Switch[
fmt,
"Notebook",
{ToString[ nbobj, InputForm],
"application/mathematica"},
"PostScript",
{DisplayString[ nbobj, "EPS"],
"application/eps"},
"GIF",
{DisplayString[ nbobj, "GIF"],
"image/gif"},
_, "Unknown format"]
]]

In this example one evaluation tests the variable $$button. If it has a value from activating one of the buttons in the form, this is used to specify a return format type and passed to a function GeneralContent. The Mathematica code for this function is placed into a separate package to be loaded when the variable is set. GeneralContent calls a function that creates a simple notebook, MakeNotebook. MakeNotebook generates a notebook using the Mathematica Notebook API and the J/Link function UseFrontEnd. In a real life situation, it would be written to build a more interesting notebook. MSPReturn returns the representation of the notebook to the server with the content type. This is then returned to the browser, which, if suitably configured, will deploy the necessary helper application.

In a real example, a dynamically generated notebook would probably use information sent with the request from the client.

If you wish to return special content and also set a filename to be used with this content, then you may wish to use the three-argument form of MSPReturn. This is described in the Mathematica Function Reference section.

Another way to set the content returned from an MSP script is to use MSPPageOptions. The topic of returning general content is discussed earlier.

8.6.8 Applets: TextApplet.msp

This example demonstrates how to call on the services of a Mathematica-powered web site from an applet. This shows a combination of client and server programming. The section involves some programming in Java.

If you installed webMathematica as described previously, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/TextApplet. (You may have some other URL for accessing your server.) The source for this page is in MSPScripts/Examples/TextApplet.msp and in webMathematica/WEB-INF/src/ExampleApplets/TextApplet.java.

First, here is the source of the MSP script.

<%Mathlet
If[ MSPValueQ[ $$Compute],
MSPReturn[ "Date[] returns " <> ToString[ Date[]], "text/plain"]] %>
<html>
<title>Applet Test</title>
<body>
<p>
Here is an applet that gets a result from Mathematica:
<br>
<applet CODE="TextApplet.class"
archive = "<%Mathlet $WebApplication <> "/Resources/applets/MSPExamples.jar" %> "
width=400
height=30>
<param name="ArgumentURL" Value="TextApplet?Compute=True">
</applet>
<p>
Hitting refresh will cause the page to update.
</body>
</html>

Here is the source for the applet, TextApplet.java.

import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;
public class TextApplet extends Applet
{
public void paint(Graphics g)
{
super.paint(g);
try {
URL url=new URL(getDocumentBase(), getParameter("ArgumentURL"));
InputStream in=url.openStream();
ByteArrayOutputStream out=new ByteArrayOutputStream();
byte[] b=new byte[1024]; int len;
while((len=in.read(b, 0, 1024)) != -1) {
out.write(b, 0, len);
}
b=out.toByteArray();
g.drawBytes(b, 0, b.length-1, 20, 20);
}
catch (Exception e) {
System.out.println("Error "+e);
}
}
}

This is a very simple applet; the paint method opens a connection to a URL, the name of which is formed from the document that loaded the applet, and the value of the parameter ArgumentURL, which is passed in from a param tag. This causes the TextApplet MSP script to be called and return a computation of the date.

8.6.9 Calling Back to Java: Request.msp

This example demonstrates how an MSP script can call on Java, a feature provided by J/Link. This allows Mathematica to call Java and Java to call Mathematica. It also allows Mathematica called from Java itself to call back into Java. The J/Link manual contains more information on this feature. This example requires some knowledge of Java.

The example demonstrates how to call methods on the HttpServletRequest object, a Java object used by the servlet engine to hold information on the HTTP request. You can learn more about the HttpServletRequest from books on servlets or by looking at the servlet API, documented at http://java.sun.com/products/servlet/.

If you installed webMathematica as described above, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/PlotScript. (You may have some other URL for accessing your server.) The source for this page is in MSPScripts/Examples/PlotScript.msp and in MSPScripts/Examples/PlotScript1.msp.

Here is the source for Request.msp.

<html>
<head>
<title>Request Information</title>
</head>
<body bgcolor="#ffffff">

<h1>Request Information</h1>

<h4>HTTP Method</h4>

<%Mathlet $ServletRequest@getMethod[] %>

<h4>Header Names and Values</h4>

<%Mathlet
   JavaBlock[
      Block[
         {headers, res, $PathWidth = 100},
         headers = $ServletRequest@getHeaderNames[] ;
         res = Rest[
            NestWhileList[
               Module[ { name = headers@nextElement[]},
                  {name, $ServletRequest@getHeader[name]}] &,
               1, headers@hasMoreElements[] &]] ;
         MSPFormat[ TableForm[res ], OutputForm]
         ]
      ]
    %>
</body>
</html>

The first Mathlet calls the getMethod method of the $ServletRequest object, and this returns the HTTP method, such as GET, that was used. The second Mathlet has some more sophisticated code that uses a Java Enumeration (returned by getHeaderNames) to extract the names and values of the headers. This is returned, formatted by TableForm.

8.6.10 Uploading a File: UploadFile.msp

This example demonstrates how to upload a file to a webMathematica server.

If you installed webMathematica as described earlier, you should be able to connect to this MSP script via http://localhost:8080/webMathematica/MSP/Examples/UploadFile. (You may have some other URL for accessing your server.) There are two scripts involved. The first has a form for submitting the file, and the second reads the file and displays its contents. The sources are in MSPScripts/Examples/UploadFile.msp and MSPScripts/Examples/UploadFileAction.msp. A portion of UploadFile.msp is shown below.

<form method=post enctype="multipart/form-data" action="UploadFileAction">
<p>
Enter a file to upload:
</p>
<br/>
   <input type="file" size=40 name="file">
<br/>
<br/>
   <input type="reset" value="Clear">
   <input type="submit" value="Submit">
</form>

This is really an HTML page since it contains no Mathematica computations. It is written as an MSP so that it can reference UploadFileAction.msp conveniently. It uses a multipart/form-data form element, which is the standard way to submit a file. The form is submitted to UploadFileAction.msp, which is shown below.

<html>
<head>
<title>Upload File Action</title>
</head>
<body>
<p>
File contents:
</p>
<br>
<pre>
<%Mathlet
   file = "FileName" /. MSPGetUploadFile[];
   Read[ file, Record, RecordSeparators-> {}]
%>
</pre>

<p>
<a href="UploadFile">Upload another file?</a>
</p>

</body>
</html>

This uses the function MSPGetUploadFile, which uploads the file and saves it on the server. It returns a list of useful information, including the filename which is used on the server, the original filename used on the client, and the content-type. In a case where there is more than one file to be uploaded, MSPGetUploadFile will throw an exception. If you wish to upload more than one file, you can use MSPGetUploadFileList. In this example here, the contents of the file are then read and displayed. Of course, it would be simple to use some other importing function, and then do some computation.



Any questions about topics on this page? Click here to get an individual response.Buy NowMore Information
THIS IS DOCUMENTATION FOR AN OBSOLETE PRODUCT. CURRENT WEBMATHEMATICA DOCUMENTATION IS NOW AVAILABLE.