This is documentation for an earlier version of webMathematica.

 Documentation9. Appendix

A number of Mathematica commands are available for inserting into JSPs that use tags from the MSP Taglib. This section gives a description of each command. It is possible to use and test these commands by using an interactive Mathematica session. Of course, they are designed to work while a web page is being processed, but it can still be useful to get some idea of how they work in a Mathematica session.

This is one of the key ways to work with variables from the HTTP request. MSPBlock takes each of the variables , interprets them, and then replaces any occurrences in body with the interpreted value. If any variables do not have values, an empty string is returned. If a security or parse error is encountered when interpreting the value, an MSPException is thrown.

You can simulate how the functions work by loading the package and setting the security content.

Needs["MSP`"];

SetSecurity[];

Here the variable \$\$var is assigned to the value "5+7"; note that the value is a string.

\$\$var="5+7";

When MSPBlock evaluates, all occurrences of \$\$var are replaced by its interpreted value.

MSPBlock[ {\$\$var}, {Hold[ \$\$var], \$\$var}]

`{Hold[5+7], 12}`

If the input value cannot be interpreted, an MSPException is thrown.

\$\$var="Sin[";

Catch[ MSPBlock[ {\$\$var}, {Hold[ \$\$var], \$\$var}], _MSPException, List]

`{{\$\$var, "Sin["}, MSPException["ParseError"]}`

If the input value does not pass the security test, an MSPException is thrown.

Catch[ MSPBlock[ {\$\$var}, \$\$var], _MSPException, List]

`{{\$\$var, "ReadList[\"/etc/passwd\"]"}, MSPException["SecurityError"]}`

Input can also be given in MathML.

\$\$e = "[itex]<mrow><mi>sin</mi><mo>&af;</mo><mrow><mo>(</mo><mi>x</mi><mo>)</mo></mrow></mrow>
[/itex]";

MSPBlock[ {\$\$e}, \$\$e]

`Sin[x]`

MSPBlock can throw the following exceptions.

MSPException["ParseError"] if the value cannot be interpreted by Mathematica.

MSPException["SecurityError"] if the value does not pass the security test.

MSPException["ValueError"] if the value is not a string. This would indicate a programmatic error by the page author.

MSPException["VariableError"] if the variable is not a Mathematica symbol. This would indicate a programmatic error by the page author.

A number of MSP commands throw an MSPException when some error situation occurs. These are caught by the page processing code, but it would be permissible for a page author to catch them and process them in some intermediate step.

Needs["MSP`"];

If a variable cannot be interpreted, a ParseError exception is thrown. Since the values may be entered from the client, this does not indicate an author error.

Catch[ MSPToExpression["f["], _MSPException, List]

`{{"f[", "f["}, MSPException["ParseError"]}`

If the result of interpretation does not pass the security check, a SecurityError exception is thrown. Since the values may be entered from the client, this does not indicate an author error.

`{{"ReadList[\"/etc/passwd\"]", "ReadList[\"/etc/passwd\"]"}, MSPException["SecurityError"]}`

If a variable that is not a Mathematica symbol is encountered, a VariableError exception is thrown. This usually indicates an author error.

Catch[ MSPValue[x[1]], _MSPException, List]

`{x[1], MSPException["VariableError"]}`

If a value that is not a Mathematica string is encountered, a ValueError exception is thrown. This usually indicates an author error.

\$\$var=Sin[1]

`Sin[1]`

Catch[ MSPToExpression[\$\$var], _MSPException, List]

`{{\$\$var, Sin[1]}, MSPException["ValueError"]}`

Needs["MSP`"];

MSPExportImage[ Graphics[ Line[ {{0, 0}, {1, 1}}]]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_245528838&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

Here MSPExportImage receives a box expression to be rendered into an image.

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_574601872&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

In this example MSPExportImage formats its argument with TraditionalForm before rendering it into an image.

MSPExportImage[ x+Sin[x]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_932131661&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

Here MSPExportImage uses its second argument to specify the image format type.

MSPExportImage[ x+Sin[x], "JPEG"]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_665363422&MSPStoreType=image/jpeg\" alt=\"Created by webMathematica\" /> "`

Since this uses Export, it is possible to set conversion options to control how the image is generated. The actual option settings are documented in the Mathematica help for Export under Further Information. For example, this generates a GIF image for which any white colors will be transparent.

MSPExportImage[ BoxData[ToBoxes[ x+y^2]], "Transparency" -> GrayLevel[1]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_787204206&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

Default values for these options can be set with the variable \$ExportImageOptions. For example, this causes all images to use white as the transparent color.

\$ExportImageOptions="Transparency" -> GrayLevel[1]

`"Transparency" -> GrayLevel[1]`

This is one of the important ways to format results from Mathematica. A more general discussion of output is available in the section on Evaluation Formatting and a discussion on formatting mathematics and graphics is given in the section on Displaying Mathematics and Graphics.

The formatted result can appear in the different format types that Mathematica provides for output. These include OutputForm, InputForm, StandardForm, TraditionalForm, and MathMLForm. In addition the result can be returned as HTML, an image format, or as MathML. You can learn more about Mathematica formatting in The Mathematica Book. The second argument of MSPFormat is a symbol that selects the Mathematica format type, and the third argument is a string that sets the actual content type of the result.

The result of any Mathlet that is not a string is formatted with MSPFormat. You can prepare your own output by generating your own string and not invoking MSPFormat.

In order for the following examples to work, the MSP application must be loaded.

Needs["MSP`"];

MSPFormat will return content in HTML for OutputForm and InputForm. These are string-based formatting types. The result is correctly escaped to be valid HTML that will work in a web page. Note that the result must be displayed in a fixed-width font for correct alignment of multiline output.

MSPFormat[ x +y^2, OutputForm]

`"<p> <code> \n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2<br>x&nbsp;+&nbsp;y\n</code></p>  \n"`

MSPFormat uses an image content for StandardForm and TraditionalForm. It creates and saves an image in a file on the server. An img tag, which can be used to retrieve the image, is then returned as the result.

MSPFormat[ x +y, StandardForm]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_874538807&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

By default the images are GIF format; this can be changed by specifying the format as a third argument. Here the image is stored in JPEG format.

MSPFormat[ x +y, StandardForm, "JPEG"]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_1065528536&MSPStoreType=image/jpeg\" alt=\"Created by webMathematica\" /> "`

It is also possible, though rather strange, to get a text-based format type (for example OutputForm) rendered into an image.

MSPFormat[ x +y, OutputForm, "GIF"]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_1061883558&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

The width that is used for typeset images is set by the variable \$TypesetImageWidth.

If the format is set to MathMLForm, the system will format the expression into MathML.

MSPFormat[ Sin[x]^2, MathMLForm]

`"[itex]\n<mrow>\n  <msup>\n    <mi>sin</mi>\n    <mn>2</mn>\n  </msup>\n  <mo>&af;</mo>\n  <mrow>\n    <mo>(</mo>\n    <mi>x</mi>\n    <mo>)</mo>\n  </mrow>\n</mrow>\n[/itex]"`

In addition you can specify a content type of RawMathML. This can be useful to get the MathML for the StandardForm rendering of an expression. This output is raw in the sense that it does not use any reference to a plug-in, applet, or special browser that would be necessary to activate the MathML.

MSPFormat[ Sin[x]^2, StandardForm, "RawMathML"]

`"[itex]\n<msup>\n  <mrow>\n    <mi>Sin</mi>\n    <mo>&af;</mo>\n    <mrow>\n      <mo>[</mo>\n      <mi>x</mi>\n      <mo>]</mo>\n    </mrow>\n  </mrow>\n  <mn>2</mn>\n</msup>\n[/itex]"`

MSPGetMessages gives a way to obtain any messages that have been generated by evaluations in the current kernel. It returns a list of strings, where each string contains the formatted contents of the message.

This function cannot be demonstrated in a normal evaluation; it must be part of a running server. The example Messages.jsp demonstrates the use of MSPGetMessages.

MSPGetPrintOutput gives a way to obtain the output of all print statements that have been processed by the current kernel. It returns a list of strings, where each string contains the formatted contents of the message.

This function cannot be demonstrated in a normal evaluation; it must be part of a running server. The example Messages.jsp demonstrates the use of MSPGetPrintOutput.

This provides a useful utility function for uploading files from the client to the server using multipart/form-data submissions. The contents of the file are saved in a new file on the server, and the name of this file is returned. The file on the server will eventually be cleared in a way similar to the clearing of image and other temporary files. The result of MSPGetUploadFile is a list of rules that show the filename on the server, the original filename on the client, and the content type.

The function cannot be demonstrated since it must really be part of an actual HTTP transaction with appropriate information sent from the client. This example just simulates the way that the function can be used with Mathematica programming. There are examples of using MSPGetUploadFile in the examples section.

Needs["MSP`"];

`{"FileName"  ->  "MSPStore2349287_0_1",  "OriginalFileName"->"C:\\last.dat",  "ContentType"->"text/plain"}`

The filename can be extracted with the typical Mathematica commands used for working with rules.

"FileName"/.%

`MSPStore2349287_0_1`

Note that parameters that are present in the HTTP headers become available as \$\$ variables after the use of MSPGetUploadFile or MSPGetUploadFileList. After this they can be used in the normal way.

There is a maximum size for a file that can be uploaded by MSPGetUploadFile; by default this is 4MB. If you wish to change this limit you can use the option SizeLimit.

MSPGetUploadFile can throw the following exception.

MSPException["FileUploadError"] in case of some error, for example, if there is not a single file to be uploaded or if the HTTP headers are malformed in some way.

MSPGetUploadFileList is very similar to MSPGetUploadFile, except that it works for several files.

The function cannot be demonstrated since it must really be part of an actual HTTP transaction with appropriate information sent from the client. This example just simulates the way that the function can be used with Mathematica programming.

Needs["MSP`"];

`{{"FileName"  ->  "MSPStore2349287_0_1",  "OriginalFileName"->"C:\\last1.dat",  "ContentType"->"text/plain"}, {"FileName"  ->  "MSPStore2349287_0_2",  "OriginalFileName"->"C:\\last2.dat",  "ContentType"->"text/plain"}}`

Note that parameters that are present in the HTTP headers become available as \$\$ variables after the use of MSPGetUploadFile or MSPGetUploadFileList. After this they can be used in the normal way.

There is a maximum size for a file that can be uploaded by MSPGetUploadFileList; by default this is 4MB. If you wish to change this limit you can use the option SizeLimit.

MSPGetUploadFileList can throw the following exception.

MSPException["FileUploadError"] in case of some error, for example, if there is not a single file to be uploaded or if the HTTP headers are malformed in some way.

MSPInclude allows one page to include the results of processing another page. Because it is not supported in the JSP version of webMathematica, its use is discouraged. Similar functionality can be obtained by using jsp:include.

MSPInclude can throw the following exception.

MSPException["MSPInclude"] in case the function is called from within a JSP.

Needs["MSP`"];

The argument to MSPLive3D must be something that evaluates to a 3D graphics object, such as a Plot3D command.

MSPLive3D[ Graphics3D[ Line[ {{0, 0, 0}, {1, 1, 1}}]]]

`"<applet archive=\"/webMathematica/Resources/applets/live.jar\" code=\"Live.class\" \nwidth=\"400\" height=\"400\" align=\"top\">\n<param name=\"magnification\" value=\"1.\"/>\n<param name=\"input\" value= \"Graphics3D[Line[{{0.,  0.,  0.},  {1.,  1.,  1.}}],  {}]\n\">\n</applet>\n"`

MSPPageDirectory returns the full path of the directory in which the current page is being processed.

Needs["MSP`"];

Integrate[1];

MSPPageDirectory[]

`"C:\\Program Files\\jakarta-tomcat\\webapps\\webMathematica\\Examples"`

MSPPageOptions sets global options concerning the current page. The option ContentType sets the return content type, which is by default text/html. The option MinimumVersion sets the minimum version of the webMathematica technology that can be used for this page.

In this example the ContentType option is set to return MathML. If the browser is configured correctly, it will launch an appropriate MathML helper application.

<msp:evaluate>
MSPPageOptions[ ContentType -> "text/mathml"]
</msp:evaluate>

<msp:evaluate>
MSPFormat[ Integrate[ 1/(1-x^3), x], StandardForm, RawMathML]
</msp:evaluate>

In this example the MinimumVersion option is set to require that the page should be run in webMathematica Version 2.0 or higher. Otherwise an MSPException will be thrown.

<msp:evaluate>
MSPPageOptions[ MinimumVersion -> 2.0]
</msp:evaluate>

This option is provided for use in future versions of webMathematica.

MSPReturn allows a page to return something that is not an HTML result. For example, a page can return a Mathematica notebook directly to the client.

<msp:evaluate>
MSPReturn[ Notebook[ Cell[ "Hello", "Title"]], "application/mathematica"]
</msp:evaluate>

The three-argument form of MSPReturn is useful when you wish to set the filename associated with the response.

<msp:evaluate>
MSPReturn[ Notebook[ Cell[ "Hello", "Title"]],
"application/mathematica", "mynotebook.nb"]
</msp:evaluate>

MSPRootDirectory returns the full path of the root directory of the webMathematica web application.

Needs["MSP`"];

Integrate[1];

MSPRootDirectory[]

`"C:\\Program Files\\jakarta-tomcat\\webapps\\webMathematica"`

This is a utility function for setting the default values of variables.

Needs["MSP`"];

Here \$\$var has a value, so its value is not modified.

\$\$var="5.6";MSPSetDefault[ \$\$var, "foo"];\$\$var

`"5.6"`

If \$\$var has no value, MSPSetDefault will set it.

Clear[\$\$var];MSPSetDefault[ \$\$var, "foo"];\$\$var

`"foo"`

MSPSetDefault can throw the following exceptions.

MSPException["ParseError"] if the value cannot be interpreted by Mathematica.

MSPException["SecurityError"] if the value does not pass the security test.

MSPException["ValueError"] if the value is not a string. This indicates a programmatic error by the page author.

MSPException["VariableError"] if the variable is not a Mathematica symbol. This indicates a programmatic error by the page author.

Needs["MSP`"];

The argument to MSPShow can be something that evaluates to a graphics object, such as a Plot command. Note that the DisplayFunction has been modified to hide actual graphical output at this stage.

MSPShow[ Plot[ Sin[x], {x, 0, 2}]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_448181998&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

MSPShow[ Graphics[ Line[ {{0, 0}, {1, 1}}]]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_490423745&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

MSPExportImage provides an alternative way to generate image output. More information on image generation is available in the section Displaying Mathematics and Graphics: Images. An alternative way to render graphics that does not involve images is to use SVG.

Needs["MSP`"];

MSPShowAnimation[ Table[ Plot[Sin[x+i], {x, 0, 4Pi}], {i, 0., 2Pi-Pi/4, Pi/4}]]

`" <img src=\"/webMathematica/MSP?MSPStoreID=FileNameBase_726239281&MSPStoreType=image/gif\" alt=\"Created by webMathematica\" /> "`

Because generating animated GIFs can be a time-consuming process, it may be necessary to modify the KernelTimeLimit parameter.

MSPShowAnimation uses the Mathematica Export command, which can be modified with a number of options. These are described in the online help for Export under Further Examples. The variable \$ShowAnimationOptions holds the options for MSPShowAnimation. For example, the following causes MSPShowAnimation to generate animations that loop, spending two seconds on each frame.

\$ShowAnimationOptions={"Loop" -> True, "AnimationDisplayTime" -> 2}

`{"Loop" -> True, "AnimationDisplayTime" -> 2}`

SVG provides an alternative way to get animated graphical features.

MSPToExpression is the webMathematica version of ToExpression; it provides the same functionality for turning strings into Mathematica input. However, it provides some additional features. The most important feature is that it carries out a security check on its input. As described in the Security section, webMathematica has a fully configurable security system, which is designed to prevent commands that may pose a security risk. Another difference is that MSPToExpression throws exceptions in cases where its argument cannot be interpreted or the argument is not a string.

You should always use MSPToExpression rather than ToExpression in your code because it provides additional security.

Needs["MSP`"];

SetSecurity[];

Here the variable \$\$var is assigned to the value "5+7"; note that the value is a string.

\$\$var="5+7";

When MSPToExpression evaluates, the parsed value of \$\$var is returned.

MSPToExpression[ \$\$var]

`12`

If a variable has no value, an MSPException is thrown.

Clear[ \$\$var];MSPToExpression[ \$\$var]

`Hold[Throw[\$\$var, MSPException["NoValueError"]]]`

Like ToExpression, MSPToExpression can take a format type for interpretation.

`Sin[x]`

If the input value cannot be interpreted, an MSPException is thrown.

\$\$var="Sin[";Catch[ MSPToExpression[ \$\$var], _MSPException, List]

`{{\$\$var, "Sin["}, MSPException["ParseError"]}`

If the input value does not pass the security test, an MSPException is thrown.

`{{\$\$var, "ReadList[\"/etc/passwd\"]"}, MSPException["SecurityError"]}`

Input can also be given in MathML.

\$\$e = "[itex]<msqrt><mfrac><mi>x</mi><mi>y</mi></mfrac></msqrt>[/itex]";

MSPToExpression[ \$\$e]

`xy`

MSPToExpression can be used on strings that are computed from input.

\$\$e="a, b, c";MSPToExpression["{"<>\$\$e<>"}"]

`{a, b, c}`

MSPToExpression can throw the following exceptions.

MSPException["NoValueError"] if the variable does not have a value. This indicates a programmatic error by the page author.

MSPException["ParseError"] if the value cannot be interpreted by Mathematica.

MSPException["SecurityError"] if the value does not pass the security test.

MSPException["ValueError"] if the value is not a string. This would indicate a programmatic error by the page author.

MSPException["VariableError"] if the variable is not a Mathematica symbol. This indicates a programmatic error by the page author.

MSPURLStore stores a string of formatted data in the MSP servlet and returns a URL that can be used to retrieve the data. It is an extension of the mechanism for storing images. It can be used to hold input for some plug-in or applet in the client or it could be formatted into img tag.

Needs["MSP`"];

m=DisplayString[Graphics[Line[ {{0, 0}, {1, 1}}]], "JPEG"];

MSPURLStore[m, "image/jpeg"]

`"/webMathematica/MSP?MSPStoreID=FileNameBase_97360396&MSPStoreType=image/jpeg"`

The result is a string that can be used as a URL referring to the MSP servlet, which can be used to retrieve the data from the store.

A third argument to MSPURLStore sets a filename in the URL. There are several uses for this functionality, such as choosing a helper application for the client. Note that no actual file with this name is created. The name is just placed in the URL.

MSPURLStore[m, "image/jpeg", "file.gif"]

`"/webMathematica/MSP/file.gif?MSPStoreID=FileNameBase_846174849&MSPStoreType=image/jpeg"`

This topic is discussed further in the Returning General Content section. You should remember that the result of MSPURLStore can be embedded in other formatting functions as described in the section MSP Functions Returning Images.

This is a utility function that is useful for extracting the value of variables.

Needs["MSP`"];

The value of the variable \$\$expr is returned.

\$\$expr=56;MSPValue[ \$\$expr]

`56`

If \$\$expr has no value, then a null string is returned.

Clear[\$\$expr];MSPValue[ \$\$expr]

`""`

Here a default value is returned.

Clear[\$\$expr];MSPValue[ \$\$expr, "x+y"]

`"x+y"`

MSPValue can throw the following exceptions.

MSPException["ValueError"] if the value is not a string. This would indicate a programmatic error by the page author.

MSPException["VariableError"] if the variable is not a Mathematica symbol. This would indicate a programmatic error by the page author.

This is a utility function that tests whether variables have values.

Needs["MSP`"];

The variable \$\$expr has a value, so the result is True.

\$\$expr=56;MSPValueQ[ \$\$expr]

`True`

Now \$\$expr has no value, so the result is False.

Clear[\$\$expr];MSPValueQ[ \$\$expr]

`False`

All of the variables must have values for MSPValueQ to return True.

\$\$expr=56;Clear[ \$\$var];MSPValueQ[ \$\$expr, \$\$var]

`False`

\$ExportImageOptions holds the options used for generating images when MSPExportImage is used. This uses the Mathematica Export command, and the possible options are described in the online help for Export under Further Examples. In this example the options are set to indicate that white is transparent; this gives the image a transparent background. The default value of \$ExportImageOptions is {}.

<msp:evaluate>
Block[{MSP`Utility`ImageQuality=2,
\$ExportImageOptions={"Transparency" -> GrayLevel[1]}},
MSPExportImage[ Plot[Sin[x], {x, 0, 2Pi}, Background->GrayLevel[1]]]
]
</msp:evaluate>

\$MSPFormatType is the default format type used by MSPFormat. The default value is OutputForm.

Expressions are formatted with the page width set by the variable \$PageWidth. The default value is 78.

\$PathInfo is a Mathematica variable that holds the setting of the path information for the request.

\$QueryString is a Mathematica variable that holds the setting of the query string for the request.

\$ScriptName is a Mathematica variable that holds the name of the top-level script. Note that this can also be given as a parameter on the URL.

\$ShowAnimationOptions keeps options used for generating animated GIFs with MSPShowAnimation. These are the options that are passed to the Mathematica Export command and are described in the online help for Export under Further Examples. In this example, the animation is set to loop with a time of two seconds between each frame. (It uses Block to restore the option setting after the computation has finished.) The default value of \$ShowAnimationOptions is {Loop -> True}.

<msp:evaluate>
Block[{\$ShowAnimationOptions=
{"Loop" -> True, "AnimationDisplayTime" -> 2}},
MSPShowAnimation[ Table[Plot[Sin[x+i], {x, 0, 2Pi}],
{i, 0, 2Pi-Pi/\$\$n, Pi/10}]]
]
</msp:evaluate>

\$TypesetImageWidth sets the width in pixels for images of typeset expressions. The default value is 800.

\$WebApplication gives the name of the web application in which webMathematica has been installed. Normally this is "/webMathematica", but it could be different. Using this definition allows you to write portable code, which is easier to move from one web application to another.

Needs["MSP`"];

\$WebApplication

`"/webMathematica"`