11.07.2015 Views

webMathematica™ Wolfram - Wolfram Research

webMathematica™ Wolfram - Wolfram Research

webMathematica™ Wolfram - Wolfram Research

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Wolfram</strong> webMathematica USER GUIDE


For use with <strong>Wolfram</strong> webMathematica 3.0 and higher.For the latest updates and corrections to this manual:visit reference.wolfram.comFor information on additional copies of this documentation:visit the Customer Service website at www.wolfram.com/services/customerserviceor email Customer Service at info@wolfram.comComments on this manual are welcomed at:comments@wolfram.comPrinted in the United States of America.15 14 13 12 11 10 9 8 7 6 5 4 3 2 1©2009 <strong>Wolfram</strong> <strong>Research</strong>, Inc.All rights reserved. No part of this document may be reproduced or transmitted, in any form or by any means,electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the copyrightholder.<strong>Wolfram</strong> <strong>Research</strong> is the holder of the copyright to the various <strong>Wolfram</strong> Mathematica software systems ("Software")described in this document, including, without limitation, such aspects of the system as its code, structure, sequence,organization, "look and feel", programming language, and compilation of command names. Use of the Softwareunless pursuant to the terms of a license granted by <strong>Wolfram</strong> <strong>Research</strong> or as otherwise authorizedby law is an infringement of the copyright.<strong>Wolfram</strong> <strong>Research</strong>, Inc. and <strong>Wolfram</strong> Media, Inc. ("<strong>Wolfram</strong>") make no representations, express,statutory, or implied, with respect to the Software (or any aspect thereof), including, without limitation,any implied warranties of merchantability, interoperability, or fitness for a particular purpose, all of whichare expressly disclaimed. <strong>Wolfram</strong> does not warrant that the functions of the Software will meet yourrequirements or that the operation of the Software will be uninterrupted or error free. As such, <strong>Wolfram</strong>does not recommend the use of the software described in this document for applications in which errorsor omissions could threaten life, injury or significant loss.Mathematica and MathLink are registered trademarks of <strong>Wolfram</strong> <strong>Research</strong>, Inc. J/Link, MathLM, .NET/Link, <strong>Wolfram</strong>Workbench, gridMathematica,and webMathematica are trademarks of <strong>Wolfram</strong> <strong>Research</strong>, Inc. Windows is a registeredtrademark of Microsoft Corporation in the United States and other countries. Macintosh is a registered trademark ofApple Computer, Inc. All other trademarks used herein are the property of their respective owners. Mathematica isnot associated with Mathematica Policy <strong>Research</strong>, Inc.1550362 0909.JP


webMathematica Users GuideIntroduction to webMathematicaWhat Is webMathematica? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Why Use Mathematica in a Website? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Interactive Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2The Mathematica Front End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Mathematical Typesetting and MathML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Why a Web Interface? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Ease of Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Server-Based Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Web Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Areas of Use for webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Web Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4Education . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Publishing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5<strong>Research</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6Hobbyist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6webMathematica Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9New Features of webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9webMathematica 3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9webMathematica 2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11webMathematica 2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11webMathematica 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12webMathematica 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


InstallationSetting Up a Servlet Container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Setting Up Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Setting Up Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Installing and Configuring Mathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Installing the webMathematica Web Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Other Servlet Engines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Configuring for the X Window System (Unix only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Configuring Xvnc and webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24Install Xvnc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Launch Xvnc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Test Xvnc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Configure webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Other X Related Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Connecting to the X Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Xvfb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27Manual Font Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Upgrading from webMathematica 2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Install Mathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Install the webMathematica Web Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Configure the New Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30web.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30MSPConfiguration.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Security Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Move Content to the New Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Finalize the Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Optional Further Configuring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31MSP Mathematica Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Launching webMathematica Automatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


Web Server Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Apache and Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Microsoft Servers and Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Basic ExamplesHello.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40Working with Variables: Variables.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41MSP Functions: Expand.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Graphics: Plot.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44Typeset Images: Integrate.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Live 3D Plotting: Plot3DLive.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47Getting Messages: Messages.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Returning General Content: Content.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Interactive Web: SliderPlot.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54Applets: TextApplet.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55JavaScript: PlotScript.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57Setting Variables: SetBasic.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Getting Variables: GetBasic.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60Developing Your Own Pages<strong>Wolfram</strong> Workbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62Tips and Tricks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Coding in Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Browse Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Design Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66Banners and Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Minimal Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Minimal File Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67


ApplicationsXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Introduction to XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68XML Compliance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Mathematica Support for XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70webMathematica XML Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71MathML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Embedding MathML in Web Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74XHTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74XHTML and MathML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Rendering XHTML and MathML Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Generating MathML from webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79MathML Integrate Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Plotting with SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84SVG Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84HTML Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86The HTML Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86HTMLTableForm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87HTMLFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88HTMLSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89HTMLCheckBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90webMathematica Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Table Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91Select Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92Interactive Web Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Example: SliderPlot.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95Formatting and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Underlying Technology and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Using Java APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Server APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97Other Java APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98Data Loading and Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99HTTP Upload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101


Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Data Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Loading Data: Load.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Uploading Data: Upload.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102Session Storage of Data: Session.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Database Connections: Database.jsp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107Mathematica Packages and Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108Loading Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108Writing Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Installing Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112webMathematica Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112$BaseDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112$UserBaseDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112The Script Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112$TopDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Absolute Filename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Extended Page Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113Expression Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113JSP Standard Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115choose/when/otherwise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115Queuing of Long Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116Interacting with the Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117Lifetime of a Queued Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Organizing and Configuring a Queued Pool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120Alternative Server Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120JavaServer Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121PDF Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121Generating a Mathematica Notebook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Converting to PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Returning PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123Creating PDF Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124Returning General Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124Direct Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125MSPReturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125MSPURLStore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126


AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127Time Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127HTML Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130Web Services and XML Exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Informal Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134AJAX Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134Mathematica SOAP Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136webMathematica SOAP Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Echo Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Plot Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140Excel Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142Type Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Simple Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146Date and Time Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147Binary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148SchemaExpr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148SchemaMathML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152Advanced TopicsVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Input Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155Interpretation of Input Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156Interpreted versus Noninterpreted Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157MSPBlock versus MSPToExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158Page Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159Session Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Server Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Mathematica Program Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161MSPBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162MSPToExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162Avoid ToExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163


Security Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163The Validation Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163Configuring a Security Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165ToExpression Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166Security and Kernel Pools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166Access Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166Evaluation Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167Automatic Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167MSPFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167Graphics and Image Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Suppressing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Multiple Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Multiple Kernel Pools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Multiple Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170Mapping URLs onto JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170Handling Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Catching Mathematica Error Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171Adding an HTTP Error Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Displaying Mathematics and Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172MSP Functions Returning Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173LiveGraphics3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174Including Static Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174TroubleshootingInitial Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176Check the Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176Check the URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176Check the Initial Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Check the Kernel Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Check the Logging System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Check the Console Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Check Mathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178Specific Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178Problems Running the Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178Problems Running the Front End . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Problems Testing Xvnc (Unix only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Problems Testing Xvfb (Unix only) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Images Do Not Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180


Images Do Not Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Mathematica Packages and Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Kernel Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180Vertical Alignment in Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Timeout Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181UnsatisfiedLinkError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Cannot Load JLink` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182NoClassDefFoundError: TryCatchFinally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182NoClassDefFoundError: JLink Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182NoSuchMethodError: KernelData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Debugging webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Not Using <strong>Wolfram</strong> Workbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Using <strong>Wolfram</strong> Workbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184webMathematica Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Server Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185The Kernel Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186Reporting Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186ConfigurationCheckToExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191CollectStreams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192FileUploadSizeLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193FrontEndExecutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194FrontEndLaunchFlags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195JlinkNativeLibraryDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196KeepFrontEndAlive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197KernelAcquireCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198KernelAcquireLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199KernelBaseMemoryLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200KernelConnectLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201KernelDestroyCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202KernelExecutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203KernelInitializeCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204KernelLaunchFlags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205KernelNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206KernelPeakMemoryLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207KernelPool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208


KernelPool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208KernelPoolName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209KernelReleaseCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210KernelTimeLimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211SecurityConfigurationFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212URLPattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214FunctionsHTMLCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217HTMLFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219HTMLSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221HTMLTableForm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224MSPBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227MSPException . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230MSPFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232MSPGetMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235MSPGetPrintOutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236MSPGetUploadFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237MSPGetUploadFileList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239MSPLive3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241MSPManipulate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242MSPManipulateHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248MSPPageDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249MSPPageOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250MSPReturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252MSPRootDirectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254MSPSessionVariable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255MSPSetDefault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256MSPShow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258MSPToExpression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259MSPURLStore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262MSPValue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264MSPValueQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266


GuidesConfiguration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272webMathematica Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273Processing Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274Web Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275webMathematica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276Tagsevaluate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279evaluateQueued . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284AppendixProcessing a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287Mathematica Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289webMathematica Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290Request Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290evaluate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292Request Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295evaluateQueued . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296Mathematica Web Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297Processing Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298Web Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298Site Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299MSPConfiguration.xml . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299Logging System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Security Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301X Server Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301


LiveGraphics3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302Dynamic HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304Server Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304Client Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Mathematica Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Mathematica Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Servers JSPs and Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Web Browser Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311XML, MathML, and SVG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311PDF Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312The X Window System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312


Introduction to webMathematicaThis document provides a guide to the installation and operation of webMathematica and thedevelopment of a webMathematica site.This introduction considers the reasons for using Mathematica in a website, examines a fewareas in which you might use webMathematica, briefly discusses the underlying technology, andoutlines the requirements for running webMathematica.What Is webMathematica?webMathematica adds interactive calculations and visualization to a website by integratingMathematica with the latest web server technology. The diagram below shows a view of awebMathematica site, http://library.wolfram.com/explorations/webUnrisk/index.html.This site gives a web browser interface to financial calculations and visualizations that aredriven by Mathematica. In this site users are taken through a sequence of web pages in whichthey select different input parameters and submit data to build up a sequence of results.


2 webMathematica User GuideWhy Use Mathematica in a Website?There are various important features that Mathematica can offer to a website, including computation,an interactive programming language, connectivity, the Mathematica front end, andenhanced support for MathML.ComputationMathematica contains a large collection of functions for computing in many areas, such asnumerics, symbolics, and graphics. webMathematica makes all of this functionality availableover the web.Many web technologies, so powerful in many areas, are not well suited to scientific computation;it is simply not their main focus. Mathematica, on the other hand, is very suitable forscientific computation and can provide this on the web.Interactive Programming LanguageMathematica contains a high-level, interactive, functional programming language. It lends itselfto rapid prototyping but can scale up to large intensive computations. These are also advantagesfor web content generation, since large sites can be developed with less programmereffort.ConnectivityMathematica connects readily to external services, which may be provided by languages suchas Java, C, Fortran, or Perl. These services can provide a data source for computations and alsotake the results from Mathematica. It is particularly easy to connect to Java via J/Link, a toolkitfor integrating Java into Mathematica. More information on J/Link can be found athttp://www.wolfram.com/solutions/mathlink/jlink.


webMathematica User Guide 3The Mathematica Front EndThe Mathematica notebook user interface (front end) has long provided the premium mechanismfor working with the Mathematica kernel. Now, webMathematica provides an alternativeinterface via the web. Even in a web environment, the front end is extremely useful. It is usedto typeset mathematics and render two- and three-dimensional graphical objects into images.In addition, the front end can generate notebook documents on the server to send to the client.Mathematical Typesetting and MathMLMathematica is a premium system for interactive mathematical typesetting. It is also a powerfulsystem for working with MathML, which is designed to allow the use and reuse of mathematicaland scientific content on the web and by other applications. These features are a valuablecomponent of webMathematica, which works well with the increasing number of tools that areavailable for MathML.Why a Web Interface?Some of the benefits that a web interface brings to Mathematica include ease of use and delivery,as well as the large number of web development professionals and the many webtechnologies.Ease of UseTo use a webMathematica site, all you need is a web browser. User interfaces can use standardweb GUI elements, such as text fields, checkboxes, and drop-down lists. This reduces trainingtime because users no longer have to learn different software applications. In many cases, noMathematica experience is required.


4 webMathematica User GuideServer-Based ConfigurationThere is no software to buy, install, or maintain in order to use webMathematica sites. All endusersneed is a web browser and, for advanced features like interactive 3D graphics, a JavaRuntime Environment. This leads to significant savings over buying and maintaining user softwareand also ensures that every end-user always has the most recent version. An additionaladvantage is that webMathematica-enhanced websites can be accessed from many differenttypes of computers.Web TechnologiesThere are many people who are experts in working with servers and developing dynamic websites.They can choose from the many web technologies and tools to develop Mathematicarelatedsites. Thus, development is easier and the applications they build are more powerful.Areas of Use for webMathematicaThere are several areas of use for webMathematica. Some of these include web computation,education, publishing, research, and hobbyist calculations.Web ComputationA major use of webMathematica is to build online tools for computation and visualization. Anexample is webUnrisk, http://library.wolfram.com/explorations/webUnrisk/index.html; someexamples of webUnrisk are shown below.


webMathematica User Guide 5EducationMathematica is widely used in many areas of education. These applications can be extended toweb-based education tools with webMathematica. The Integrator, http://integrals.wolfram.com,is a <strong>Wolfram</strong> <strong>Research</strong>-developed website that solves integration problems. Another use ofwebMathematica in education is Calc101, http://www.calc101.com, which mixes free and payper-usecalculators that lead precollege and college students through integration and differentiationproblems.PublishingMany publishers are developing web-based supplements to textbooks, manuals, and journals.webMathematica provides a suitable technology to support these efforts in technical subjects.An example web-based supplement, built with webMathematica, is available athttp://library.wolfram.com/explorations/explorer/index.html, as shown in the following.


6 webMathematica User Guide<strong>Research</strong><strong>Research</strong>ers all over the world use Mathematica to investigate their fields of interest anddevelop techniques and algorithms for solving problems. All the Mathematica work they developcan now be delivered with live interactive websites, vastly increasing the number of people whocan use and learn from their results. A typical website that plots surfaces of constant curvatureis http://library.wolfram.com/webMathematica/Mathematics/ConstantCurvature.jsp.HobbyistwebMathematica allows individual users to showcase their personal interests with web-basedinteractive calculations and visualizations. AnalyticCycling.com, http://www.analyticcycling.com,provides a recreational website that takes advantage of the web Mathematica engine.Designed for technically oriented cyclists, AnalyticCycling.com offers web-based calculators thattake a no-compromise, textbook approach to computing cycling performance.


webMathematica User Guide 7webMathematica TechnologywebMathematica is based on two standard Java technologies: Java Servlet and JavaServerPages (JSPs). Servlets are special Java programs that run in a Java-enabled web server, whichis typically called a "servlet container" (or sometimes a "servlet engine"). There are manydifferent types of servlet containers that will run on many different operating systems andarchitectures. They can also be integrated into other web servers, such as the Apache webserver.webMathematica allows a site to deliver HTML pages that are enhanced by the addition ofMathematica commands. When a request is made for one of these pages, the Mathematicacommands are evaluated and the computed result is placed in the page. This is done with thestandard Java templating mechanism, JavaServer Pages, making use of a special tags; examplesof these are given in a later section.webMathematica technology uses the request/response standard followed by web servers.Input can come from HTML forms, applets, JavaScript, and web-enabled applications. It is alsopossible to send data files to a webMathematica server for processing. Output can be manydifferent formats such as HTML, images, Mathematica notebooks, MathML, SVG, XML,PostScript, and PDF. This user guide includes examples of working with all these differenttechnologies.webMathematica provides a large library of Mathematica commands to handle the many possibleways of working with Mathematica computations. An important part of webMathematica isthe kernel manager that calls Mathematica in a robust, efficient, and secure manner. The managermaintains a pool of one or more Mathematica kernels and, in this way, can process morethan one request at a time. An overview of the workings of a webMathematica site is shownhere.1. Browser sends request to webMathematica server.


8 webMathematica User Guide2. webMathematica server acquires Mathematica kernel from the pool.3. Mathematica kernel is initialized with input parameters, carries out calculations, andreturns result to server.4. webMathematica server returns Mathematica kernel to the pool.5. webMathematica server returns result to browser.


webMathematica User Guide 9RequirementsThe aim of webMathematica and MSP technology is to reduce the amount of extra knowledgerequired for developing a site to a minimum. In practice, this means knowing something aboutHTML and Mathematica. You do not need any special knowledge of Java, nor do you need toknow anything about JavaScript. webMathematica also aims to automate the management ofthe site to make running, maintenance, and configuration as convenient as possible. Administratorsof webMathematica sites do not need any knowledge of Java beyond its installation.The minimum technical components for webMathematica are:1. A servlet container supporting both the Servlet Specification 2.4 (or higher) and JSPSpecification 2.0 (or higher)2. A JDK 1.2 (or higher); Java 2 Version 1.4 (or higher) is recommendedThere are many different combinations of hardware and operating systems that support thesecomponents. Most systems that run Mathematica will support webMathematica. At presentIntel/Windows, Intel/Linux, Mac OS X, and Sun/Solaris are fully supported,http://www.wolfram.com/products/mathematica/platforms/. Setting up the servlet container isdiscussed in a later section.New Features of webMathematicawebMathematica 3.0Interactive ToolswebMathematica 3.0 replicates the popular interactive Manipulate command for web pages.You can create web pages that contain various GUI features such as sliders, checkboxes, andpopup menus, which control a calculation. All of this is done with the same concise syntaxprovided by Manipulate.


10 webMathematica User GuideExpression Language and Custom TagswebMathematica 3.0 comes with support for a more concise way to call to Mathematica fromthe web page. It also contains a library with a number of useful tags; these tags provide anumber of valuable tools, such as redirecting flow as the web page is generated.Queueing SystemwebMathematica 3.0 allows long running or asynchronous computation jobs to be executed bya new queueing system.Support for <strong>Wolfram</strong> Workbench<strong>Wolfram</strong> Workbench provides a significant number of features that help to accelerate the developmentof webMathematica content. webMathematica 3.0 integrates with <strong>Wolfram</strong> Workbenchso that Mathematica code can be debugged as it runs in the server.Web ServiceswebMathematica 3.0 enables you to write REST and SOAP web services that use Mathematica.New Logging SystemA new, highly configurable logging system helps to track different types of errors and to identifyproblems so that they can be resolved easily.Improved Kernel MonitorThe Kernel Monitor has been significantly improved. It has new code for monitoring memoryusage, running time, concurrent requests, and Java objects; this helps to improve the reliabilityof the server. It allows starting and stopping of individual kernel pools and canceling individualcomputations. Queued jobs are monitored for progress and errors.Improved Kernel InteractionwebMathematica 3.0 has improved the way that it interacts with the Mathematica kernel. Itlaunches kernels as soon as the server starts and launches all kernels in parallel; this helps toimprove the startup time for the server. It also has a number of new configuration tools, whichlimit the use of time and memory by the kernel; this helps to improve the reliability of theserver. Kernels are automatically restarted in the background, so service remains uninterrupted.


webMathematica User Guide 11IncompatibilitiesThis section lists any changes in webMathematica 3.0 that work differently from previousversions.Classic webMathematica Technology DroppedSupport for the classic webMathematica technology has been dropped. This technology hasbeen deprecated since webMathematica 1.0.ConfigurationA new configuration system based on a single XML file, MSPConfiguration.xml, is now supported.The name of the security configuration file is now called SecurityConfiguration.m.webMathematica 2.3The main new feature of webMathematica 2.3 is support for Mathematica 5.2. There are also anumber of internal improvements.webMathematica 2.2Support for Mathematica 5.1webMathematica 2.2 comes with Mathematica 5.1. Mathematica 5.1 contains many importantnew features relevant to web operations, the most important being optimized binary I/O, graphand array plotting, and comprehensive string manipulation, matching, and searchingcapabilities.Database ConnectivityDatabaseLink provides Mathematica with an industrial-strength, ready-made solution for integratingMathematica with any standard SQL database. Integrated with Mathematica 5.1, itprovides a convenient bridge between SQL databases and webMathematica. One particularlyuseful feature for webMathematica is that DatabaseLink contains the HSQL Database Engine(HSQLDB), a lightweight database. This means that if you do not already have a database orwant to experiment with using one, you do not have to set one up; instead you can useHSQLDB.


12 webMathematica User GuideClient Web ServicesThe Mathematica Web Services Package allows Mathematica to call web services across theinternet. Bundled with Mathematica 5.1, it provides a convenient way for webMathematica touse a web service. This is an important way to extend the functionality of a webMathematicawebsite.webMathematica 2.1The main new feature of webMathematica 2.1 is support for Mathematica 5.0. There are also anumber of internal improvements and new examples.webMathematica 2.0webMathematica 2.0 offered a number of new features and improvements. These are listed inthis section.Support for Mathematica 4.2webMathematica 2.0 comes with Mathematica 4.2. Mathematica 4.2 has many features that arevery relevant to web operations, the most important being the XML support. There are manyexamples in webMathematica 2.0 that use XML features and XML applications such as MathMLand SVG.Simplified InstallationwebMathematica 2.0 has a simplified installation process that only requires the installation ofthe webMathematica web application. There is a minimum of extra configuration that isrequired.Extended Documentation and ExamplesThe documentation for webMathematica is now shipped in HTML format and accessible from thewebMathematica front page. In addition many new examples have been added that demonstratethe new features.


webMathematica User Guide 13New Templating Mechanism Based on JSP Custom TagsA new HTML templating mechanism based on JSP custom tags has been added. This is now thepreferred mechanism for using webMathematica. The mechanism is easier to understand, itallows the use of other JSP custom tag libraries, and it facilitates the integration of webMathematicainto other server applications.MathML, SVG, and XML SupportSupport for the XML applications, MathML and SVG, is built into webMathematica 2.0. In additionit can make use of the new XML processing tools that are available in Mathematica 4.2.Support for Catching Message and Print OutputNew functions are provided for catching the output of any Mathematica Message or Print statements.This can be useful for debugging or developing material.Support for HTTP File UploadNew functions are provided to support HTTP file upload. This is an important way to submitinformation to a webMathematica web server.Support for HTTP Session VariablesNew functions are provided for saving material in an HTTP session stored in the server. This canbe useful for saving results from one computation to another.HTML Formatting FunctionsNew functions are provided for formatting results into HTML.IncompatibilitiesThis section lists any changes in webMathematica 2.0 that work differently from 1.0.Location of Security Configuration FileThe mechanism for locating the security configuration file has changed from webMathematica1.0. Now the security configuration file is named in the pool configuration file and is located in acentral configuration directory in webMathematica/WEB-INF/conf. Previously the configurationfile could be loaded from anywhere on the Mathematica path.


14 webMathematica User GuideThis change was made because loading the security configuration from a single central locationis more secure. Since the default security system of webMathematica is very conservative, anysites that do not move their security files will run with a higher level of security than isexpected. Security is discussed in a later section.Location of MSP.confThe default location MSP.conf has been moved into a central configuration directory inwebMathematica/WEB-INF/conf. This leads to a great simplification in the setup of your serverbecause it will look automatically in this location.


InstallationThese installation instructions focus on setting up a servlet container and installing webMathematica.As explained previously, webMathematica is based on a standard Java technology calledservlets; support for servlets is typically provided by a program called a servlet container. Youmust set up the servlet container before adding webMathematica.Installation can take the following steps:1. Set up a servlet container.2. Set up Mathematica using the CD-ROM from your distribution or from your download.3. Install the webMathematica web application into your servlet container using the webMathematicaTools CD-ROM from your distribution or from your download.4. For Unix, you may need to set up an X server.5. Finally, you should test your webMathematica site.More information on installation of webMathematica can be obtained from <strong>Wolfram</strong> <strong>Research</strong> athttp://www.wolfram.com/products/webmathematica/install.Setting Up a Servlet ContainerBefore you start to install webMathematica, you need an installation of Java and a servletcontainer. If you already have these components, you may skip this section.There are many different servlet containers, but one that is particularly convenient is Tomcat,which can be obtained from http://jakarta.apache.org. Since Tomcat is a common way to runwebMathematica, there is information on installing and setting it up on Unix, Windows, and MacOS X.webMathematica has been tested with Tomcat as well as other containers listed athttp://www.wolfram.com/products/webmathematica/technology/. If you have a particularinterest or experience in running webMathematica with other containers, please contact<strong>Wolfram</strong> <strong>Research</strong>. However, if you do not have expertise with these other containers, usingApache Tomcat is recommended.


16 webMathematica User GuideWhen your servlet container is functioning correctly, as demonstrated by running its sampleservlets, you are ready to install webMathematica. If your servlet container does not work, thenwebMathematica cannot work. The remaining steps in this section show you how to set up Javaand Tomcat. If you are not using Tomcat, you should skip this section and study the documentationfor your servlet container.Setting Up JavaIt is recommended that you use a modern version of Java, such as Java SE 6. For Linux, Linuxx64, Solaris SPARC, Solaris x64, Solaris x86, Windows, and Windows x64, this is available fromthe Sun Java site at http://java.sun.com/javase/downloads/index.jsp. The Sun Java site providesdetailed installation instructions for the different platforms. These are all relatively simple;typically, you download and execute an installer. If you are using Java SE 5 or higher, you canuse either a JRE or JDK to run webMathematica. If you are using an older version of Java, youneed the JDK. For Mac OS X, J2SE 5.0 is already installed. For other platforms, modern versionsof Java are available from the appropriate vendors; a list of useful links is maintained in theAppendix: Java.You will also need to set the JAVA_HOME environment variable. This is described in the nextsections for Unix and Windows.UnixThe JAVA_HOME environment variable needs to be set for the environment in which Tomcatruns. An example of this, suitable for inclusion in .bashrc (this is the initialization file for thebash shell), is shown below.JAVA_HOME=/usr/local/jdk1.6.0_14export JAVA_HOMEFor other shells, you should follow their standards for setting environment variables.WindowsIt is less important to set the JAVA_HOME variable for Windows because the Tomcat installer willfind your installation of Java. However, it is still recommended.


webMathematica User Guide 17If you go to the Control Panel and open the System icon, you will see the System Propertieswindow. From this, select the Advanced tab and then the Environment Variables button.Enter JAVA_HOME as a system variable, setting it to the top-level directory containing your JDK.For example, if your JDK is installed in C:\Program Files\Java\jdk1.6.0_14, this is thesetting for JAVA_HOME.Mac OS XMac OS X 10.5 ships with J2SE 5.0 and Java SE 6. Mac OS X 10.4 ships with J2SE 5.0. You mayfind that an updated version can be obtained via the software update mechanism (see alsohttp://www.apple.com/java/). If you update your Java, you can ensure that you are alwaysusing the most recent version of the JDK by setting up the JAVA_HOME environment variableproperly; this is shown below.JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Homeexport JAVA_HOMEThe default login shell for Mac OS X 10.5 is bash; hence, the above command needs to beplaced in the appropriate shell initialization file, for example, .bashrc.Setting Up TomcatThis section describes setting up Tomcat on Unix, Windows, and Mac OS X. The main websitefor Tomcat is http://jakarta.apache.org; a list of useful links is maintained in Appendix: Tomcat.UnixBefore you run Tomcat, you should first make sure you have set up Java on your machine; thiswas described in the previous section.Download information for current versions of Tomcat is given at http://www.wolfram.com/products/webmathematica/resources/?tab=Updates.A variety of archive formats are available; oneof these should be unpacked in some central location, for example /usr/local. You may alsowish to change the name of the top-level directory. The actual location of Tomcat and the nameof the top-level directory are entirely up to you. Sample shell instructions for these steps areshown below (note that tar xvfz archive will give you more information on what files arebeing extracted). Other versions of Tomcat are available from the Apache website,http://jakarta.apache.org.


18 webMathematica User Guide[server1]$ cd /usr/local[server1]$ tar xfz jakarta-tomcat-5.5.27.tar.gz[server1]$ mv jakarta-tomcat-5.5.27 tomcatOn some platforms, such as Solaris, the default tar command does not work to unpackthe Tomcat archive as shown above. You need to obtain the GNU tar utility fromhttp://www.gnu.org/directory/GNU/tar.html in order to use the options shown.It is often useful to create a low privilege account, such as tomcat, to run your servlet container.It is probably helpful if this account has a home directory so that your X server andMathematica can store preferences information. If you create such an account, you may needto change ownership of the Tomcat layout so it can be run by this account.[server1]$ chown -R tomcat tomcatThe main top-level directory of Tomcat contains some important directories, including:tomcatbinconflogswebappsThe bin directory contains commands for running Tomcat; the conf directory contains siteconfiguration files; the logs directory contains various log files; the webapps directory is whereyou will install webMathematica. You should be able to launch Tomcat immediately from thebin directory, making sure to be the tomcat user.[server1]$ su tomcat[server1]$ cd tomcat/bin[server1]$ ./startup.shAt this point, you should be able to connect to Tomcat via a URL such as http://localhost:8080.If this does not return the Tomcat front page, then something is wrong with your setup. If youlook at the log files, it may help you track down your problem. Make sure that you have setyour JAVA_HOME variable as described in the installing Java for Unix section.The bin directory also contains a script, shutdown.sh, used for shutting down Tomcat.Information on launching Tomcat automatically on Unix is given in a later section.


webMathematica User Guide 19WindowsBefore you run Tomcat, you should first make sure you have set up Java on your machine; thiswas described in the previous section.Download information for current versions of Tomcat is given at http://www.wolfram.com/products/webmathematica/resources/?tab=Updates. A convenient way to install Tomcat is todownload the self-installing executable. You should launch the installer and follow the instructionsit provides. If you choose not to use the self-installing executable, then unpack the binarydistribution into a convenient location. Other versions of Tomcat are available from the Apachewebsite, http://jakarta.apache.org.After installation is complete, you may wish to inspect the main top-level directory of Tomcat,which contains some important directories, including:Tomcat 5.5binconflogswebappsThe bin directory contains commands for running Tomcat; the conf directory contains siteconfiguration files; the logs directory contains various log files; the webapps directory is whereyou will install webMathematica.The installer adds a Start Menu Group from which you can run Tomcat. You should test it via aURL such as http://localhost:8080. If Tomcat does not run correctly, you should open a commandprompt window, change directories (”cd”) to the bin directory (in the main top-leveldirectory of Tomcat) and try running the tomcat5.exe executable file (this can also be accomplishedby double-clicking on the file via the Windows Explorer). Previous versions of Tomcatused a startup.bat batch file. Starting and stopping Tomcat from the Start Menu is veryconvenient (this is also a new feature of Tomcat 4.1), but for running Tomcat as a productionserver under Windows you may wish to run it as a Windows Service. This is described in thesection on launching Tomcat automatically on Windows.Mac OS XOf course, before you run Tomcat, you should first make sure you have set up Java on yourmachine as described in the previous section.


20 webMathematica User GuideIt is often useful to create a low privilege account, such as tomcat, to run your servlet container.You can accomplish this via the System Preferences panel. If you create such anaccount, you may need to change ownership of the Tomcat layout so it can be run by thisaccount.[server1]$ sudo chown -R tomcat tomcatThe main top-level directory of Tomcat contains some important directories, including:tomcatbinconflogswebappsThe bin directory contains commands for running Tomcat; the conf directory contains siteconfiguration files; the logs directory contains various log files; the webapps directory is whereyou will install webMathematica. You should be able to launch Tomcat immediately from thebin directory, making sure to be the tomcat user.[server1]$ su Tomcat[server1]$ cd Tomcat/bin[server1]$ ./startup.shAt this point, you should be able to connect to Tomcat via a URL such as http://localhost:8080.If this does not return the Tomcat front page, then something is wrong with your setup. If youlook at the log files, it may help you track down your problem. Make sure that you have setyour JAVA_HOME variable as described in the installing Java for Mac OS X section.The bin directory also contains a script, shutdown.sh, used for shutting down Tomcat.Please also note that for webMathematica to fully function, you need to log on via the Mac OS Xconsole. This is necessary since the Mathematica front end makes use of the Mac OS X windowingenvironment.Download information for current versions of Tomcat is given at http://www.wolfram.com/products/webmathematica/resources/?tab=Updates. A variety of archive formats are available;one of these should be unpacked in some central location, for example, /Library. You mayalso wish to change the name of the top-level Tomcat directory. The actual location of Tomcatand the name of the top-level directory are entirely up to you. /Library is useful because itcan be viewed via the Finder. Other versions of Tomcat are available from the Apache website,http://jakarta.apache.org.Note that the default OS X tar command does not work to unpack the Tomcat archive asshown below. You would need to use the GNU tar utility (gnutar), which normally resides in


webMathematica User Guide 21Note that the default OS X tar command does not work to unpack the Tomcat archive asshown below. You would need to use the GNU tar utility (gnutar), which normally resides in/usr/bin/, to use the options shown. You could also use Stuffit Expander (Version 7.0.1 andlater), which uncompresses *.tar.gz archives.Sample shell instructions for these steps are shown below (note that tar xvfz archive will giveyou more information on what files are being extracted). These instructions assume that youare using the Terminal application found in Applications-> Utilities-> Terminal.[server1]$ cd /Library[server1]$ sudo /usr/bin/gnutar xfz jakarta-tomcat-5.5.27.tar.gz[server1]$ sudo mv jakarta-tomcat-5.5.27 tomcatInstalling and Configuring MathematicaInstall the version of Mathematica appropriate for the platform you wish to use for your webserver. You should choose a single-machine installation. When you have finished, you should beable to run Mathematica interactively to validate your installation. If Mathematica cannot run,then webMathematica cannot run.If you already have an installation of Mathematica on your server, you do not need to installMathematica again, but can proceed with the remaining installation steps. With an existinginstallation of Mathematica, you may place your webMathematica license information into adifferent location, as described in the following section. Placing the license information in adifferent location will ensure that an interactive usage of Mathematica on your server does notinterfere with the operation of your webMathematica site. One possible alternative directory isthe webMathematica/WEB-INF/conf directory as demonstrated in the section on installingwebMathematica into Tomcat. Note that if you install the license in a special file, you will haveto set the -pwfile option when you run Mathematica outside of webMathematica.Installing the webMathematica Web ApplicationThis section describes how to install webMathematica components into your servlet container.For most servlet containers, this involves deploying the webMathematica web application foundin archived form on the webMathematica Tools CD-ROM or from your download. Separate


22 webMathematica User Guideinstallation instructions are given for some different servlet containers. A web application is acollection of HTML and other web components, which are placed in a specific directory structure.Any servlet container that supports web applications will be able to use these files in astandard way. Web applications support a special type of archive called a WAR archive, which issupported by some servlet containers. webMathematica provides a WAR archive of the webMathematicaarchive.TomcatThis section describes the deployment of the webMathematica webapp in Tomcat. There aretwo steps: unpacking the webMathematica archive and configuring the MSPConfiguration.xmlfile.First, choose one of the webMathematica archives from the Tools CD-ROM; for example, webÖMathematica.zip or webMathematica.tar.gz. Unpack the archive into the webMathematicadirectory located in the Tomcat webapps directory. This is usually found in the top-level directoryof Tomcat. You have now created a web application called webMathematica. Some of thecontents of the top directory of Tomcat, along with the location of the webapps directory andwebMathematica web application, are shown below.tomcatconfbinlogslibwebappswebMathematicaSecond, configure the file MSPConfiguration.xml, located in the WEB-INF/conf directory. Thisfile holds various site-specific parameters and may need modification for your site. The settingsthat can be placed into MSPConfiguration.xml are described in the section Site Configuration.The most important setting is KernelExecutable, the location of the Mathematica kernel. TheMSPConfiguration.xml that ships with webMathematica contains settings suitable for a defaultinstallation of Mathematica for Windows, Unix, Linux, and Mac OS X. However, if you installMathematica into a nondefault location, you will need to modify this file. For example, if youinstalled Mathematica into E:\Mathematica, make the following setting of KernelExecutable inMSPConfiguration.xml.


webMathematica User Guide 23E:\Mathematica\MathKernel.exeAnother reason to modify MSPConfiguration.xml is to store your webMathematica license in itsown password file, for example, webMathematica/WEB-INF/conf/mathpass. It would then benecessary to modify KernelLaunchFlags in MSPConfiguration.xml to ensure that Mathematicauses this location. The following shows how this could be done for a typical Windows installation.-pwfile c:/Program Files/tomcat/webapps/webMathematica/WEB-INF/conf/mathpassA typical setting for MSPConfiguration.xml to use a special mathpass file under Unix is shownbelow.-pwfile /usr/local/tomcat/webapps/webMathematica/WEF-INF/conf/mathpassUnder Unix, you may need to add a FrontEndLaunchFlags parameter so the front end can runproperly. In the following example, the front end will be launched to use DISPLAY 1 with fixedgeometry and in server mode. For more information on running the front end under Unix, seethe documentation section Configuring for the X Window System.-display :1 -nogui -geometry 1000x500+10+10Other Servlet EnginesIf you are unfamiliar with servlets, then it is recommended that you use Apache Tomcat. Youshould only use another servlet engine if you are already experienced with it.If you have some other servlet engine, follow its instructions for installing a web application,which may be supported by some special tools. After installing the web application, you willneed to modify the MSPConfiguration.xml file as described in the section on installing underTomcat. It may also be necessary to make various modifications to MSPConfiguration.xml,such as changing the JLinkNativeLibraryDirectory setting.


24 webMathematica User GuideConfiguring for the X Window System (Unix only)There are special problems associated with running the Mathematica front end under X fromwithin a web server. This is because, typically, the web server is run as a special account, suchas tomcat. This means that when webMathematica runs the front end, it is running as thisaccount. For the front end to operate, it must connect to an X server; this could be achieved bylogging into the console of the web server machine with this special account running an Xserver. There are a few problems with this approach: first, you may not want to leave themachine with an open login on the console; secondly, every time the front end does something,a window will appear on the screen, which may be distracting for someone using the machine.If a different user logs into the console and runs an X server, the front end (which is run by thespecial webMathematica account) will not be able to connect to this server at all under thestandard authentication system of X. While it is possible to configure the server to allow theseconnections, it is not satisfactory because webMathematica will be displaying windows on thescreen every time it does something with the front end. This topic is discussed in greater lengthin a later section.These problems are solved by running a virtual X server, such as Xvnc, as described in thefollowing section. Running a virtual server prevents the windows created by the Mathematicafront end from displaying on the screen console of the computer running Mathematica.Configuring Xvnc and webMathematicaXvnc is the Unix VNC server. It provides a virtual X server that can be used by applications,such as the Mathematica front end, when it is running for webMathematica. It also provides aVNC server so that a VNC viewer can connect to view and control any applications running inthe server. This can be useful since it can help track down problems in running the front end.Xvnc comes with a number of Unix distributions. It can also be ovtained from RealVNC,http://www.realvnc.com/, and TightVNC, http://www.tightvnc.com.


webMathematica User Guide 25Install XvncInstallation of Xvnc is quite straightforward; you unpack the archive and then copy the relevantfiles into some local bin directory, for example, /usr/local/bin. (Note that some modernLinux distributions already have Xvnc installed.) Copying of the Xvnc binaries is shown below.[server1]$ cp vncviewer vncserver vncpasswd vncconnect Xvnc /usr/local/binLaunch XvncLaunching Xvnc is also quite straightforward; this should be done as the user that will be runningwebMathematica, for example, the user tomcat. The first time Xvnc is launched, it asks fora password. In the example below, the server is launched as display :1.Test Xvnc[server1]$ su tomcat[server1]$ vncserverYou will require a password to access your desktops.Password:Verify:New'X' desktop is server1:1Creating default startup script /home/tomcat/.vnc/xstartupStarting applications specified in /home/tomcat/.vnc/xstartupLog file is /home/tomcat/.vnc/server1.wolfram.com:1.logOnce it is launched, it is a good idea to test the server by running an application to use it, forexample, the Mathematica front end. This is shown below.[server1]$ su tomcat[server1]$ mathematica -display :1Of course, when this is done, you do not see an actual window on your screen; this is becauseit is a virtual server. To see the window from the Mathematica front end, you can run thevncviewer. This can be done as shown below.[server1]$ vncviewer :1This should show you a screen with the front end window visible. You should be able to typeinto the front end and see it working. At any time webMathematica is running, you can view thedesktop with vncviewer.


26 webMathematica User GuideConfigure webMathematicaThe final step is to modify your MSPConfiguration.xml file to instruct the front end to use thisserver. The setting of FrontEndLaunchFlags is described in the Appendix: Site Configuration.Here is a sample setting that connects to the X server on display :1.-display :1 -nogui -geometry 1000x500+10+10Now your Unix server should be ready to run webMathematica.If you find that the front end does not launch correctly, it may help to add the name of theserver in the configuration file. An example is shown below; here, myserver is the name of themachine on which webMathematica and Xvnc are running.-display myserver:1 -nogui -geometry 1000x500+10+10Other X Related IssuesThe following section describes a number of further issues that relate to using webMathematicain conjunction with an X server. If you have set up an Xvnc server as described above it shouldnot be necessary to study these.Connecting to the X ServerWhen the Mathematica front end runs, it must connect to an X server. If the X server is beingrun by a different user than the user running the front end, the X server will reject the connection,as shown below.[root]# su tomcatbash$ mathematicaXlib:connection to ":0.0" refused by serverXlib:Client is not authorized to connect to Serverxset:unable to open display ":0.0"Xlib:connection to ":0.0" refused by serverXlib:Client is not authorized to connect to Serverxset:unable to open display ":0.0"Xlib:connection to ":0.0" refused by server


webMathematica User Guide 27Xlib:Client is not authorized to connect to Serverxset:unable to open display ":0.0"Xlib:connection to ":0.0" refused by serverXlib:Client is not authorized to connect to ServerXMathematica:can't open display:0.0,exiting...bash$One way to avoid this problem is to allow all connections from the local machine.[root]# xhost +localhostlocalhost being added to access control list[root]# su tomcatbash$ mathematicabash$This is not a good technique since there is a potential for security problems. These are probablylimited since it is only connections from the same machine that are allowed. Another problem isthat every time the front end is used, a window will be drawn on the screen, which may beannoying to a user of the system.A more satisfactory alternative is to run a virtual X server, such as Xvnc.XvfbXvfb is a virtual frame buffer server described at http://www.xfree86.org/4.3.0/Xvfb.1.html. Itcan be used as an alternative to Xvnc, but typically we have found Xvnc to be easier to use andprovide more functionality.For Linux, you can download an RPM archive from http://www.redhat.com. After installation,you can launch it as follows (you will probably run this as root).su tomcat -c "/usr/X11R6/bin/Xvfb :1 -fpunix/:7100,/usr/local/<strong>Wolfram</strong>/Mathematica/4.2/SystemFiles/Fonts/Type1,/usr/local/<strong>Wolfram</strong>/Mathematica/4.2/SystemFiles/Fonts/BDF -screen 0800x600x24 " &This command launches Xvfb referencing a font server on port 7100 and adding directories thatcontain the Mathematica fonts. Note that if you install Mathematica in some alternative location,you should modify these directories. Under some Mathematica installations the location ofMathematica fonts is added to the font server configuration; in this case the Mathematica fontsdo not need to be referenced when Xvfb is launched. Xvfb could then be launched as shownhere.su tomcat -c "/usr/X11R6/bin/Xvfb :1 -fp unix/:7100" &


28 webMathematica User GuideIn these examples, Xvfb expects to use port 7100 on the local machine for the font server. Theactual setting may need to be modified if some alternative configuration of font server is used.For example, under Redhat 6 the font server uses a local Unix socket and Xvfb should belaunched as follows.su tomcat -c "/usr/X11R6/bin/Xvfb :1 -fpunix/:-1,/usr/local/<strong>Wolfram</strong>/Mathematica/4.2/SystemFiles/Fonts/Type1,/usr/local/<strong>Wolfram</strong>/Mathematica/4.2/SystemFiles/Fonts/BDF -screen 0800x600x24 " &If you are not running a font server, you may need to launch Xvfb with no font server reference.In this case, it may be necessary to copy the Mathematica fonts into the X distributionlayout as described in the section below on manual font installation.su tomcat -c "/usr/X11R6/bin/Xvfb :1 -screen 0 800x600x24 "&Once you have launched the virtual frame buffer server, you can test that it is running. You willprobably run this as root.[root]# su tomcatbash$ mathematica -display :1Of course, one problem with confirming that the front end is running correctly with this serveris that you cannot see it on the screen! This makes it hard to see a dialog box indicating anerror. One way to see what the front end is displaying is to inspect a dump of the server withxwd and xwud, which you can do with the following.xwd -display :1 -root | xwudThis will show what the front end is displaying. For example, if you see a message about notfinding the password, you may need to add a pwfile command-line option.When you are running the virtual frame buffer X server, you will need to modify your MSPConfigÖuration.xml file to instruct the front end to use this server. The setting of FrontEndLaunchÖFlags is described in Appendix: Configuration. Here is a sample setting.-display :1 -nogui -geometry 1000x500+10+10On some systems, such as Sun/Solaris, the X server has problems when being launched by theuser tomcat since the permissions to the /tmp/.X11 directories have been restricted for secu-


webMathematica User Guide 29rity reasons. The problem manifests itself with a message that says the system cannot establishany listening sockets. One solution would be to modify the directories so that tomcat can writeto them. For more detail, see http://www.faqs.org/faqs/Solaris2/FAQ/.Manual Font InstallationThe front end cannot run without access to the Mathematica fonts. If you notice from the outputof the X server with vncviewer or xwd that the front end is displaying a dialog box indicatingthat it cannot find its fonts, you will have to take some further steps to locate the fonts.One solution that is simple but drastic is to copy the Mathematica fonts into your X distribution.cd /usr/X11R6/lib/X11/fontscp -r 75dpi 75dpi.origcd 75dpicp /usr/local/<strong>Wolfram</strong>/Mathematica/5.1/SystemFiles/Fonts/X/*.bdf .mkfontdirThis is really a poor solution to be avoided if possible. One deficiency is that if you update yourcopy of Mathematica, you will have to remember to copy the new fonts. The proper solution isto launch Xvfb so it either uses a font server or a font path setting, as described above. Rememberthat this is not a problem when working under Windows.Upgrading from webMathematica 2.3This section discusses some of the issues that will concern you if you already have webMathematica.If you are using an older servlet container, this may be a good opportunity to upgradeto something more recent. If you are going to upgrade your servlet container, you could followthe instructions at the beginning of this chapter as though this was a fresh installation ofwebMathematica.Install MathematicawebMathematica comes with a copy of Mathematica and this should be installed as discussed inthe section on Installing and Configuring Mathematica.If you have installed any applications into your copy of Mathematica, you will need to makethem available to Mathematica. This is discussed in the section Installing Packages. Note thatyou should not copy the MSP application to Mathematica.


30 webMathematica User GuideInstall the webMathematica Web ApplicationTo install the webMathematica web application, you will need to remove your current webMathematicaweb application out of your servlet container. For Tomcat, this is a simple matter ofmoving the webMathematica directory from the webapps directory. You may need some of thematerial in this web application, so you should probably keep it somewhere accessible. Afterthis you can follow the instructions for Installing the webMathematica Web Application.Configure the New LayoutIf you made any special configuration to your old version of webMathematica, you may want tomake similar changes in webMathematica 3.0. Typically this might affect the file web.xml, aswell as the webMathematica and security configuration files.web.xmlYou should only make changes to web.xml if you are certain that you understand the intent ofthe setting. In addition, it would be better to copy any modified configuration parameters fromthe old version rather than taking the entire file. The web.xml file is found in the directorywebMathematica/WEB-INF.MSPConfiguration.xmlwebMathematica 3.0 uses a new configuration system based on an XML file called MSPConfiguraÖtion.xml, which is found in the directory webMathematica/WEB-INF. You should copy specificconfiguration parameters rather than taking the entire file. The configuration section describesthe new format and the meaning of the configuration settings.Security ConfigurationThe mechanism for locating the security configuration file has changed. Now the security configu -ration file is named in the pool configuration and is located in a central configuration directoryin webMathematica/WEB-INF; the default name is SecurityConfiguration.m. Previously theconfiguration file could be loaded from anywhere on the Mathematica path.This change was made because loading the security configuration from a single central locationis more secure. Since the default security system of webMathematica is very conservative, any


webMathematica User Guide 31sites that do not move their security files will run with a higher level of security than isexpected. A fuller discussion is found in the section on Security.Move Content to the New LayoutNow you should copy your content from your old layout. You should not copy any of the examplesbecause webMathematica 3.0 has its own set of updated examples. Instead, you shouldjust copy your own material from the old layout into the new.Finalize the InstallationWhen you have installed the new version of webMathematica you should test your installation.A good URL to use is http://localhost:8080/webMathematica/Examples/Specification.jsp. Thiswill print the version numbers of your installation. You should confirm that you have webMathematica3.0 and Mathematica 7.0.Optional Further ConfiguringThere are a number of additional features that can be obtained by optional extra installationsteps. It is not necessary to carry them out to run your webMathematica server, but they areincluded in this section to provide extra information.MSP Mathematica ApplicationThe MSP Mathematica application contains various Mathematica packages and utilities such asdocumentation. It is already installed in the webMathematica layout so that webMathematicawill operate without any extra steps. However, you may wish to use some of the functions or toview the webMathematica documentation in the Mathematica Documentation Center. In orderto do this, you will need to install the application. This installation step is optional because it isnot needed for webMathematica to run. Note that you can also find the documentation on the<strong>Wolfram</strong> <strong>Research</strong> web site at http://reference.wolfram.com/mathematica/webMathematica/tutorial/Overview.html.


32 webMathematica User GuideThe MSP Mathematica application is in archive form on the webMathematica Tools CD-ROM.Unpack the appropriate archive and place its contents into the AddOns/Applications directoryin your Mathematica directory. It should then be possible to launch Mathematica and the web-Mathematica documentation to appear in the Documentation Center under Installed AddOns.The MSP Mathematica application contains useful functions for formatting Mathematica expressionsinto HTML tables and select tags, in addition to utilities useful for using SVG.Launching webMathematica AutomaticallyIt is common for a web application, such as webMathematica, to be launched automaticallywhenever the server machine starts. This section will review the ways that this can be done. Ofcourse this is typically done by the system administrator; the information here is somethingthat can be used to adapt to the conventions of your own system. The instructions are differentfor Unix and Windows. These instructions will focus on launching Tomcat; if you use some otherservlet container, you will need to consult its documentation.UnixTomcat can be launched automatically by adding it to a system startup script. The descriptionhere is typical of a Linux RedHat system. It is a good idea to first study the instructions forsetting up Tomcat on Unix.A common way to launch is to add a script to the initialization directory init.d and making alink to the appropriate startup directory (for example rc3.d). The script will make definitionsfor starting and stopping Tomcat, making use of the tomcat user that was created. A samplescript is shown below.#!/bin/sh## tomcat This shell script takes care of starting and stopping# tomcat.# description: tomcat is a servlet/JSP engine, which can be used# standalone or in conjunction with Apache# Source function library.. /etc/rc.d/init.d/functions


webMathematica User Guide 33# Source networking configuration.. /etc/sysconfig/networkRETVAL=0export JAVA_HOME=/usr/local/javaexport CATALINA_HOME=/usr/local/tomcatexport PATH=$PATH:/usr/local/bin:$JAVA_HOME/bin# See how we were called.case "$1" instart)# Start daemons.echo -n "Starting tomcat: "cd ~tomcatsu tomcat -c '$CATALINA_HOME/bin/catalina.sh start'RETVAL=$?[ $RETVAL -eq 0 ] && touch /var/lock/subsys/tomcatecho;;stop)# Stop daemons.echo -n "Shutting down tomcat: "cd ~tomcatsu tomcat -c '$CATALINA_HOME/bin/catalina.sh stop'RETVAL=$?[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/tomcatecho;;restart)$0 stop$0 startRETVAL=$?;;*)echo "Usage: tomcat {start|stop|restart}"exit 1esacexit $RETVAL


34 webMathematica User GuideIn addition, if you are using a virtual X server, such as Xvnc, you will need to launch this atsystem initialization time. A sample script for launching Xvnc is shown below.!/bin/sh## description: VNC instance for webMathematica# Source function library.. /etc/rc.d/init.d/functions# Source networking configuration.. /etc/sysconfig/networkRETVAL=0# See how we were called.case "$1" instart)# Start daemons.echo -n "Starting VNC: "cd ~tomcatsu tomcat -c '/usr/bin/vncserver -geometry 800x600 -depth 24 :1>/dev/null 2>/dev/null'RETVAL=$?[ $RETVAL -eq 0 ] && touch /var/lock/subsys/vncecho;;stop)# Stop daemons.echo -n "Shutting down VNC: "cd ~tomcatsu tomcat -c '/usr/bin/vncserver -kill :1 >/dev/null 2>/dev/null'RETVAL=$?[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/vncecho;;restart)$0 stop$0 startRETVAL=$?;;*)


*)esacecho "Usage: vnc {start|stop|restart}"exit 1webMathematica User Guide 35exit $RETVALWindowsThe way to run programs automatically on Windows is to install them as a service.Installing Tomcat as a service on Windows is quite easy, since the installer will give you theoption of installing it as a service. If you did not choose this as an option when you firstinstalled Tomcat, you can rerun the installer.You can get extra information about the services you have installed by going to the AdministraÖtive Tools icon of the Control Panel. Here you will see a Services icon which you can open.The Services dialog that opens will show the services that have been installed on yourmachine. You should see one for Tomcat. The dialog will tell you if the service has started ornot and will tell you how it is launched. Typically the installer makes it an Automatic startuptype that causes it to launch when the computer is booted. Clicking the Tomcat entry andselecting Properties will give you a dialog, that allows you to configure the service.Running Tomcat as a service works well if the JDK is 1.4. The JDK is found by searching forjava.exe on the Windows path, so you need to make sure that the JDK you installed earlier isfound.Web Server ConnectionsIn some configurations, the main accessible server is a regular web server such as the ApacheHTTP server, the Microsoft Internet Information Server, or the Netscape Enterprise Server. It ispossible to use such a server in conjunction with a servlet container. This type of configurationis more complicated, but can take advantage of many additional features, for example, authenticationand URL rewriting, and is often suitable for an existing web infrastructure. This sectiongives a brief description of configuration for some typical arrangements. It is probably useful toconfigure your servlet container to work in a standalone mode before starting any of this work.If you wish to use webMathematica in conjunction with a separate web server, you will need tomake sure that all requests to webMathematica are forwarded to the webMathematica web


If you wish to use webMathematica in conjunction with a separate web server, you will need to36 webMathematica User Guideapplication. This will make sure that requests for applet archives, HTML pages, and images areproperly processed. If the server is only set to allow access to servlets, then these otherresources will not be accessible.If you just wish to test webMathematica running directly through a servlet container such asTomcat, you may skip this section.Apache and TomcatThere are a number of ways for the Apache web server to communicate with Tomcat. Oneconvenient way is to use an HTTP forwarding mechanism to send requests from the Apache webserver to Tomcat. This can be arranged with the ProxyPass configuration directive. A sampleconfiguration, that could be added to the Apache configuration file (typically called httpd.Öconf), is shown below.Order allow,denydeny from allProxyPass /webMathematica http://tomcatserver:8080/webMathematicaProxyPassReverse /webMathematica http://tomcatserver:8080/webMathematicaThe ProxyPass directive provides a mapping from a path to an external URL, and the ProxyPassÖReverse directive causes the responses to be modified so that the proxy is transparent. Anyaccess to /webMathematica will be sent to port 8080 on the machine tomcatserver. The configu-ration also denies access to the kernel monitor via the proxy. The features of the kernel monitorare described in a later section.For the ProxyPass directive to be effective, the modules mod_proxy and mod_proxy_http mustbe loaded, this can be done with the following configuration information in the Apache configurationfile.LoadModule proxy_module modules/mod_proxy.soLoadModule proxy_http_module modules/mod_proxy_http.soFor more information on using Apache and Tomcat, you should consult the websites for Apache,http://httpd.apache.org, and Tomcat, http://jakarta.apache.org. Note that you can run Apacheon both Windows and Unix machines, as well as Mac OS X machines. Another useful website ishttp://www.galatea.com/flashguides/apache-tomcat-4-win32.xml.


webMathematica User Guide 37Microsoft Servers and TomcatIf you wish to deploy Microsoft PWS or IIS as your web server, it is possible to use them withTomcat as a servlet container.Tomcat comes with instructions for configuring it as a servlet container for IIS and PWS. Theconfiguration has to be done manually, and, although straightforward, it has a number of stepsthat must be followed carefully and involves editing the Windows registry by hand.You need to make sure that you edit the workers.properties file, found in the Tomcat confdirectory, to give values to workers.tomcat_home and workers.java_home. The requiredsettings will be clear from the description in the file.TestingYou should now be able to restart your server and connect to webMathematica. Note that youmay have to modify the URLs shown in this document to connect to your servlet container; forexample, the URL may require a different port number than 8080, which is chosen as thedefault port for direct access to Apache Tomcat. The URL that you use to test your servletcontainer will show the correct URL to use for webMathematica. In addition, you should notethat the URL is case sensitive, so make sure to type in capitals as they appear.You may first want to connect to the webMathematica front page via http://localhost:8080/webMathematica; this should look similar to the picture below. It contains links to examples,documentation, templates, images, and external references.


38 webMathematica User GuideAfter this, it may be good to try some of the active examples, such as Expand, which can bereached from a link on the front page and from a URL such as http://localhost:8080/webMathematica/BrowseExamples/Expand.html. Enter parameters into the input fields and clickEvaluate; it should look similar to that shown below.It may also be a good idea to test a graphics example such as http://localhost:8080/webMathematica/Examples/Plot.jsp. If you are running on Unix, you will need to configure yourX server specially (as described here) to generate graphics and use other features of theMathematica front end. It is a good idea to test that this works correctly.If you have problems and cannot connect, go to the section on Troubleshooting.


Basic ExamplesThis covers a number of initial examples of webMathematica. Many of these can be copied andused as the basis for your own work.These examples are a form of JavaServer Pages (JSPs) that use a special library of tags thatwork with Mathematica. JSPs support the embedding of Java into HTML, and are frequentlyused with Java Servlets to develop large dynamic websites. The library of tags is called the MSPTaglib and will work on any compliant servlet engine. One advantage of the use of a tag libraryis that it can completely hide any use of the Java programming language; this is the case withthe MSP Taglib.Here, you can learn the basics of webMathematica scripts. This requires some knowledge ofHTML, including form and input elements. A reference to HTML is included at the end of thisdocument. If you have no understanding of form elements, it will be hard to write interactiveexamples for webMathematica.The description given here will work through a collection of sample JSPs, each of which willdemonstrate some detail or feature. The sources for all these examples are included in thewebMathematica web application in the directory Examples (the full path in Tomcat would bewebapps/webMathematica/Examples). If you followed the installation steps when you installedyour server, you should be able to see these examples running live in your server. Please notethat these examples are designed to be simple examples of how to program with webMathematicatechnology and have not been created for pleasing visual appearance.These examples can be reached from the webMathematica home page, which you should beable to reach via http://localhost:8080/webMathematica. (You may have some other URL foraccessing your server.) The home page shows examples wrapped up in a template that addsmore design around the pages to give them a better visual appearance. To study the details ofhow to program for webMathematica, this extra design may be a distraction and it is also possibleto reach the examples without using the template.When you have finished, you may wish to look at Developing Your Own Pages. This gives someideas for starting to develop your own site.


40 webMathematica User GuideHello.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Hello.jsp. (You may have some other URLfor accessing your server.)This example evaluates the Date[] function of Mathematica. The result changes each time thepage is accessed, demonstrating that this really is a dynamic process. The source for this pageis in webMathematica/Examples/Hello.jsp. standard jsp headersstandard html tagsHello WorldHello WorldDate[]Date::usageIts current value is:Date[]evaluated by Mathematicaevaluated by MathematicaThis example shows a basic use of webMathematica.This page uses standard HTML tags as well as special webMathematica tags; these have theform . The webMathematica tags are executed from the top of the page to thebottom. The contents of the tags are sent to Mathematica for computationwith the result inserted into the final page.


webMathematica User Guide 41Working with Variables: Variables.jspIf you installed webMathematica as described above, you should be able to connect to this MSPvia http://localhost:8080/webMathematica/Examples/Variables.jsp. (You may have some otherURL for accessing your server.) It demonstrates how variables are connected to input values.The source for this page is in webMathematica/Examples/Variables.jsp.Assigning VariablesAssigning VariablesEnter something: $$inputhtml formfield for user inputbutton for activating formevaluated by MathematicaThis example shows how to use form variables with webMathematica.This page is more elaborate because it contains form and input elements. These are importantways for allowing interaction from the client.


42 webMathematica User GuideA form element is a block of HTML that may contain input elements. A form may be activatedwith an input of type submit; this sends the name and value associated with each input tag tothe server. Here, the opening tag of the form element contains two attributes. The actionattribute refers to a URL that is accessed when the form is activated. In this case, it is a relativeURL that refers to the original Variables script. The method attribute tells the browser whatHTTP 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 thesecond 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 JSP). Text entered into the input tag, which uses the name tmp, will beassigned to the input variable $$tmp.The first time the page is accessed there is no value for $$tmp. When a value is entered in thetext field and the Evaluate button pressed, $$tmp gets a value that is displayed. Note that thevalue is a Mathematica string~if you try and enter a computation such as "5+7", no computationis actually done. If you want the input to be interpreted and evaluated by Mathematica,you need to use one of the MSP functions.Note that the $$ prefix is used to label input variables; these are variables that are sent withthe HTTP request. The use of variables is discussed further in Tips and Tricks: Variables.MSP Functions: Expand.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Expand.jsp. (You may have some otherURL for accessing your server.)When the submit button is pressed, the polynomial is raised to the power and expanded, andan HTML page that contains the result is returned. The source for this page is in webMathematiÖca/Examples/Expand.jsp. A section that shows the form tag is shown below.


webMathematica User Guide 43Expanding PolynomialsExpanding PolynomialsEnter a polynomial (e.g. x+y): Enter a positive integer (e.g. 4): MSPBlock[{$$expr,$$num},Expand[$$expr^$$num]]secure computation with input variablesThis example demonstrates expanding polynomials.This page contains form and input tags as described in the previous example. Additionally, themsp:evaluate tag refers to the MSP function MSPBlock.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 isentered, the symbols will not have any definition.


44 webMathematica User GuideMathematica now evaluates the contents of the msp:evaluate tag. The MSPBlock command isa programming construct, which here inspects two input variables, $$expr and $$num. If eitherof these has no value, MSPBlock returns a null string, which is why the first time you access thepage, 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 bodyof 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 inthe HTML page, which is returned to the client.Interpretation of the variables by Mathematica can fail in two ways: the input might not bevalid Mathematica input (for example, f[}), or it might be dangerous input (such asReadList["/etc/passwd"]). In both cases, the inputs are rejected and an error messagegenerated. This demonstrates some of the security features of the system, which the Securitysection documents in detail. The use of variables is discussed further in Tips and Tricks:Variables.The formatting of the result of an msp:evaluate tag is discussed in more details in AdvancedTopics: Evaluation Formatting.Graphics: Plot.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Plot.jsp. (You may have some other URLfor accessing your server.)This example generates a plot. The source for this page is in webMathematica/Examples/Plot.jsp. A section that shows the form tag is shown below.Enter a function:remember input settings from one call to the nextEnter a number:


webMathematica User Guide 45The example shows the use of the MSP functions MSPBlock and MSPShow. MSPBlock is aprogramming construct introduced in the previous section. MSPShow takes the Mathematicagraphics object from the Plot command and generates a GIF image, which is stored on theserver, returning an tag. A further discussion on formatting mathematics and graphics isgiven in the section on Displaying Mathematics and Graphics. Note how the page usesMSPValue to keep the user input each time the page is used.Typeset Images: Integrate.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Plot.jsp. (You may have some other URLfor accessing your server.)This example allows the user to enter a function to be integrated. The result is then formattedby the typesetting system and saved as an image. The source for this page is in webMathematica/Examples/Integrate.jsp. A section that shows the form tag is shown below.Integrate A FunctionIntegrate A Functionintegrand = Null;kernel request variable to hold the integrandIf[ MSPValueQ[ $$expr],integrand = MSPToExpression[$$expr]]; interpret input with secure conversionInput:


46 webMathematica User GuideIf[integrand =!= Null,MSPFormat[Integrate[integrand,x], StandardForm]]carry out the integrationThis example shows how to generate typeset output with webMathematica.In this example, an msp:evaluate tag integrates an expression and uses MSPFormat to formatthe 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 variables with MSPToExpression. This is analternative to using MSPBlock suitable in certain constructions, for example, when the input willbe used in a number of computations. The page variable integrand is initialized to Null andlater, if its value has been modified, the integration is carried out. It is assigned to the interpretedvalue 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 andintegrand will remain assigned to Null.Note that MSPToExpression applies a security check to the input variable. You should be awarethat input variables are a major source of danger and always use the secure conversion functionsMSPBlock and MSPToExpression. In particular, you should never use ToExpression on aninput variable. The Security section documents the security system in more detail.It is also possible to return the result using MathML; this is described in greater detail in thesection on MathML. A further discussion on formatting mathematics and graphics is given in thesection on Displaying Mathematics and Graphics.


webMathematica User Guide 47An interesting point about the first msp:evaluate tag is that it contains two Mathematica commands.To use two commands in the same tag, they can be separated with a semicolon ';'. Inaddition, the last command is also followed by a semicolon. This makes sure that no outputfrom the tag is inserted into the output page. More information on adding code into webMathematicapages is given in Tips and Tricks: Coding in Pages.Live 3D Plotting: Plot3DLive.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Plot3DLive.jsp. (You may have someother URL for accessing your server.) It allows the user to enter a function to be plotted by theLiveGraphics3D applet. The source for this page is in webMathematica/Examples/Plot3DLive.jsp.Live 3D PlottingLive 3D PlottingPlot3D of x from:to: y from:


48 webMathematica User Guide${msp:evaluate('MSPValue[ $$y0, "-2"]')}"/>to: Number of points to plot: $ImageBackground = "#ffffff";$ImageSize = {300,300};MSPBlock[{$$fun, $$x0, $$x1, $$y0, $$y1, $$pts},MSPLive3D[Plot3D[$$fun, {x, $$x0, $$x1}, {y, $$y0, $$y1}, PlotPoints -> $$pts]]]This example shows how to use live three-dimensional graphics withwebMathematica.This example uses a number of evaluations to set up parameters. The last evaluation takes thevalues of these parameters and uses them in a call to Plot3D. The result of this goes toMSPLive3D, which calls the LiveGraphics3D applet. This gives a real-time rotation of the threedimensionalgraphics object. More information in found in the section Mathematics and Graphics:LiveGraphics3D.Getting Messages: Messages.jspThis example demonstrates how messages and print output generated by Mathematica can bereturned in the web page. If you installed webMathematica as described above, you should be


webMathematica User Guide 49able to connect to this JSP via http://localhost:8080/webMathematica/Examples/Messages.jsp.(You may have some other URL for accessing your server.) The source for this page is inwebMathematica/Examples/Messages.jsp.Message and PrintMessage and PrintInput is 1/01/0Input is Sin[x,1]Sin[x,1]Input is Print["The result is ", x^2];5.6Print["The result is ", x^2];5.6The messages were:ColumnForm[MSPGetMessages[]]messages displayed here


50 webMathematica User GuideThe print output was:ColumnForm[MSPGetPrintOutput[]]print output displayed hereThese are some evaluations that will cause messages to begenerated by Mathematica. There is also a Mathematica printstatement.The contents are very simple; there are two evaluations that cause messages to be generated.These are followed by uses of MSPGetMessages and MSPGetPrintOutput, both of which areformatted by ColumnForm. The messages that were generated are displayed in the resultingpage.Returning General Content: Content.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Content.jsp. (You may have some otherURL for accessing your server.)All of the examples up to this point return HTML to the browser, but the web can work withgeneral content involving many different formats. MSPReturn is provided to allow an MSP toreturn arbitrary content. Here is an example that demonstrates how different formats can bereturned. The source is in webMathematica/Examples/Content.jsp and webMathematica/WEB-INF/Applications/ExampleUtilities/Content.m.First, here is the source.


General ContentwebMathematica User Guide 51General ContentPlease select a format:


52 webMathematica User GuideNeeds["ExampleUtilities`Content`"]If[MSPValueQ[$$button],MSPReturn @@ GeneralContent[$$button]]This example takes a format type and converts a notebook intothis format type. It returns the converted notebook.Here is the Mathematica source.MakeNotebook[fmt_] :=Developer`UseFrontEnd[Module[{nb, nbobj},nb = NotebookCreate[];NotebookWrite[nb, Cell["A Dynamically Created Notebook","Title"]];NotebookWrite[nb, Cell["Converted to " fmt, "Subtitle"]];NotebookWrite[nb, Cell["The date is " ToString[Date[]],"Text"]];SetOptions[nb, WindowSize -> {400,500}];nbobj = NotebookGet[nb];NotebookClose[nb];nbobj]]GeneralContent[fmt_] :=Module[{nbobj},nbobj = MakeNotebook[fmt];Developer`UseFrontEnd[AbortProtect[Switch[fmt,"Notebook",{ToString[nbobj, InputForm], "application/mathematica",


webMathematica User Guide 53"Content.nb"}"Content.eps"}"Content.pdf"}]]]],"PostScript",{ExportString[nbobj, "EPS"], "application/eps",,"PDF",{ExportString[nbobj, "PDF"], "application/pdf",,"GIF",{ExportString[nbobj, "GIF"], "image/gif", "Content.gif"},_,"Unknown format"In this example, one evaluation tests the variable $$button. If it has a value from activatingone of the buttons in the form, this is used to specify a return format type and passed to afunction, GeneralContent. The Mathematica code for this function is placed into a separatepackage to be loaded when the variable is set. GeneralContent calls a function that creates avery simple notebook, MakeNotebook. MakeNotebook generates a notebook using the MathematicaNotebook API and the function Developer`UseFrontEnd. In a real life situation a moreinteresting notebook would probably be generated. MSPReturn returns the representation of thenotebook to the server with the content type. This is then returned to the browser, which, ifsuitably configured, will deploy the necessary helper application.In a more advanced example, the dynamically generated notebook would probably use informationsent with the request from the client.If you wish to return special content and also set a filename to be used with this content, thenyou may wish to use the three-argument form of MSPReturn.Another way to set the content returned from an MSP script is to use MSPPageOptions. Thetopic of returning general content is discussed later.


54 webMathematica User GuideInteractive Web: SliderPlot.jspThis example demonstrates webMathematica interactive web technology.If you installed webMathematica as described above, you should be able to connect to this pagevia http://localhost:8080/webMathematica/Examples/Manipulate/SliderPlot.jsp. (You may havesome other URL for accessing your server.) The source for this page is in webMathematica/Examples/Manipulate/SliderPlot.jsp.First, here is the source.Manipulate Example: Slider, Checkbox, and PlotManipulate Example:Slider, Checkbox, and PlotNeeds["MSPManipulate`"]MSPManipulateHeader[$$updateArgs, $$manipulateNumber]MSPManipulate[ Plot[ Cos[var+x], {x,0,2Pi}, Frame -> frame], {var, 0,20},{frame, {True,False}}, OutputSize->{621, 384}]Slider and Checkbox


webMathematica User Guide 55The example has three key sections. First, the MSPManipulate` package is loaded with theNeeds statement. This needs to be done in its own evaluate tag, and at the start of the page.Secondly, a special header is put down with a call to MSPManipulateHeader. This needs to referto the variables $$updateArgs and $$manipulateNumber exactly as shown (note that youcannot rename these variables). MSPManipulateHeader initializes the interactive features.Thirdly, a particular interactive example is put down with MSPManipulate. This follows thesyntax of the Manipulate function, introduced in Mathematica 6. In the example here, a sliderand a checkbox are returned in the page.More information about webMathematica interactive features is found in the section InteractiveWeb Tools.Applets: TextApplet.jspThis example demonstrates how to call on the services of a Mathematica-powered website froman applet. This shows a combination of client and server programming. The section involvessome programming in Java.If you installed webMathematica as described above, you should be able to connect to this pagevia http://localhost:8080/webMathematica/Examples/TextApplet.jsp. (You may have someother URL for accessing your server.) The source for this page is in webMathematica/Examples/TextApplet.jsp and webMathematica/WEB-INF/src/ExampleApplets/TextApplet.java.First, here is the JSP source.Text Applet ExampleText Applet Example


56 webMathematica User GuideIf[MSPValueQ[$$Compute],MSPReturn["Date[] returns " ToString[Date[]], "text/plain"]]Here is an applet that gets a result from Mathematica.Hitting refresh will cause the page to update.Here is the source for the applet TextApplet.java.package com.wolfram.msp.example;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);}


webMathematica User Guide 57}}b = out.toByteArray();g.drawBytes(b, 0, b.length, 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 whichis formed from the document that loaded the applet, and the value of the parameter ArgumenÖtURL, which is passed in from a param tag. This causes the TextApplet JSP to be called andreturn a computation of the date.JavaScript: PlotScript.jspThis example demonstrates how to integrate a Mathematica-powered website with JavaScript.It also demonstrates both client and server programming. The section involves some programmingin JavaScript.Note that JavaScript and Java are different languages. JavaScript is a scripting language that isuseful for manipulating documents and other features of browsers. Java is a general purposeprogramming language that can be used in an HTML document via an applet. The two languagescomplement each other: JavaScript is useful for manipulating the browser and documentsthat are open in the browser, while Java has a more sophisticated collection of functionsand can draw into the browser window. It is possible for JavaScript and Java to work together.If you installed webMathematica as described above, you should be able to connect to this MSPvia http://localhost:8080/webMathematica/Examples/PlotScript/PlotScript.jsp. (You may havesome other URL for accessing your server.) The source for this page is in webMathematica/Examples/PlotScript/PlotScript.jsp and webMathematica/Examples/PlotScript/PlotScript1.jsp.First, here is the source for PlotScript.jsp.


58 webMathematica User GuidePlotting with JavaScriptfunction plot(f) {win = window.open( "PlotScript1.jsp?fun=" + URLescape(f.fun.value) +"&x1=" +URLescape(f.x1.value), "plot","toolbar=none,resizeable=yes,width=450,height=350");}Plotting with JavaScriptEnter a function: Enter a number: This example shows an example of JavaScript and webMathematica.Second, here is the source for PlotScript1.jsp.Plotting with JavaScript


webMathematica User Guide 59MSPBlock[ {$$fun, $$x1},MSPShow[ Plot[$$fun, {x,0,$$x1},ImageSize->400]]]This is a simple example given to demonstrate how a JSP can work with JavaScript. The initialpage, PlotScript.jsp, puts up a page with a form of two text input elements and one submitbutton. When the button is clicked, it opens a new window that contains the output ofPlotScript1.jsp.Setting Variables: SetBasic.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/SetBasic.jsp. (You may have some otherURL for accessing your server.)This example passes values computed in a JSP into Mathematica where they are used for compu -tation by Mathematica. This example uses the Java programming language making it differentfrom most webMathematica examples, typically these do not require any Java programming.The source for this page is in webMathematica/Examples/SetBasic.jsp and is shown below.&lt;set&gt; Tag Example


60 webMathematica User Guide&lt;set&gt; Tag ExampleNest[f, x, var1]ToCharacterCode[var2]var3@hashCode[]This example shows how a general JSP can set values in webMathematica.In this example, a variable num, which is an int, str, which is a String, and obj, which is anObject, are created in the JSP. These are then passed to Mathematica using the msp:set tag.This tag takes two attributes, the name attribute gives the name that the variable will be givenin Mathematica, while the value attribute refers to the value. If the variable is of a primitivetype, such as int, char, or double, then it needs to use the appropriate value attribute, such asintValue, charValue, or doubleValue. Notice how msp:set sends a Java int as a Mathematicainteger and a Java String as a Mathematica string. The Java Object is sent as a Mathematicaobject reference. The rules that govern how types are sent from Java to Mathematica areexactly those that J/Link uses.Getting Variables: GetBasic.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/GetBasic.jsp. (You may have some otherURL for accessing your server.)


webMathematica User Guide 61This example gets values computed in Mathematica into a JSP where they are used for processingby the page. The source for this page is in webMathematica/Examples/GetBasic.jsp, anda selection is shown below.num = RandomInteger[{1, 10}];list = RandomReal[{0, 1}, num];mean = Mean[list];${d}In this example, Mathematica generates a list of random numbers and computes the mean. TheJSP obtains these values using the msp:get tag. The setting of the value attribute is used as aMathematica expression to be evaluated and transmitted to Java. This is stored as a pagecontext variable using the name attribute setting of the tag. The rules for transmission fromMathematica are that the normal J/Link type conversions will be applied, but if none of theseapplies, then the object will be converted into an object of type com.wolfram.jlink.Expr, a classthat is provided by J/Link to represent general Mathematica expressions.The example also makes use of extended JSP tags. It also requires programming in both Javaand Mathematica. It shows how easy it would be to incorporate webMathematica into an existingJSP framework.


Developing Your Own PagesOnce you have installed and configured a webMathematica server so that the examples runcorrectly and have studied the basics of writing material for webMathematica, as describedpreviously, you are ready to start developing your own material.One way to start is to make your own area in the webMathematica web application. You couldmake a directory here (for example NewScripts) and copy one of the samples (for examplePlot.jsp) from the Examples directory. You could then access this script with the URLhttp://localhost:8080/webMathematica/NewScripts/Plot.jsp.This might be a good time to revisit the webMathematica index page found athttp://localhost:8080/webMathematica/index.html, which provides a number of links thatdemonstrate features of webMathematica. When you actually want to write your own material,you may look at the Tips and Tricks described in this chapter. The chapter continues to describeother page development utilities that are part of webMathematica.<strong>Wolfram</strong> Workbench<strong>Wolfram</strong> Workbench provides tools for developing solutions and applications based on <strong>Wolfram</strong>products such as Mathematica and gridMathematica, http://www.wolfram.com/products/workbench. It also includes support for webMathematica.More information can be found in the Workbench documentation, but the following gives asummary of some of the main features.webMathematica Projects<strong>Wolfram</strong> Workbench is a project-based system, and to work with webMathematica it supports atype of webMathematica project. This allows you to develop your web pages and Mathematicacode, perhaps archiving it in a code repository. You can test the individual components, andthen deploy them to the server to actually use them.


webMathematica User Guide 63Syntax Support for JSP Pages<strong>Wolfram</strong> Workbench provides a variety of syntax support for JSP pages. This includes showingboth XML, HTML, and JSP syntax errors. Of particular value are reports on Mathematica syntaxerrors inside of evaluate tags.Authoring Pages<strong>Wolfram</strong> Workbench provides a number of tools that help writing JSP and HTML pages. Theseinclude command completion and preview features. In addition, a palette is provided thatallows templates for entire page structures to be added.Wizards<strong>Wolfram</strong> Workbench offers a number of wizards for creating webMathematica material such asan entire project or a new web page.Server Interaction Tool<strong>Wolfram</strong> Workbench contains a tool that works with the actual server. From this you can carryout tasks such as starting or stopping the server, deploying your project, and connecting with adebug session.Full webMathematica Documentation<strong>Wolfram</strong> Workbench contains the webMathematica user guide, along with other material specificto the Workbench tools. This is probably the most convenient way to read the documentation.Debugging for Mathematica Code<strong>Wolfram</strong> Workbench provides a debugger for Mathematica code. You can use this debugger toconnect to the server and follow your code as it executes, setting breakpoints to halt in particularlocations.More information is available in the debugging section.Tips and TricksThis section provides a summary of a few issues that will help you to get started writing yourown pages. These are all described in more detail in later sections of the documentation, butare collected together here in a brief description. Getting a good grasp of these points will helpyou to make progress in developing your site.


64 webMathematica User GuideVariablesThere are two types of variables that are important for you to understand when you are gettingstarted with webMathematica: input variables and page variables.Input variables come with the HTTP web request, for example from an input field in an HTMLform. You can identify input variables in Mathematica code because they are labeled with a '$$'prefix. In the example below, the setting variable may be sent from an input field. In Mathematicacode it is called $$setting.If[ MSPValueQ[ $$setting],....]You should be aware that input variables are a potential security risk to your server. Therefore,you should always use the special functions, MSPBlock and MSPToExpression, for convertinginto Mathematica input. In particular, you should never use ToExpression on an input variable.An example of using MSPBlock is shown below.MSPBlock[ {$$fun},Integrate[ $$fun, x]]Page variables are Mathematica variables that you use to hold intermediate values. They arecalled page variables since they are cleared when the page is finished. In the example below,the page variable tmp is used to hold the expression that was entered into the text input field(which is held in an input variable called $$expr). Note the use of the secure function, MSPToExÖpression, to convert the Mathematica expression from the input.


webMathematica User Guide 65tmp = Null;tmp = MSPToExpression[ $$expr] ;If[ tmp =!= Null,....]If you want your variable to persist from one page to another, you can declare it as a sessionvariable. This and further details of variables are discussed in detail in Advanced Topics:Variables.Coding in PagesThe purpose of webMathematica is to use Mathematica for web computation; a key part of thisis placing Mathematica code in your web pages. This is done with evaluate tags, as follows.Integrate[ 1/(1-x^3),x]Note that the Mathematica code will evaluate in the typical way for Mathematica and the resultof the computation will appear in the web page. You can use MSPFormat to change the way thatthe result is formatted; more information on formatting in webMathematica is found inAdvanced Topics: Evaluation Formatting. An example of MSPFormat is shown below; this formatsthe integral into TraditionalForm using a GIF image to display the result.MSPFormat[ Integrate[ 1/(1-x^3),x], TraditionalForm]If you do not wish to see the result in the web output, you can suppress it by using a semicolon';'. In the following example an assignment is made to the variable x, but no output appears.


66 webMathematica User Guidex = 109;A final tip for working with code in webMathematica pages is the separation of multiple computationsin a single evaluate tag by using a semicolon ';'. This is shown below.x = 109;y = 44.5;{x+y}More information on coding in webMathematica pages is found in Appendix: MSP Taglib, whichgives a detailed reference on the webMathematica tags.TemplateswebMathematica provides a number of templates and other utilities that can be used to incorporatemore design into your webMathematica material.Browse ExamplesThe webMathematica examples can be reached from the webMathematica home page, whichyou should be able to reach via http://localhost:8080/webMathematica. (You may have someother URL for accessing your server.) The home page shows examples wrapped up in a templatethat adds more design around the pages to give them a better visual appearance. Thistemplate makes use of HTML frames and so it would be relatively easy to modify your own workto make use of it.Design ExamplesAs you develop your own material, you may wish to look at the design examples. These are acollection of samples that make use of colors, fonts, and images for a more professional appearance.You can access the design examples from the main index page, or with a URL such ashttp://localhost:8080/webMathematica/DesignTemplates/DesignTemplate1.jsp.


webMathematica User Guide 67Banners and ButtonsA collection of banners and buttons are available for use in your pages, which you can find withthe link http://localhost:8080/webMathematica/BannersImages/. To use one of these images,such as the banner webm-white.gif, you can use an img tag such as the following.The section on including static files has more information on how to include images.Certain license options for webMathematica require that you use an approved banner for yoursite. You may use one of these banner images in order to comply with this requirement.Minimal InstallationWhen you have confirmed that your webMathematica site is running correctly and you start todevelop your own material, you may wish to strip out all of the documentation and examples toget a minimal installation. The minimum set of files for webMathematica is that everything inthe WEB-INF directory must be kept.Minimal File LayoutwebMathematicaWEB-INFeverything in hereIn addition you can remove all the J/Link native libraries from webMathematica/WEB-INF/lib/SystemFiles/Libraries except for the library required for your system, which is locatedin a directory named by $SystemID.


ApplicationsThis section shows how to use webMathematica in a number of specific applications.XMLXML is a general data format that is becoming increasingly important. Data that is formatted inXML can readily be used by applications that are able to process it. In this case the choice of anXML format means that you will save considerable development effort. In addition there are anincreasing number of existing data formats that use XML. Some of the more important formathematical and scientific purposes include XHTML (an XML compliant version of HTML),MathML (a way to store mathematical information), and SVG (a graphics format). A large list ofXML applications is available at http://www.xml.org.Mathematica contains a large number of features for working with XML, all of which are availablein webMathematica. XML can be very useful for webMathematica with its support for specificXML applications and as a general format for data interchange. The use of MathML, SVG,and XHTML will be covered in their own sections. This section will give an overview of XML andthe XML features of Mathematica. It will also give some examples of why this functionality isuseful to webMathematica.Introduction to XMLThis section will give a very brief introduction to XML. For more information, go to one ofthe many references such as those detailed at http://www.w3.org/XML/, for example,http://www.w3.org/XML/1999/XML-in-10-points.


webMathematica User Guide 69A sample XML document is shown below.A New Kind of ScienceStephen <strong>Wolfram</strong>The Lord of the RingsJ.R.R. TolkienThe example above shows a data format for a library. The library contains books and each bookhas a title and an author. This shows how XML is suitable for structured data. In addition, youcan see how XML looks a little like HTML, except that the tags (words bracketed by '')are not restricted to a fixed set since new tags, that are suitable for a particular application, canbe introduced. Unlike HTML, the format of XML is stricter with a valid XML document beingrequired to follow rules that do not apply to HTML. This is demonstrated in the next section.XML ComplianceOne issue with XML is that documents must be wellformed, following the rules of XML. Somebasic examples of compliance are described in this section.An XML document must include a header. For example, it must start with something like thefollowing.Empty elements must either have an end tag, or the start tag must end with />. Thus, thefollowing is legal.However, this is not legal.For nonempty tags, the end tag is required. Thus, the following is legal.Here is a paragraph.Here is another.


70 webMathematica User GuideHowever, this is not legal.Here is a paragraph.Here is another.Mathematica Support for XMLMathematica provides some very convenient ways to work with XML. Many of these are basedon the strong correspondence between structured XML documents and Mathematica expressions(the basic data type of Mathematica). This makes it easy to import XML data into Mathematicaand then work with it. This section gives a very brief introduction to working with XML inMathematica; more information is available in the online documentation.The following is a simple example.In[1]:= xml ="\n \n \n ANew Kind of ScienceStephen <strong>Wolfram</strong>\n\n \n The Lord of the RingsJ.R.R. Tolkien\n \n";This XML can be imported into Mathematica, which represents it with symbolic XML. Because ofthe nature of Mathematica expressions, symbolic XML is a Mathematica native form of XML thatis isomorphic to textual XML.In[2]:=sym = ImportString@ xml, "XML"DOut[2]= XMLObject@DocumentD@8XMLObject@DeclarationD@Version Ø 1.0D


webMathematica User Guide 71This outputs the new XML expression.In[5]:=ExportString@newSym, "XML"DOut[5]= a new kind of sciencestephen wolframthe lord of the ringsj.r.r. tolkienThis type of transformation can of course be done in other ways. For example, the use of XSLTstylesheet technology provides one way. However, there is an overhead to setting up an XSLTstylesheet to make the transformation. The use of Mathematica, with its uniform programmingprinciples, is often a quick and simple way to get the task carried out.There are many more features of the Mathematica XML tools, for example, working withattributes, entities, namespaces, validation, and CDATA. More information is available from theMathematica documentation.webMathematica XML ApplicationsMany webMathematica applications involve generating HTML to be read by browsers. However,the output from a webMathematica site may not go to a browser; it may involve some data tobe read by an application that will then do further processing. This section will study an examplethat shows how this can be done.The source for this example is in webMathematica/Examples/XML/Phone.jsp andwebMathematica/Examples/XML/Processed.jsp. It also uses an XML file webMathematica/Examples/XML/phone.xml. If you installed webMathematica as described above, you should beable to connect to this JSP via http://localhost:8080/webMathematica/Examples/XML/Phone.jsp. (You may have some other URL for accessing your server.)


72 webMathematica User GuideThis shows the XML data.The contents of Processed.jsp are shown below.xml = Import[ToFileName[MSPPageDirectory[], "phone.xml"], "XML"] ;xml = First[Cases[xml, _XMLElement]];If[MSPValueQ[$$patt],xml = DeleteCases[xml,XMLElement["Person", {___,"Name"->n_/;!StringMatchQ[n, $$patt], ___}, _], Infinity]];ExportString[xml, "XML"]This example first imports the XML file into Mathematica. It uses the command MSPPageDirecÖtory because the XML data is located in the same directory as Processed.jsp. It then checksto see if a parameter name was sent. If this is the case, then it uses this to discard XML elementsthat do not match this name. You should be able to see the operation of thisparameter with a URL such as http://localhost:8080/webMathematica/Examples/XML/Processed.jsp?name=T. (You may have some other URL for accessing your server.) It ends byconverting the symbolic XML into a string version of the XML and returning this.Of course, you may want to use this XML data for further processing. If you have a system thatis XML-aware, this is quite straightforward. One useful application that is XML-aware is ofcourse Mathematica. For example, the following will call your webMathematica site and retrievethe information.


webMathematica User Guide 73In[1]:=XML`Parser`XMLGet@"http:êêlocalhost:8080êwebMathematicaêExamplesêXMLêProcessed.jsp"DOut[1]= XMLObject@DocumentD@8XMLObject@DeclarationD@Version Ø 1.0D, XMLObject@CommentD@This is a demonstration XML file that is used as an exampleby webMathematica. The example demonstrates how to returnXML from a webMathematica site.D


74 webMathematica User GuideOne resource for learning more about MathML is the <strong>Wolfram</strong> <strong>Research</strong> sponsored website,http://www.mathmlcentral.com. A section describing the evolution of MathML and some of theissues involved in developing a mathematical language suitable for a computation system suchas Mathematica is found at http://www.mathmlcentral.com/history.html.If you are not interested in the specific details of how MathML works and just want to useMathML in your output, then you should go to the sections Generating MathML and SendingMathML.Embedding MathML in Web DocumentsThis section discusses how documents can be written that mix both mathematics and text.These documents are written in XML format and use both MathML and XHTML (the XML compliantform of HTML). webMathematica contains functions that do all of this automatically, so youdo not need to read this unless you wish to learn more about the details of how browsers supportMathML.XHTMLXHTML is an XML compliant form of HTML, available as an official W3C recommendation,http://www.w3.org/MarkUp. It is very similar to HTML, except that for a document to be valid itmust follow the rules of XML. (Some of these were described in the previous section.) To usedocuments that mix mathematics and text, XHTML is required. Use of XHTML is needed anyway,since the W3C intends that HTML will not be developed further.The sample XHTML document illustrated below is very similar to HTML, except for the initialXML declaration and the DTD reference. The latter can be used by an XML parser to validatethat the input document is indeed valid XHTML. This demonstrates one of the benefits of XMLtechnology. That is, a parser can validate a document, checking details such as the differenttags being in the correct places and holding the correct number of arguments, without specializingin the particular flavor of XML. The reference to the DTD is not required; however, it isnecessary if the document is to be validated.


webMathematica User Guide 75Basic XHTML DocumentXHTMLThis is a basic XHTML document.This document could be read by modern web browsers and would display in the expectedfashion.XHTML and MathMLTo add mathematics and other technical notation to a text document, it is possible to write onedocument that contains both XHTML and MathML. A sample document follows.Basic XHTML+MathML DocumentXHTML+MathMLHere is a math expression.x2


76 webMathematica User GuideThis could be read into a browser that provides native support for MathML and would be read asexpected. Note the reference to a DTD that allows the embedding of MathML into XHTML toform an XHTML+MathML document.Unfortunately, not all browsers support MathML natively. While Mozilla, Amaya, and the mostrecent versions of Netscape do give native support for MathML, Internet Explorer does not.For MathML to work with Internet Explorer or older versions of Netscape, a plug-in mechanismmust be used. The way to do this is explored in the next section.Rendering XHTML and MathML DocumentsThe previous section showed how to embed MathML into XHTML, creating documents that mixtext and mathematics. It also explained that this does not work with browsers that rely on aplug-in mechanism. This section shows how to write documents that will work in a wide rangeof browsers.To support MathML in browsers using a plug-in mechanism, the document must use special tagsthat are relevant to the particular plug-in used. If the browser supports MathML natively, thenno special tags are needed. Of course, an author does not want to produce different versions ofeach document specific to each rendering technology. The solution is to make use of XSLTstylesheet technology to convert the document in the browser before it is viewed. This automaticallyinserts any special tags that are needed for plug-ins. An XSLT stylesheet that implementsthis solution is available from the W3C Math site, http://www.w3.org/Math/XSL.Here is a document that uses the MathML stylesheet.Basic XHTML+MathML DocumentXHTML+MathMLHere is a math expression.x


webMathematica User Guide 772This document can be rendered by any browser that is supported by the stylesheet. At thecurrent time this includes the following:Windows:1. Internet Explorer 5.5 with the MathPlayer plug-in2. Netscape 7.0 (and later)3. Amaya (Presentation MathML only)4. Firefox 1.0 (and later)Macintosh:5. Netscape 7.0 (and later)6. Firefox 1.1 (and later)Linux/Unix:7. Netscape 7.0 (and later)8. Firefox 1.0 (and later)9. Amaya (Presentation MathML only)See http://www.w3.org/Math/XSL for updates.By using an absolute reference to the stylesheet, documents that use the stylesheet found onthe W3C site can be moved from one server to another or saved locally and continue to work.One issue with an absolute stylesheet reference is that Internet Explorer may, according to itsconfiguration, give a warning or even reject the stylesheet altogether (leading to a failure torender the MathML). This can be solved with a relative reference to the stylesheet and byplacing a copy of the stylesheet on the same server as the document. For example, the documentcan start as follows.


78 webMathematica User GuideThis means that the stylesheet will be found at the URL /webMathematica/Resources/XSL/mathml.xsl relative to the root of the server from which the document is beingretrieved. If a server chooses to do this, it will work well with Internet Explorer, but it will benecessary to ensure that the server has an up-to-date version of the stylesheet. It will alsomean that documents will not be quite so portable when moved from one server to another.Note that the XHTML+MathML document shown above that uses the MathML stylesheet doesnot contain a DOCTYPE declaration. This is, of course, a limitation because the document cannotnow be validated. Another consequence is the XML system that renders it will not be awareof any special entity names. The DTD is missing because Internet Explorer does not accept allthe entities in the MathML DTD. The solution is to use MathML which refers to numerical ratherthan named entities.Here is an example that uses a named entity reference, &af;.sin&af;(x)This example uses the numerical value &#8289;. It is the preferred form.sin&#8289;(x)


webMathematica User Guide 79If you want to find the numerical value for any character, you can use the Mathematica functionToCharacterCode to generate the numerical value, and BaseForm to generate the hexadecimalform. For example, the unicode value of a capital phi can be found as follows.In[1]:= BaseForm@ToCharacterCode@"F"D, 16DOut[1]//BaseForm= 83a6 16


80 webMathematica User GuideThe following generates content MathML.MSPFormat[ expr, TraditionalForm, ContentMathML]Tools for working with MathML typically support both content and presentation.MathML Integrate ExampleThis example JSP uses the MathML stylesheet. The page is actually a combination of two JSPs,IntegrateForm.jsp and IntegrateXSLT.jsp, that use JavaScript. They are closely modeled onthe standard webMathematica examples PlotScript.jsp and PlotScript1.jsp. The source forthese MathML examples is available in webMathematica/Examples/MathML. If you installedwebMathematica as described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/MathML/IntegrateForm.jsp. (You may have someother URL for accessing your server.)You first see the source for the input page, IntegrateForm.jsp.MathML Example: Integrate a Functionfunction integrate(f, page){if ( page == 1)pageToLoad = "IntegrateXSLT.jsp"else if ( page == 2)pageToLoad = "IntegrateXML.jsp"elsepageToLoad = "IntegrateMathPlayer.jsp"win = window.open( pageToLoad + "?fun=" + URLescape(f.fun.value),"integrate","toolbar=none,resizeable=yes,width=450,height=350");}


webMathematica User Guide 81MathML Example: Integrate a FunctionEnter a function to be integrated: The following uses the MathML XSLT style sheet. Uses the general MathML XSLT style sheet, this is the most generalsolution.The following are alternatives for rendering MathML. They are notgeneral solutions, but are included for demonstration purposes. Returns XHTML+MathML, suitable for a browser with native MathMLsupport. Uses MathPlayer specific markup, suitable if you have MathPlayerinstalled.This example shows how MathML can be generated from webMathematica.This is standard HTML. When the input button is clicked, a JavaScript function is called thatextracts the input from the input field and calls the JSP IntegrateXSLT.jsp, which then opensin a new window. The contents of IntegrateXSLT.jsp are shown below.


82 webMathematica User GuideIntegrate ResultMSPPageOptions[ "ContentType" -> "text/xml"];fun = Unspecified;int = Unspecified;If[ MSPValueQ[ $$fun],fun = MSPToExpression[ $$fun];int = Integrate[ fun, x];If[ Head[int ] === Integrate, int = Unknown]] ;Integration of a function, formatting into MathML.FunctionIntegral MSPFormat[ fun,MathMLForm] MSPFormat[ int,MathMLForm]


webMathematica User Guide 83This uses the MathML stylesheet, which here is assumed to be installed in the webMathematicaweb application in the directory XSL. The output content type is set to text/xml, and the necessarycomputation in Mathematica is carried out.When this example works, it might be interesting to use the View Source menu of yourbrowser. It should be noted how the MathML flows naturally with the XHTML. Also note how thedocument does not state the physical size of each mathematical expression. This is very usefulbecause the size will only be known accurately when the document is rendered in the browser.The actual example code delivered with webMathematica is a little more complicated since itcontains alternatives for rendering directly with MathPlayer and for generating XHTML+MathML.However, the one shown above that uses the MathML stylesheet is the most general solution.The others are included in the example for demonstration purposes.SVGSVG is a language for describing two-dimensional graphics in XML. Like MathML it is an officialrecommendation of the W3C, http://www.w3.org/Graphics/SVG/. It provides a number ofbenefits for users of webMathematica. First, since it is a vector-based format the results oftenhave a higher quality than is typically the case with image formats. This is very much the casewhen considering print output. Secondly, for many types of image, the actual file size is oftenquite small especially compared with image formats. Thirdly, it supports a number of dynamicand interactive features. Mathematica can generate SVG from graphics and this section will givesome examples of web usage involving SVG. One thing to be noted is that any exampleswill require that your browser supports SVG. Ways to do this include the use of the Amayabrowser, http://www.w3.org/Amaya/, which provides native support, or the Adobe plug-in,http://www.adobe.com/svg.A utility package is provided with webMathematica that supports adding the necessary tags tohook into the Adobe plug-in. This section will give some simple examples of the use of thispackage with webMathematica.


84 webMathematica User GuidePlotting with SVGThe source for this example is in webMathematica/Examples/SVG/Plot.jsp. It is closelyrelated to the basic example, Plot.jsp. If you installed webMathematica as described above,you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/SVG/Plot.jsp. (You may have some other URL for accessing your server.)An extract of the source follows.Enter a function: Enter a number: Needs["MSP`SVG`"]MSPBlock[{$$fun, $$x1},SVGShow[Plot[$$fun, {x, 0, $$x1}]]]This is very similar to the basic example Plot.jsp. The differences between the two are theloading of the SVG support package and the use of the SVG plotting function SVGShow. If thisworks correctly, you may wish to use some of the features that the Adobe plug-in provides.SVG AnimationsSVG supports a number of animation and interaction features. This example will demonstratethe use of SVG animations.


webMathematica User Guide 85The source for this example is in webMathematica/Examples/SVG/NDSolvePlot.jsp. If youinstalled webMathematica as described above, you should be able to connect to this JSP viahttp://localhost:8080/webMathematica/Examples/SVG/NDSolvePlot.jsp. (You may have someother URL for accessing your server.)The source contains an HTML form that sets up a number of input fields to collect the equation,starting and ending points, as well as initial conditions. These are then fed to a function thatsolves the differential equation and returns a plot of the result formatted as SVG. The SVG isthen displayed with the function SVGDisplay, which is defined in the package MSP`SVG`. Thecode, which inserts the plot, is shown below.MSPBlock[ {$$eqn, $$t0, $$init1, $$init2, $$t1},svg = NDSolveToSVG[ $$eqn, {$$init1, $$init2}, {$$t0,$$t1}] ;SVGDisplay[ svg, {400, 300}]]The actual definition of the function that creates the SVG is shown below. This solves the differentialequation and generates a plot of the result. It then generates Symbolic XML, which representsthe SVG of the result, using the function XML`SVG`GraphicsToSymbolicSVG. Next, itfinds the points that represent the plot of the result and uses these to form an SVG animationof a red ball, which moves along these points. This animation is inserted into the SVG to form anew result, which is returned to be plotted.NDSolveToSVG[ eqn_, init_, lims_List]:=Module[ {sol, dep, t, int, t0, t1},{o,dep,t} = EquationToVariables[ eqn] ;{t0, t1} = lims ;sol=NDSolve[Append[init,eqn],dep,{t,t0,t1}];{int0, int1} = Part[dep /. First[ sol],1,1];If[ t0 < int0, t0 = int0];If[ t1 > int1, t1 = int1];p=ParametricPlot[ {dep[t],dep'[t]} /. sol,{t,t0,t1}, ImageSize ->400];xml = XML`SVG`GraphicsToSymbolicSVG[p];pts="M"First[Cases[ xml,XMLElement["polyline",{"fill" -> _,"points" ->x_},_]->x, Infinity]];newElem=XMLElement["circle",


86 webMathematica User Guide{"cx"->"0","cy"->"0","r"->".1","fill"->"red", "stroke"->"blue","stroke-width"->"0.01"},{XMLElement["animateMotion",{"dur"->"6s","repeatCount"->"indefinite","rotate"->"auto", "path" -> pts},{}]}];newXML=xml/.x:XMLElement["polyline",___] -> Sequence[x,newElem] ;ExportString[newXML,"XML"]]There are a number of other ways of obtaining interactive results with SVG. For example,JavaScript can interact with and manipulate the SVG tree, thereby supporting interactive featuressuch as popups when the mouse is moved over a graphic.HTML FormattingOne of the advantages of the HTML templating technique that webMathematica provides is thatthere is often little need to try and generate HTML formats with Mathematica programs. In fact,many of the HTML formatting issues can be left to web designers who can use their standardtools. However, sometimes it is useful to apply some HTML formatting functions to Mathematicaexpressions. This is particularly the case for HTML tables. In order to allow this, an HTML utilitypackage is provided with webMathematica that supports table formatting functions. This sectionwill explore the use of this HTML formatting. A more general discussion of output is available inthe section on Evaluation Formatting.Remember that if you want to return HTML that is not generated by the HTML package, youshould construct your own string of HTML and return this as shown in the example below.StringJoin[ "", ToString[ x], ""]The HTML FunctionsThe HTML functions are contained in a package, MSP`HTML`, which is part of the webMathematicalayout. Since the package is loaded when webMathematica starts there is no need to load


webMathematica User Guide 87the package manually. However, if you wish to use it in Mathematica outside of webMathematica,you will need to copy the package into your AddOns/Applications directory, described in aprevious section.HTMLTableFormAs explained above, the MSP`HTML` package is available for webMathematica and can beinstalled into regular Mathematica. It can then be loaded as shown below.In[1]:=Needs@"MSP`HTML`"DThe function HTMLTableForm takes an input and formats it into an HTML table.In[2]:=HTMLTableForm@ 88a, b, c


88 webMathematica User GuideIn[4]:=HTMLTableForm@ 88x^2, Sin@xD


webMathematica User Guide 89It is less suitable for formatting large expressions, since everything will come out in InputForm.In[4]:=Out[4]=Nest@ 1 ê H1 - ÒL &, x, 5D11 -111-11-11-1-xIn[5]:=HTMLFormat@% DOut[5]= 1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;x-1-1-1-1-1For larger expressions, the recommendation is to use one of the versions of the formattingfunction MSPFormat to gain a result in an image format or MathML.HTMLSelectAs explained above, the MSP`HTML` package is available for webMathematica and can beinstalled into regular Mathematica. It can then be loaded as shown below.In[1]:=Needs@ "MSP`HTML`"DThe function HTMLSelect provides a useful way to generate select tags with webMathematica.It takes a list of the different options and the name to be used when the selection is submitted.Its operation is shown below.In[2]:=HTMLSelect@ 8"a", "b", "c"


90 webMathematica User GuideIn[4]:=HTMLSelect@ 8"a", "b", "c"


webMathematica User Guide 91In[3]:=HTMLCheckbox@boxname, 10 > 5DOut[3]= webMathematica ExamplesA number of webMathematica examples are provided that make use of the HTML formattingpackage. These are shown in this section.Table FormattingA first simple example is Table.jsp, the source for which is available in webMathematica/Examples/HTML. If you installed the webMathematica webapp as described above, you shouldbe able to connect to it via http://localhost:8080/webMathematica/Examples/HTML/Table.jsp.(You may have some other URL for accessing your server.)A second example is RegressTable.jsp, the source for which is available in webMathematica/Examples/HTML. If you installed webMathematica as described above, you should be able toconnect to it via http://localhost:8080/webMathematica/Examples/HTML/RegressTable.jsp.(You may have some other URL for accessing your server.) A section of the contents is shownbelow.data = {{0.055, 90}, {0.091, 97}, {0.138, 107},{0.167, 124}, {0.182, 142}, {0.211, 150},{0.232, 172}, {0.248, 189}, {0.284, 209},{0.351, 253}};data = Map[# + {0, Random[Real, {-20, 20}]}&, data];lm = LinearModelFit[data, {1, x^2}, x];HTMLTableForm[MSPShow[ListPlot[data, Frame -> True, Axes -> False]],TableHeadings -> {"Data to be fitted"},TableAttributes -> {"cellpadding" -> "0", "cellspacing" -> "0"}]HTMLTableForm[


92 webMathematica User GuideHTMLTableForm[lm["ParameterTableEntries"], TableAttributes ->{"cellpadding" -> "0", "cellspacing" -> "0"}],TableAttributes -> {"cellpadding" -> "0", "cellspacing" -> "0"},TableHeadings->{"ParameterTable"}]This shows how the packages are loaded. Note how the subpackage must be loaded as well.The data is assigned (typically this would be loaded in some dynamic fashion), and the regressionanalysis is carried out. Two uses of HTMLTableForm then follow. In the first, the result ofMSPShow is put into a table with a heading. This is a convenient way to attach a border andheading to something. In the second, the parameter table, pTable, is put into a table. Thistable is itself put into another table to get a heading.Select FormattingAn example of the use of HTMLSelect is in Select.jsp, the source for which is available inwebMathematica/Examples/HTML. If you installed the webMathematica webapp as describedabove, you should be able to connect to it via http://localhost:8080/webMathematica/Examples/HTML/Select.jsp. (You may have some other URL for accessing your server.) Thesource is shown below.days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"};day = Null;If[MSPValueQ[$$daySelected],dayPT = MSPToExpression[$$daySelected];day = Part[days, dayPT]];HTMLSelect[days, daySelected, SelectedOptions -> day]


webMathematica User Guide 93If[day =!= Null,dayPT = Mod[dayPT + 1, 7, 1];"The day after the day selected is " Part[days, dayPT] "."]In this example, the input parameter $$daySelected is inspected and used to determine whichday was selected. The second evaluation actually puts down the select tag, showing how easythis is. The last evaluation computes the day after the day selected by incrementing the dayPTvariable and then takes its modulus with respect to 7 with an offset of 1.Interactive Web ToolsOne of the key features of Mathematica 6 was a simple way to construct user interfaces. Previously,user interface construction required specialist knowledge and expertise as well as complicatedtools. The result was that many users were not able to create their own user interfaces,they would work with specialists or go without the extra facility of a user interface. However,the new ideas and technology based on Manipulate, allowed users to create a wide range ofinteresting user interfaces without their needing to learn this special knowledge.webMathematica 3 introduced a web version of Manipulate technology, which is covered in thissection.Example: SliderPlot.jspThe core of an example web page that demonstrates the web interactive tools isSliderPlot.jsp. If you installed webMathematica, you should be able to connect to this pagevia http://localhost:8080/webMathematica/Examples/Manipulate/SliderPlot.jsp. (You may havesome other URL for accessing your server.) The source for this page is in webMathematica/Examples/Manipulate/SliderPlot.jsp.The source is shown below.


94 webMathematica User GuideManipulate Example: Slider, Checkbox, and PlotSlider, Checkbox, and PlotNeeds["MSPManipulate`"]MSPManipulateHeader[$$updateArgs, $$manipulateNumber]MSPManipulate[ Plot[ Cos[var+x], {x,0,2Pi}, Frame -> frame], {var, 0,20},{frame, {True,False}}, OutputSize->{621, 384}]There are three key parts to this page. First, the MSPManipulate` package is loaded withNeeds, as shown below. This must be done in its own evaluate tag, and at the start of thepage.Needs["MSPManipulate`"]Secondly, the special header is put down, with a call to MSPManipulateHeader. This must referto the variables $$updateArgs and $$manipulateNumber exactly as shown (note that youcannot rename these variables). MSPManipulateHeader initializes the interactive features.MSPManipulateHeader[$$updateArgs, $$manipulateNumber]Finally, you have to add the actual interactive code. This is done with a call to MSPManipulate;an example follows.


webMathematica User Guide 95MSPManipulate[Plot[ Cos[var+x], {x,0,2Pi}, Frame -> frame],{var, 0,20}, {frame, {True,False}}]MSPManipulate supports a number of different interactive controls, which are all similar tothose of Manipulate. Detailed information can be found in the function page for MSPManipulate.webMathematica contains a number of other examples of the use of its interactive web tools.These are all found in webMathematica/Examples/Manipulate.ControlsMSPManipulate has a syntax that is very similar to that of Manipulate. The default controls areshown below.8var, min, max


96 webMathematica User GuideIn the following example, the variable appears with the label "shift", and it has the initialvalue 10.MSPManipulate[Plot[ Cos[var+x], {x,0,2Pi}], {{var, 10, "shift"}, 0,20}]Formatting and OutputMSPManipulate takes a couple of options that control the formatting of the argument and theoutput size.optiondefaultFormatType StandardForm formatting for the argumentOutputSize Automatic output sizeOptions of MSPManipulate.MSPManipulate always formats its argument into an image; by default it uses StandardForm.However, it can be changed to format into TraditionalForm; this is shown in the followingexample.MSPManipulate[ Integrate[ 1/(1-^num),x], {num, 1,20,1},FormatType -> TraditionalForm]The size of the finished interactive web output can be controlled by the OutputSize option. Thishas a default that tries to keep track of the number of controls. If there is not enough space,then scrollbars will be added automatically. In the following example a size of 800 by 800 pixelsis used.MSPManipulate[ Integrate[ 1/(1-^num),x], {num, 1,20,1},OutputSize -> {800,800}]


webMathematica User Guide 97Underlying Technology and LimitationsThe web version of Manipulate is based on Flash web technology. Flash is commonly used toadd interactive features and effects to websites and is quite well supported over a variety ofdifferent platforms and browsers. webMathematica actually uses Flash 9, so any browser thatdoes not support this will not be able to support webMathematica interactive web tools.MSPManipulate does not support all the features of Manipulate. While it will increase its supportover time, any interactive example that uses Locator expressions is not going to work forsome time. Also, MSPManipulate only formats its argument into an image.Using Java APIsThe purpose of webMathematica is to allow Mathematica computations to be run by a webserver. These computations will typically involve one of the many tasks for which Mathematicais well suited, such as numerical or symbolic computation. However, sometimes it is useful in awebMathematica computation to call outside of Mathematica to gain some extra functionality.The most convenient way to do this is to make use of Java. Regular interactive Mathematicacan call to Java very easily with the J/Link toolkit, and webMathematica can do the same. Moreinformation on the concept of working with Java APIs and referencing Java objects from withinMathematica can be found in the J/Link documentation.In webMathematica two classes of calls can be distinguished: those to serverrelated APIs andthose to more general Java APIs. These are discussed in the following two sections.Server APIsCalls to server-specific APIs that govern the operation and details of a particular webMathematicasite are facilitated by definition of the following server objects.$ServletRequest$ServletResponseHttpServletRequest object for this requestHttpServletResponse object for this request


98 webMathematica User GuideThese are all Java object references maintained by J/Link and can be used in the typical J/Linkfashion. $ServletRequest holds a reference to the servlet HTTPServletRequest object and$ServletResponse holds a reference to the servlet HTTPServletResponse object. The variousmethods for these objects are documented as part of the servlet API and will be found in anyreference to servlets. For example, the request object has a method getRemoteAddr, which canbe used in an MSP as follows.$ServletRequest@getRemoteAddr[]This will return the IP address of the client that sent the request and is equivalent to the CGIvariable REMOTE_ADDR.A more elaborate example is found in Request.jsp, the source for which is available inwebMathematica/Examples. If you installed webMathematica as described above, you should beable to connect to it via http://localhost:8080/webMathematica/Examples/Request.jsp. (Youmay have some other URL for accessing your server.) This example extracts names and valuesfrom the HTTP request.Note that any Java object references created when processing a particular page will be releasedwhen the whole page finishes. Note that Java objects created during initialization of the kernelwill not be removed, providing a mechanism to maintain Java objects that persist from one callto another. Despite the fact that Java objects are automatically released, it is strongly recommendedthat all Java objects are either created inside of a call to JavaBlock or use ReleaseÖJavaObject explicitly. You can learn more about JavaBlock and ReleaseJavaObject in theJ/Link documentation.Other Java APIsThere are many other Java APIs that can be used by webMathematica. These include APIs fordatabase connectivity, XML processing, speech generation, data format I/O, and calling viaHTTP to other web services. All of these are readily available to webMathematica. For informationread the appropriate Java reference.


webMathematica User Guide 99Data Loading and ComputationMathematica contains a variety of data loading functions, available through the functionImport. This supports many formats such as comma and tab-delimited text data, as well asmore specialized formats for graphics, science, sound, and XML. In addition, binary data can beloaded using the function Experimental`BinaryImport. If you find that your particular data isnot well supported directly by Mathematica, it is possible that you may use a Java API to loadthe data, which was described in the previous section.In order to develop data loading technology, it is probably a good idea to work in interactiveMathematica so that you understand how the data loading functions work. When you have donethis, you can add data loading to your web applications. At this point you need to determine thesource for your data. The following sections discuss some of the possibilities.File I/OIf your data files are available to the file system of the computer on which your webMathematicaserver runs, they can be read with a command like Import. For this to work, the name andlocation of the data file must be specified. This can be done in several ways. One way involvesplacing the files into a directory and setting the full pathname of this directory. This suffersfrom the extreme disadvantage that if you change the name of the directory, you will have tomodify all your scripts that use this name. An improvement could be obtained by setting thename of the directory with an initialization parameter. This can be done in MSPConfiguration.xmlwith the parameter KernelInitializeCode as shown in the following.MyApplication`DataDirectory="C:\\Work\\Data"This assigns the Mathematica symbol MyApplication`DataDirectory to "C:\Work\Data". Notethe use of a full context name. This is necessary to prevent the symbol being cleared by thekernel cleaning mechanism. This can then be loaded in a webMathematica computation asshown in the following example.data = Import[ ToFileName[ MyApplication`DataDirectory, "file.dat"],"Table"];


100 webMathematica User GuideAn alternative is to place the data file into a directory that is on the Mathematica path setting$Path. This is the approach taken by the example Data1.jsp, which is shown below. Anotheralternative is to place the data file into the same directory as the script, and to use MSPPageDiÖrectory, as shown in the following.data = Import[ ToFileName[MSPPageDirectory[], "file.dat"], "Table"];This was used in the XML example Phone.jsp, which was discussed previously. It is particularlyconvenient to use MSPPageDirectory since it means that data and scripts live in the samedirectory. Thus the entire web application can be moved from one server to another with aminimum of setting up. One disadvantage is that for JSPs the data file can be loaded by a directrequest to the server; thus it should only be used if there is no specialized information presentin the data file. This might be the case if only certain information was suitable to be used in aresponse to each request.HTTP UploadAnother way to load data into a webMathematica server is to send it from the client machinewith the HTTP request. webMathematica contains tools to support this with the functionMSPGetUploadFile. This is demonstrated in the example, Upload.jsp, which is shown below.Database ConnectivityDatabaseLink provides Mathematica with an industrial-strength, ready-made solution for integratingMathematica with any standard SQL database. Integrated since Mathematica 5.1, itprovides a convenient bridge between SQL databases and webMathematica.DatabaseLink is based on Java Database Connectivity (JDBC) technology and so it fits very wellwith the Java technology on which webMathematica is based. It has many useful andimportant features (listed at http://reference.wolfram.com/mathematica/DatabaseLink/tutorial/Overview.html). One particularly useful feature for webMathematica is thatDatabaseLink contains the HSQL Database Engine (HSQLDB), a lightweight database. Thismeans that if you do not already have a database or want to experiment with using one, you donot have to set one up.


webMathematica User Guide 101webMathematica contains two examples of working with a database. These are Database.jsp,which is accessible via http://localhost:8080/webMathematica/Examples/Database/Database.jsp and DatabaseTable.jsp, which is accessible via http://localhost:8080/webMathematica/Examples/Database/DatabaseTable.jsp. Note that for these links to work, youneed to have installed webMathematica, and also the DatabaseLink example databases, asdescribed in its documentation. The example databases are installed into $UserBaseDirectory,and so you need to make sure this is $UserBaseDirectory for the user who is runningwebMathematica.Web ServicesAnother way to find data for Mathematica is by contacting another website. A particularly convenientway to do this is if the other website provides the data as a web service. In this caseMathematica can use the Web Services Package (described at http://reference.wolfram.com/mathematica/WebServices/tutorial/Overview.html) to call the website and use its services.Data ExamplesThe following is a collection of examples of webMathematica working with data.Loading Data: Load.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Data/Load.jsp. (You may have someother URL for accessing your server.)This example shows how to load Mathematica packages and how to read a data file that isstored on the server. The data is processed with a data smoothing algorithm and then a coupleof plots are made. The source for this page is in webMathematica/Examples/Data/Load.jsp. Asection that shows the form tag is shown below.data = Flatten[N[Import["Data/DataFile1.dat"]]];term = 4;If[MSPValueQ[$$term], term = MSPToExpression[$$term]];


102 webMathematica User GuideNumber of smoothing terms: dataSmooth = MovingAverage[data, term];MSPShow[ListPlot[{data, dataSmooth}, Joined -> {False, True}, ImageSize-> 600]]In this example, an msp:evaluate tag loads the dataset Data/DataFile1.dat using the Importcommand. This will search for the data file on the Mathematica $Path and will find the Datadirectory inside the MSPScripts directory, which by default is located in webMathematica/WEB-INF. It is worth looking inside your webMathematica web application and confirming thatyou can locate the data file. The example then computes a moving average and plots the originaland the smoothed data. This is all placed inside a form element so that it is possible tomodify the number of terms.One weakness of this example is that the data has to be loaded from the data file for everycomputation. It would be better to save the data somehow. In addition, it might be useful toallow the data to be uploaded from the client. These will be explored in the sections that follow.Uploading Data: Upload.jspIf you installed webMathematica as described above, you should be able to connect to thisexample via http://localhost:8080/webMathematica/Examples/Data/Upload.html. (You mayhave some other URL for accessing your server.)This example allows the user to enter a function to be integrated. The result is thenformatted by the typesetting system and saved as an image. The source for thispage is webMathematica/Examples/Data/Upload.html and webMathematica/Examples/Data/Upload.jsp. The contents of Upload.html are shown below.Uploading Data


webMathematica User Guide 103Uploading DataEnter a file to upload: To generate suitable data,click hereThis example shows how data can be uploaded for processing bywebMathematica.It should first be noted that this is an HTML page; it contains no Java or Mathematica inserts. Aservlet container will deliver HTML pages just as it delivers JSPs, and they can all be puttogether in the same directories inside of the webapp, which can also contain other files such asthose containing images or movies. This file contains a single form element that is set up tosubmit a data file using an enctype attribute of multipart/form-data and an input element oftype file. When the submit button is clicked, the form will be submitted along with the file tothe Upload.jsp. A selection of Upload.jsp is shown below.file = "FileName" /. MSPGetUploadFile[];data = Flatten[ N[ Import[ file, "Table"]]];term = 4;If[ StringQ[ file],dataSmooth = MovingAverage[ data, term];MSPShow[ MultipleListPlot[ data,dataSmooth,PlotJoined ->{False,True},SymbolShape -> Point,SymbolStyle -> {{PointSize[0.008],Hue[0]}, {PointSize[0.001]}},ImageSize -> 600]]]


104 webMathematica User GuideIn this selection we see how the MSP function MSPGetUploadFile is used to retrieve the nameof the data file by which the data has been stored on the server. This filename can then be usedto read the data as was done in the previous example and the computation can proceed. Itshould be noted that this solution is somewhat limited; the data is only available once for onecomputation, and no facility has been added to change a parameter, for example, to control thedata smoothing. For this the data needs to be stored in a session variable. This is explored inthe next example.In this example a test was made to determine whether the filename was in fact a string. Thischecks that a data file has in fact been uploaded. A file would not be uploaded if the pageUpload.jsp was visited directly instead of coming from a request to Upload.html.MSPGetUploadFile returns a list of useful information, including the filename that is used onthe server, the original filename used on the client, and the content-type. In a case where thereare multiple files to be uploaded, MSPGetUploadFile will throw an exception. If you wish toupload more than one file, you can use MSPGetUploadFileList.Session Storage of Data: Session.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Data/Session.html. (You may have someother URL for accessing your server.)This example allows the user to enter a function to be integrated. The result is thenformatted by the typesetting system and saved as an image. The source forthis page is webMathematica/Examples/Data/Session.html, webMathematica/Examples/Data/Session.jsp, and webMathematica/Examples/Data/SessionProcess.jsp. The contentsof Session.html are shown below.Data in HttpSessionsData in HttpSessionsEnter a file to upload:


Data in HttpSessionswebMathematica User Guide 105Enter a file to upload: To generate suitable data,click hereThis example shows how data can be stored in HttpSessions for processingby webMathematica.This is very similar to Upload.html, except that it calls the JSP Session.jsp when the form issubmitted. Session.jsp is shown below.file = "FileName" /. MSPGetUploadFile[];data = Flatten[N[Import[file, "Table"]]];MSPSessionVariable[UploadedData, Null];UploadedData = data;This short JSP reads the data that was uploaded, and then uses MSPSessionVariable to storethe data in a session variable named UploadedData. This is a very convenient way to store datapersistently from one HTTP request to another. The data is actually stored in the server, so thateven if the Mathematica kernel was restarted, the data would still be available. The storageuses what is known as an HTTP session and the server may use cookies or some other mechanismto actually store the data. This is how a shopping cart in an e-commerce website works.As far as a developer of a webMathematica website is concerned, it is all very simple; just usethe function MSPSessionVariable, giving it the name of the variable and an initial value. Afterthe data has been read, there is a jsp:forward to the page that actually does the computationsand plots, Data3.jsp. Often it is a very good design principle to divide the code over a numberof separate pages that all do different tasks; if you develop pages that have large amounts ofcomplicated code in them, then refactoring might improve your system. A selection of SessionÖProcess.jsp is shown below.


106 webMathematica User GuideNumber of smoothing terms: Load another data file?MSPSessionVariable[UploadedData, Null];term = 4;If[MSPValueQ[$$term], term = MSPToExpression[$$term]];If[UploadedData =!= Null,dataSmooth = MovingAverage[UploadedData, term];MSPShow[ListPlot[{UploadedData, dataSmooth},Joined -> {False, True},PlotStyle -> {{PointSize[0.008], Hue[0]}, {PointSize[0.001]}},ImageSize -> 600]]]SessionProcess.jsp is very similar to Load.jsp; the main difference is the line that obtainsthe data. Instead of reading data from a file, it uses the session variable UploadedData, whichwas assigned to the data in the previous JSP, Session.jsp. If, by some chance, UploadedDatawas not previously defined, as might happen if SessionProcess.jsp is visited directly, thenUploadedData will have the value Null. Here this just prevents any plot from being produced,but in general it might be used to transfer to an error page.A further change to this section might be to store the data permanently on the server. For asimple data file, this could easily be done by using Mathematica file output operations. A moresophisticated application could use Java database connectivity to store the data and certainrelated information.Session variables are discussed further in Advanced Topics: Variables.


webMathematica User Guide 107Database Connections: Database.jspIf you installed webMathematica as described above, you should be able to connect to this JSPvia http://localhost:8080/webMathematica/Examples/Database/Database.jsp. (You may havesome other URL for accessing your server.)This example shows how to use DatabaseLink to connect to an SQL database. The databasein question is one that is contained in HSQLDB, and for it to work the sampledatabases need to be installed. This is described in the documentation (http://reference.wolfram.com/mathematica/DatabaseLink/tutorial/Overview.html). The databases areinstalled into $UserBaseDirectory, and so you need to make sure this is $UserBaseDirectoryfor the user who is running webMathematica.This example shows how you can open a connection to a database and make a query to aparticular table based on an input parameter. The data is displayed with HTMLTableForm.Lower limit: Needs["DatabaseLink`"];limit = 6000;If[MSPValueQ[$$limit],limit = MSPToExpression[$$limit]];conn = OpenSQLConnection["publisher"];headings = {"TITLE_ID" , "LORANGE", "HIRANGE", "ROYALTY"};data = SQLSelect[conn, {"ROYSCHED"}, headings, SQLColumn["LORANGE"] >limit];Royalty Schedule Table


data = SQLSelect[conn, {"ROYSCHED"}, headings, SQLColumn["LORANGE"] >limit];108 webMathematica User GuideRoyalty Schedule TableHTMLTableForm[data, TableHeadings -> headings, TableAttributes ->{"cellpadding" -> "0", "cellspacing" -> "0"}]SQLExecute[conn, "SHUTDOWN"];CloseSQLConnection[conn];The code loads DatabaseLink and carries out some processing of an input variable, which isused to select data from the database. It opens a connection to the database and selects datausing the input variable and then formats and prints the result. Finally, it shuts down thedatabase and closes the connection. The shut down instruction is specific to HSQLDB and isnecessary to make sure that the database can be used if the server is restarted.Mathematica Packages and ApplicationswebMathematica provides a way to embed Mathematica code inside HTML. If the amount ofcode is significant, it might be more convenient to place the code into a Mathematica packageand then refer to the package. In addition, a script might be needed to make use of existingMathematica packages or applications. This section discusses how to work with Mathematicacode and packages.Loading PackagesIt is relatively simple to add code that loads a package. Here is a simple example.


webMathematica User Guide 109Live 3D PlottingConvexHull ComputationConvexHull ComputationNeeds["ComputationalGeometry`"]; ConvexHull[ {{1,5},{4,1},{10,2},{5,4}}]Notice how the evaluate tag uses Needs to load the package. An alternative, but less desirable,way to load a package is with Get. This is much less efficient since the package will be loadedeach time the page is loaded. When Needs is used, the package is only loaded the first time.An important detail is that one tag loads the package and another uses a function from thepackage. A tag that loads a package should not use functions that come from the package. Ifthis happens, a shadowing symbol is created, which will mask the function you wish to use.When a shadowing symbol is created, a warning message is issued; the text of messages canbe obtained with MSPGetMessages. It will also be displayed in the log files if verbose logging isenabled. The sections on Logging and The Kernel Monitor discuss verbose logging and log files.Sometimes, it is inconvenient to use two tags, and in this case you should use the fully qualifiedname for a function. This is shown in the following example.Needs["ComputationalGeometry`"];ComputationalGeometry`ConvexHull[ {{1,5},{4,1},{10,2},{5,4}}]


110 webMathematica User GuideA final issue concerns the use of subpackages. This can be an issue with Mathematica applications,that break up their implementation around a number of subpackages. For example, thefollowing two fragments show a main package with context Main`, and a subpackage withcontext Main`SubUnit`.BeginPackage[ "Main`", {"Main`SubUnit`"}]…EndPackage[]BeginPackage[ "Main`SubUnit`"]MyFunction::usage = "MyFunction is in context Main`SubUnit`"…EndPackage[]Both packages are loaded when the main package is loaded, as in the following.In[1]:=Needs@"Main`"DNote that the MyFunction function is defined in the Main`SubUnit` context.In[2]:= Context@ MyFunctionDOut[2]= Main`SubUnit`The implication for webMathematica coding is that a Needs statement is required for all thecontexts that contain symbols you wish to use directly inside evaluate tags. Thus, if you wishto use MyFunction, you must insert a Needs statement for the Main` application and also forthe context that contains the MyFunction function. An example follows.Needs["Main`"];Needs["Main`SubUnit`"];MyFunction[ arguments]If you feel that packages are not being used correctly, it would be good to check that the contextsfor symbols you are using have Needs statements. One way to check this would be towrite a small page that checked the contexts of functions you were using.


webMathematica User Guide 111Needs["Main`"];Needs["Main`SubUnit`"];Context[ MyFunction]If you have installed the application and run this script on your server, you should see Main`SubÖUnit` returned. This confirms that you have correctly loaded the function from the application.Similar issues apply if you use the Master mechanism to load packages. You will either requirea Needs statement for the individual contexts, or refer to the full context name of the symbols.Of course, the former makes the Master mechanism not useful. An example of using full contextsis shown below.Needs["Graphics`Master`"];color = Graphics`Color`Red Writing PackagesIf you write any significant amount of your own code, it is a good idea to write it as a Mathematicapackage and load it into webMathematica. This is particularly important for webMathematicasince you want to reduce the amount of Mathematica code that you have in your webMathematicapages. There are a number of references that help with the process of writing a package; forexample, the section Setting Up Mathematica Packages. Instructions on how to load the packageare given in the previous section; information on the location to place your package isgiven in the following section.If you do not use the Mathematica package format, but instead use global definitions for yourcode, then you will need to load it every time the script is accessed. This is because of thepostprocessing that takes place when a script is accessed. It is recommended that you placecode into a Mathematica package.


112 webMathematica User GuideInstalling PackagesWhen a package of Mathematica code is available, it must be installed in some location so thatit can be used by webMathematica. There are a number of ways this can be done; they arecovered in the following sections.webMathematica ApplicationswebMathematica provides an Applications directory, located in webMathematica/WEB-INF/Applications, which can be used for adding packages and applications. Any resources that areadded in this location will only be available to webMathematica.$BaseDirectoryThe directory, $BaseDirectory, is provided to install resources such as packages and applicationsso that they are available to all users of Mathematica and all installations of Mathematicaon a machine. Packages and applications can be installed in $BaseDirectory/Applicationswhere they will be available to webMathematica.$UserBaseDirectoryThe directory, $UserBaseDirectory, is provided to install resources such as packages andapplications so that they are available to a particular user of Mathematica on a machine. Packagesand applications can be installed in $UserBaseDirectory/Applications where they willbe available only to the particular user who is running the webMathematica server.The Script DirectoryAnother location for packages and applications is in the directory in which the JSP script lives.By default files cannot be loaded from this directory. It is possible to add the location to theMathematica path using MSPPageDirectory. This is demonstrated below, using Needs to load apackage and Get to load a data file.Block[{$Path=Append[$Path, MSPPageDirectory[]]},Needs["MyPackage`"];Get["Data.m"];]This arrangement would allow the directory of JSPs and code to be moved to another installationof webMathematica with a minimum of rearrangement.


webMathematica User Guide 113A drawback to this technique is that the code, MyFile.m, is available to be downloaded directlyfrom the web server by a direct request. If it contained private information, this might beconsidered a security risk.$TopDirectoryIt is possible to install packages and applications inside the Mathematica layout. This makesthem only available to that particular installation of Mathematica. Generally this is notrecommended.Absolute FilenameA last way of installing code is to use an absolute pathname. An example is the following.Get[ "d:\\MyWork\\LastOneThatWorked\\MyFile.m"]This type of loading is very common and is nearly always a very bad idea. It leads to fragilecode that requires a significant amount of maintenance. For very little extra effort, one of theother methods that have been described should be used.Extended Page LanguagewebMathematica provides a number of extended ways for a server computation to direct thecontents of the resulting web page. These are in addition to the basic tags such as evaluate.Expression LanguagewebMathematica support for the expression language gives a more concise way to call to Mathematicathan typically done in the evaluate tag. It is also much more suitable to be nestedinside another tag or an attribute.An example is shown below.The expression language form of evaluate is more concise and neater than the alternativeversion that relies on nesting an evaluate tag.


114 webMathematica User GuideThe expression language is particularly useful for working with the standard tags.JSP Standard TagsThe Java Server Pages technology, on which webMathematica is based, provides a number oflibraries of standard tags for carrying out a variety of useful purposes such as controlling flowwithin the web page. The libraries for these tags are included with webMathematica. If youwant to use them, you must include an extra declaration at the top of your web page.ifThe if tag is useful for conditionally adding a section of a web page. An example isJSTLif.jsp, found in the webMathematica web application in the directory Examples/ExtendedLanguage (the full path in Tomcat would be webapps/webMathematica/Examples/ExtendedLanguage). Some of the contents are shown below.The input variable had a value: ${msp:evaluate('$$test')}.The input variable did not have a value.In this example, if the input paramater $$test has a value, then the contents of the first if areincluded in the output page; this also shows the value of the parameter. On the other hand, ifthe parameter does not have a value, for example this is the first request, then the contents ofthe second if are included in the output page.


webMathematica User Guide 115setThe set tag is a convenient way to store a result that can be used in other locations. An exampleis JSTLset.jsp, found in the webMathematica web application in the directory Examples/ExtendedLanguage (the full path in Tomcat would be webapps/webMathematica/Examples/ExtendedLanguage). Some of the contents are shown below.The value is ${id}.In this example, if the variable id is initialized with the result of a Mathematica computation.This is then used in a number of other instances of the expression language.choose/when/otherwiseThe choose, when, and otherwise tags are another way to conditionally add blocks of text. Anexample is JSTLchoose.jsp, found in the webMathematica web application in the directoryExamples/ExtendedLanguage (the full path in Tomcat would be webapps/webMathematica/Examples/ExtendedLanguage). Some of the contents are shown below.Sin was chosenCos was chosenTan was chosenSomething else was chosen


116 webMathematica User GuideIn this example, the variable id is initialized with the result of a Mathematica computation. Thisis then used in a number of different when or otherwise tags. The final page depends on whatwas stored in the input parameter.Queuing of Long CalculationsThe standard usage of webMathematica carries out calculations inside of a single HTTP request.Mathematica can do a tremendous amount during an HTTP request and so many interestingwebsites can be built. However, if you want to run longer calculations, taking more time than atypical HTTP request, for example, a calculation that takes 20 minutes, this cannot be donewith the standard usage.When the evaluateQueued tag is processed, webMathematica creates a job object that waits ina queue until a kernel is available to do the calculation and the HTTP request returns immediately,probably before the computation has even started. At some time in the future, therequest is run and any results are saved. The web client can make a request to the server,using an identifier for the job, at any time to find out what has happened to the request.webMathematica contains a simple example of the queuing system, the source for this can befound in the webMathematica web application in the directory Examples/Queueing (the full pathin Tomcat would be webapps/webMathematica/Examples/Queueing). There are three files,Start.jsp, which sets up parameters for the calculation, Submit.jsp, which actually submitsthe calculation to the queue, and Result.jsp, which waits for and displays the result.The basis of the queueing system is the evaluateQueued tag, which is used instead of theevaluate tag. An example of the tag is shown below.longCalculation[]The body of the tag contains the long running calculation, in this case longCalculation[].Note that if you load any package in this body, then you need to refer to the fully qualifiedname; this is discussed in more detail in the section Loading Packages. An alternative would behow to use the KernelInitializeCode configuration parameter to load any necessarypackages.


webMathematica User Guide 117The evaluateQueued tag actually creates a job object and places it into a queue. The job hasan id that can be used to work with it later, and this can be found with the var attribute. Whenthe job actually runs, it uses the pool set by the pool attribute; if this is not found, then it willuse the standard URL mapping used by the evaluate tag.varpoolthe name of a page variable to hold the job idthe pool to use for the compuationAttributes of the evaluateQueued tag.The actual computation of the body of the evaluateQueued tag proceeds very similarly to theevaluate tag. The computation can make use of many of the MSP functions, for example,saving image files and constructing URLs. It also has access to all the request parameters thatcame with the request. However, it does not have access to an HTTP request object, and so itcannot make use of an HTTP session.Interacting with the QueueOne key way that you can interact with the queue is using the var attribute of the evaluateÖQueued tag. This can be passed around the various web pages you want to work with, either asa request parameter or by saving in an HTTP session. An example, which starts a calculation,and then offers a link to another page passing the var as a request parameter, is shown below.longCalculation[]Get results here.The var attribute is actually a variable that holds a reference to the id of the job object. web-Mathematica offers an expression language function that helps to find the job.There are a number of things you can do with the job object. You can find out its state, whetherit has started, finished, etc... You can find out its input and also the result, if it has finished.You can also cancel the job.It is also possible to access the job object via the Mathematica syntax, when the kernel isinitialized the symbol MSP`Utility`$Job is assigned to the job. Some functions for workingwith the job in both the expression language and Mathematica are shown below.


118 webMathematica User Guideexpression language syntaxMathematica syntaxstate of the job ${job.state} jobügetState@Dresult of thecomputation${job.output}jobügetOutput@Did of the worker ${job.id} jobügetId@DSome techniques for the job object.The state property of the job object shows you what the state it is in. The possible values areshown below.state valuesNEWQUEUEDRUNNINGTERMINATEDmeaningjob has been createdjob is waiting in the queuejob is runningjob has terminatedValues of the state property of the Job object.The errorType and errorText properties of the job object show you information about theerror state of the job. The possible values are shown below.errorType valuesNOERRORKERNELEXCEPTIONmeaningjob has no errora kernel exception occurredValues of the errorType property of the Job object.If the state is TERMINATED, you can extract the result and you know that the job has finishedthe computation.For example, the Result.jsp page has code that looks like the following.Job with Id ${param.id} not found.


webMathematica User Guide 119Job with Id ${param.id} not found.The computation is queued until a kernel becomes available.Check again?The computation is currently running.Check again?Error text: ${job.errorText}Error type: ${job.errorType}Here are some snapshots of the result.${job.output}Error with job ${job.id}This shows how the job object is extracted from the request parameter, and how to get thestate property. The page then returns different content depending on the value of the state.Lifetime of a Queued RequestThese are the steps in processing a queued request.A page that contains an evaluateQueued tag is processed. This creates a job object, choosesa kernel pool, and submits the job to the job queue for that pool. The pool is chosen from thepool attribute or a URL pattern if there is no pool attribute. If there is a var attribute it is boundto the id of the job. The state of the job is NEW when it is created and this moves to QUEUEDonce it is queued. Any request parameters that are sent with the page are saved to be usedwhen the computation is actually run.


A page that contains an evaluateQueued tag is processed. This creates a job object, choosesa kernel pool, and submits the job to the job queue for that pool. The pool is chosen from the120 webMathematica User Guideto the id of the job. The state of the job is NEW when it is created and this moves to QUEUEDonce it is queued. Any request parameters that are sent with the page are saved to be usedwhen the computation is actually run.The request that contains the evaluatedQueued tag returns to the client. This might contain areference to the id of the job.At some future time a kernel in the pool becomes available. This kernel is acquired for thejob. At this point any AcquireKernelCode configuration will be called. The job changes statefrom QUEUED to RUNNING.The kernel executes the body of the evaluateQueued tag. It is subject to all the constraintsand limits of executing commands in webMathematica, and if one of these is exceeded then thecomputation will terminate and the errorType will be set to KERNELEXCEPTION. However, if thecomputation finished normally, the errorType is set to NOERROR and the result is stored in thejob.Organizing and Configuring a Queued PoolAny kernel pool can be used to run computations from an evaluateQueued tag. However, it istypically good practice to have a pool that is designated for queued computations. More informationabout kernel pools and how to set them up can be found in the kernel pools section. Usinga separate pool is advantageous because you can configure it in a way that is more useful for aqueued computation. For example, you might want to increase the KernelTimeLimit parameter,to increase it to some longer value. Most of the configuration parameters are useful for aqueued computation; you can find out more about configuring webMathematica in the sectionon configuration. Another advantage of a separate pool for queued calculations is that you havea pool available for normal calculations.Alternative Server TechnologiesThere are various different server technologies that can be used in conjunction with webMathematica.One basic strategy is to use URLs that refer to computations for a webMathematicaserver, a technique that should work for any server technology. This is particularly easy for imgtags.


webMathematica User Guide 121Here is an img tag that refers to a computation carried out in webMathematica. It could beembedded in the result from any server technology.Tighter cooperation between a specific server technology and webMathematica is often possible.Remember that webMathematica is based on servlets so any question about interoperation of aserver technology and webMathematica is really a question of interoperation of the servertechnology and Java Servlets and JavaServer Pages. Some specific examples of integrationfollow.JavaServer PagesJavaServer Pages (JSP) technology is an extension of Java Servlet technology. It is the Javaequivalent of MSP technology allowing Java code to be embedded in HTML pages. Since web-Mathematica has a JSP implementation, it is very strongly integrated with JSPs.PHPPHP is a server-side, cross-platform, HTML-embedded scripting language (http://www.php.net).There is a PHP extension that allows interaction of PHP and servlets, which is available athttp://cvs.php.net/cvs.php/php4.fubar/sapi/servlet. This link contains a README file, which is agood place to start to integrate PHP and webMathematica.PDF DocumentsMathematica provides a powerful medium for electronic technical documents. Mathematicanotebook documents can combine text, mathematics, computations, charts, visualizations, andinteractive elements suitable for many technical areas. The documents can be kept as notebookformat and viewed with the Mathematica notebook front end; alternatively they can be convertedinto a variety of other formats such as PDF, PostScript, or XHTML.webMathematica can use these features to automatically generate technical reports.


122 webMathematica User GuideOne format that is very easy to generate is Mathematica notebooks, and there are a number ofwebMathematica examples that work by returning Mathematica notebooks to the client. Oneexample is Content.jsp. Using Mathematica notebooks has the advantage that the documentcan be worked on further after reaching the client. A disadvantage is that it requires the clientto have access to an application that can read notebooks, such as Mathematica or MathematicaPlayer (http://www.wolfram.com/products/player/). Another alternative is to use PDF. This hasthe advantage that the vast majority of clients are set up to render PDF.Mathematica can now automatically convert notebook documents into PDF format. This sectionwill explore how to generate PDF documents from webMathematica.Generating a Mathematica NotebookA common way to do this involves using Mathematica commands for generating notebooks. Asample function is shown below (taken from the source used by Content.jsp).MakeNotebook[] :=Developer`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]]This sample shows how a notebook object is created with NotebookCreate, and then how thecontent is added with NotebookWrite. When the notebook is complete, a Mathematica expressionholding the notebook is obtained with NotebookGet and this is returned. In a real lifesituation, the document could contain graphics, more text, and some computations. The Mathematicadocumentation has much more information on the commands for generating notebooks.A major advantage of working with Mathematica notebooks like this is that they will take careof details such as font selection, graphics, and mathematics without the author having to bevery involved.


webMathematica User Guide 123Converting to PDFThe Mathematica function ExportString can be used to convert a Notebook expression into astring that contains the PDF. When it runs in webMathematica it needs to be wrapped withUseFrontEnd. An example of the conversion is shown below.UseFrontEnd[ ExportString[ nb, "PDF"]]You can read more about PDF generation in the format documentation.Returning PDFThere are several ways to return non-HTML content from webMathematica. These are summarizedin the section Returning General Content. One simple way is to embed a URL that willdownload the document in your result. This can be done with MSPURLStore as shown in thefollowing.nb = MakeNotebook[];pdf = UseFrontEnd[ ExportString[ nb, "PDF"]];MSPURLStore[ pdf, "application/pdf", "notebook.pdf"]An alternative is to return the result directly from the request, which can be done as follows.Note that the content type must be set in the page directive.nb = MakeNotebook[];UseFrontEnd[ ExportString[ nb, "PDF"]Yet another approach is to use MSPReturn. This is useful if your call is embedded inside someother programs, or if the result is not always PDF (perhaps because of error handling).If[ convert === "True",nb = MakeNotebook[];pdf = UseFrontEnd[ ExportString[ nb, "PDF"]];MSPReturn[ pdf, "application/pdf"]]


124 webMathematica User GuideCreating PDF ExampleThis section describes an example that generates a notebook and converts it to PDF. For it towork you need to install PDF tools described in the last section. If you installed webMathematicaas described above, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/PDF/Generate.jsp. (You may have some other URL for accessingyour server.) The source is in webMathematica/Examples/PDF/Generate.jsp. Here is the JSPsource.Needs["ExampleUtilities`Content`"]If[MSPValueQ[$$button],nb = MakeNotebook["PDF"];pdf = UseFrontEnd[ExportString[nb, "PDF"]]]This code loads a basic package for creating notebooks. This is done in a separate evaluatetag, as described in the section Mathematica Packages and Applications. It calls the functionMakeNotebook, which generates a very simple notebook and converts this into a string of PDF.The string is returned to the client using MSPReturn.Returning General ContentThe typical result of a webMathematica request is an HTML page, which might include referencesto images. The commands available for webMathematica are designed to make this typeof request very convenient. However, it is also very useful to be able to return other formatssuch as Mathematica notebooks or TeX documents. Mathematica commands for generatingthese other formats are Export and ExportString. When these other formats are returned to abrowser, it can often launch a helper application that provides special functionality for thatformat. This section discusses how to use webMathematica to return general content of differentformats.


of request very convenient. However, it is also very useful to be able to return other formatssuch as Mathematica notebooks or TeX documents. Mathematica commands for generatingwebMathematica User Guide 125browser, it can often launch a helper application that provides special functionality for thatformat. This section discusses how to use webMathematica to return general content of differentformats.Direct ReturnThe simplest way to return content type other than HTML is to write a page that only returnsyour data. If your data is static, you should insert it into the page. Alternatively, if it has to begenerated each time by Mathematica, you should just have an evaluate tag that returns yourdata and not use any HTML markup. It is a good idea to set the content type at the top of thepage. This technique can be useful for AJAX and web service interactions. An example follows.MSPFormat[ Integrate[ 1/(1-x^3),x], StandardForm, RawMathML]An alternative to using a page directive is to use the ContentType option of MSPPageOptions.The following example demonstrates how this can be done.MSPPageOptions[ ContentType -> "text/mathml"]MSPFormat[ Integrate[ 1/(1-x^3),x], StandardForm, RawMathML]It is probably more convenient just to use the page directory.MSPReturnWhen an MSP script evaluates MSPReturn, the processing of the script is terminated and thefirst argument is immediately returned. The second argument specifies the content type. In thisexample a notebook object is returned, and the result is set to be application/mathematica.MSPReturn[ "Notebook[Cell[\"Hello\",\"Title\"]]","application/mathematica"]


126 webMathematica User GuideCertain HTTP clients can use the content type to launch a helper application. However, someclients need a filename to be associated with the request. For this purpose, MSPReturn takes athird argument that sets the filename in an HTTP header. An example follows.If[ format === Notebook,MSPReturn[ data, "application/mathematica","notebook.nb"]];However, for some HTTP clients (for example Internet Explorer) this has the undesirable effectof causing the client to display two Open or Save dialog boxes. Most clients work much betterif the request for the script that contains the MSPReturn uses the filename with an appropriateextension. Since the extension for webMathematica requests has to end in .jsp, this is notpossible. An alternative is to generate a URL that has the correct extension; this functionality isprovided by MSPURLStore.MSPReturn is useful when the commands are embedded inside an existing page and you justwant to terminate processing the page and return the result. It is simpler to use the directreturn technique, so this would be preferred if it is possible.MSPURLStoreMSPURLStore uses the mechanism that webMathematica provides for storing images generatedby commands such as MSPShow. It actually stores its argument on the server and returns a URLthat references the argument.In[1]:=In[2]:=Needs@"MSP`"Dm = ExportString@Graphics@Line@ 880, 0


webMathematica User Guide 127In[4]:=MSPURLStore@ "Notebook@Cell@\"Hello\",\"Title\"DD","applicationêmathematica", "notebook.nb"DOut[4]= êwebMathematicaêMSPêFileNameBase_682425268?MSPStoreName=notebook.nb&MSPStoreType=applicationêmathematicaSetting the filename can be helpful for the browser to choose the correct helper application. Theexample script Examples/ContentStore.jsp has an example of MSPURLStore.MSPURLStore is useful as a way of returning content if you need a URL such as in a srcattribute of an img tag. This can be useful when working with dynamic client technologies suchas AJAX or Flash.AJAXAJAX is a collection of related web technologies that help to make interactive web applications.The term actually stands for Asynchronous JavaScript and XML and is aimed at increasingresponsiveness and interactivity of web material.Using AJAX requires that you work with JavaScript and have some experience with the structureof an HTML document. However, it is quite straightforward to work with AJAX inwebMathematica.Time ExamplewebMathematica contains a simple example of working with AJAX. The source for this can befound in the webMathematica web application in the directory Examples/AJAX (the full path inTomcat would be webapps/webMathematica/Examples/AJAX). The two files are LoadDate.jsp,which contains the AJAX code to call to the server, and ReturnDate.jsp, which returns theresult from the server. If your server is configured and running, you can test this example withthe URL http://localhost:8080/webMathematica/Examples/AJAX/LoadDate.jsp. (You may havesome other URL for accessing your server.)LoadDate.jsp contains two sections, a JavaScript section and an HTML section. The JavaScriptis as follows (in a real usage, this would be better put into a js library file rather than directlyinto the web page).


128 webMathematica User Guidefunction loadDate( ) {var xmlHttp;try { // Firefox, Opera 8.0+, SafarixmlHttp = new XMLHttpRequest();if (xmlHttp.overrideMimeType) {xmlHttp.overrideMimeType('text/plain');}}catch (e) {// Internet Explorertry {xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}catch (e) {try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e) {alert("Your browser does not support AJAX!");return false;}}}xmlHttp.onreadystatechange = function() {if(xmlHttp.readyState == 4) {var elem = document.getElementById("time");elem.value = xmlHttp.responseText;}}var fullDate = document.getElementById("fullDate").checked;var url = "ReturnDate.jsp";url=url+"?fullDate="+fullDate;xmlHttp.open("POST", url, true);xmlHttp.send(null);}The first part of this example involves obtaining an instance of an XMLHttpRequest object. Inthis example, the instance is called xmlHttp. Note how different techniques are used for differentbrowsers.


webMathematica User Guide 129The XMLHttpRequest object is a major part of AJAX; this allows the asynchronous interaction,set up by the onreadystatechange function. This is called when there is a change in the stateof the HTTP request. The change that this example tracks is when the readyState goes to 4,which means that the request is complete. When this happens the function takes the text in theresponse and inserts it into the time element of the web page. The onreadystatechange functionis called asynchronously at some time in the future when the HTTP request is complete.The details of how this is done is completely left up to the XMLHttpRequest object, which leadsto a tremendous simplification for the AJAX programmer.After the result handler is set up, the actual request is made. This is done by setting up the URLto call, which includes an input parameter taken from the value of the checkbox in the HTML.After the send call, the request is triggered.The HTML part of the page is as follows.AJAXDemoA basic AJAX example.Result: Full Date: UpdateSome of this is concerned with the content of the page, such as the title, while other parts workwith the interactive content. Note the button element. When this is clicked the loadDate()JavaScript function, which you saw above, is called. This means that when you click the button,the time input field is updated with the result of the web request.On the server there is a different page, ReturnDate.jsp, which actually does the server work.It is quite simple and is shown below.


130 webMathematica User GuideIf[ $$fullDate === "true",DateString[],DateString[{"Hour", ":","Minute",":","Second"}]]There is one evaluation carried out by Mathematica; this checks the setting of the fullDateinput parameter (which came from the checkbox in the original web page). It returns a string ofthe date.Note how the page does not need any HTML formatting because the result is just a string thatis used by the loadDate() JavaScript function. Also, note how the page displayed in thebrowser does not change; only part of the page changes. This can help to improve performance,since less is transmitted. Also, it can improve appearance since the whole page doesnot flicker. Another benefit is that other effects can be added, for example, while the browser iswaiting for the result to come back it could do something to indicate that the page is waiting forsomething.HTML ExampleAJAX techniques are not limited to string results from the server. In fact, the server can returnwith many differrent types of format, and these can be used to change the contents of thedocument in the browser. This example shows how the src attribute of an img tag can bechanged.The source for this example can be found in the webMathematica web application in the directoryExamples/AJAX (the full path in Tomcat would be webapps/webMathematica/Examples/AJAX). The two files are LoadImage.jsp, which contains the AJAX code to call to the server, andReturnImage.jsp, which returns the result from the server. If your server is configured andrunning you can test this example with the URL http://localhost:8080/webMathematica/Examples/AJAX/LoadImage.jsp. (You may have some other URL for accessing your server.)First, this is the source of ReturnImage.jsp, which is similar to ReturnDate.jsp except that itreturns an HTML fragment (this is done with MSPShow); it also sets the content type to betext/xml.


webMathematica User Guide 131fun = If[ MSPValueQ[ $$fun] && $$fun =!= "",MSPToExpression[ $$fun],Sin[x]];p = Plot[ fun, {x,0,10}];MSPShow[p]You can test this with the URL http://localhost:8080/webMathematica/Examples/AJAX/ReturnImage.jsp. You should see something like the following.Thus the page returns a fragment of HTML, not a complete document. The JavaScript functiontakes this fragment and inserts it into the document.Here is the JavaScript function in LoadImage.jsp. It is quite similar to LoadDate.jsp.function loadImage( ) {var xmlHttp;try { // Firefox, Opera 8.0+, SafarixmlHttp = new XMLHttpRequest();if (xmlHttp.overrideMimeType) {xmlHttp.overrideMimeType('text/xml');}}catch (e) {// Internet Explorertry {xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}catch (e) {try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}catch (e) {alert("Your browser does not support AJAX!");return false;}}}xmlHttp.onreadystatechange = function() {


132 webMathematica User Guide}catch (e) {return false;}}}xmlHttp.onreadystatechange = function() {if(xmlHttp.readyState == 4) {var xmlData = xmlHttp.responseXML;var imgNode = xmlData.getElementsByTagName('img')[0];var srcAttr = imgNode.attributes.getNamedItem("src");var srcTxt = srcAttr.nodeValue;var elem = document.getElementById("image");elem.src = srcTxt;}}var fun = document.getElementById("fun").value;var url = "ReturnImage.jsp";url=url+"?fun="+fun;xmlHttp.open("POST", url, true);xmlHttp.send(null);}The main difference here is the function that takes the result. It takes this as XML and doessome processing on the result to find the value of the src attribute, which it sets into an imgtag present in the page.The HTML part of the page is as follows.AJAX Image DemoA basic AJAX example that loads an image.Function: Update


webMathematica User Guide 133Some of this is concerned with the content of the page, such as the title, while other parts workwith the interactive content. Note the img tag labeled image, which has its src attribute filledout by the JavaScript function when the HTTP call is finished.One important point about this example is how the client side JavaScript function can work withthe XML. In this case the XML is XHTML, but in general it might be any form of XML.Web Services and XML ExchangeThe AJAX model is quite close to a web service. In fact, the techniques for setting up an AJAXinteraction, particularly on the server, are closely related to informal web services, which arediscussed in a later section. There is also an example of an informal web service that uses AJAX.Web ServicesWeb services are typically function calls made over a network using web technology to transmitthe information. Often the information that is transmitted is formatted as XML.A web service can be contrasted with a typical web request even though they both use webtechnology. A typical request is started by a human who uses a web browser and the result isHTML that is displayed in the browser. In a web service the request is started from a programand the result comes back to the program. In some cases the program is running in a browser,and it will modify the HTML that the browser is displaying. This is a common usage for AJAXapplications.It is often convenient to use the terms client and server when discussing web services. Theclient makes a request to the server which responds with a result. Note that the client andserver need not be on the same machine and might be different types of computers. Also, theclient and server might be running different languages.Web services can be informal ad hoc services where both ends agree on a format for data.Alternatively, there are web services specifications such as SOAP. These define the format forinformation transmitted for the web service. They may also provide other features such asbeing able to query a server to find out details of the web service that the server is publishing.Mathematica can work as a client for web services. The HTTP and XML tools are good for informalweb services, while the Web Services Link, allows you to call to use SOAP web services.Here, you can see how to use webMathematica as a server for web services.


134 webMathematica User GuideInformal Web ServicesInformal web services do not use a special protocol, and this means that a client needs to knowdetails of how the server passes data. The advantage of an informal web service is that it iseasy to set up. One use of an informal web service is for a program running inside a browser tomake a call to the server. Examples are a JavaScript program using AJAX or an Actionscriptprogram running in the Flash runtime. In fact, the webMathematica interactive tools, based onMSPManipulate, use an informal web service to send details of the user interface that is to beconstructed to the Flash runtime.AJAX ExampleThis example uses AJAX technology to demonstrate the setting up of an informal web service. Itwill not discuss all the details of how AJAX works, which is covered in the section on using AJAXwith webMathematica.The source for this example can be found in the webMathematica web application in the directoryExamples/AJAX (the full path in Tomcat would be webapps/webMathematica/Examples/AJAX). The two files are LoadXML.jsp, which contains the AJAX code to call to the server, andReturnXML.jsp, which returns the result from the server. If your server is configuredand running, you can test this example with the URL http://localhost:8080/webMathematica/Examples/AJAX/LoadXML.jsp. (You may have some other URL for accessing your server.)First, this is the source of ReturnXML.jsp. This sets the content type to be text/xml, and thentakes the input number, $$num, and does an integer factorization of the factorial of the input.The result is then formatted into XML, making use of symbolic XML.num = MSPToExpression[ $$num];factors = FactorInteger[ num!];xml =XMLElement[ "factors", {},Flatten[Apply[{XMLElement["factor", {}, {ToString[#1]}],XMLElement["exponent", {}, {ToString[#2]}]} &, factors, {1}]]];ExportString[ xml, "XML"]


webMathematica User Guide 135You can test this with the URL http://localhost:8080/webMathematica/Examples/AJAX/ReturnXML.jsp?num=8. You should see something like the following.27325171This is a simple XML fragment made up for this example. The root tag is factors and it containssequences of factor and exponent tags. This might be improved if each pair of factorand exponent tags were placed in a containing tag. The current approach is taken to keep thecode simple.Note how the XML is created by first making an XMLElement expression, and then convertingthis to a textual representation of the XML with ExportString. An alternative would be to uselots of string concatentation operations. It is very strongly recommended to use the symbolicXML technology of XMLElement. Symbolic XML will be much more robust, since a coding errorwill not lead to a string of ill-formed XML. It will also be much more flexible, if you want tochange one of the tags it will be easier. Also, it is convenient to use other XML features such asattributes or namespaces. Mathematica provides some very nice tools for working with XML andit is extremely good to use them.Here is part of the JavaScript function in LoadXML.jsp. It shows how the XML result is extractedfrom the HTTP result and arrays of factor and exponent tags are obtained. The result is thenformatted into an HTML table, which is then inserted into the final page.xmlHttp.onreadystatechange = function() {if(xmlHttp.readyState == 4) {var xmlData = xmlHttp.responseXML;var rootNode = xmlData.getElementsByTagName('factors')[0];var factorList = rootNode.getElementsByTagName('factor');var exponentList = rootNode.getElementsByTagName('exponent');var newHTML = "";var num = document.getElementById("inputvalue").value;newHTML = newHTML + "Factorization of " +num + "! ";newHTML = newHTML + "FactorExponent";for ( var i = 0; i < factorList.length; i++) {newHTML = newHTML + "";


136 webMathematica User Guidevar exponentList = rootNode.getElementsByTagName('exponent');var newHTML = "";newHTML = newHTML + "Factorization of " +num + "! ";newHTML = newHTML + "FactorExponent";for ( var i = 0; i < factorList.length; i++) {newHTML = newHTML + "";newHTML = newHTML + "" +factorList[i].childNodes[0].nodeValue + "";newHTML = newHTML + "" +exponentList[i].childNodes[0].nodeValue +"";newHTML = newHTML + "";}newHTML = newHTML + "";document.getElementById("result").innerHTML=newHTML;}}Part of the HTML is as follows.Input: CalculateThis shows the span tag that takes the result, the input tag that holds the input value, and thebutton to set off the interaction. As is typical for AJAX, when the button is clicked the page itselfdoes not change, just part of the page.Mathematica SOAP ClientMathematica provides a nice interface for calling SOAP web services with the Web ServicesLink. This is complemented by webMathematica, which provides functionality for publishingSOAP web services. It is quite convenient to use the Mathematica client tools in order to testthe server tools.This section provides a short description of the Mathematica SOAP client. More details can befound in the Web Services Link user guide.


webMathematica User Guide 137The first step to using a web service in Mathematica is to install it. This is done with theInstallService function; giving the URL that describes the service, it returns a list of functionsthat are provided by the service. An example is shown below (note that this service comes froma third party and might stop working at some time in the future).In[1]:= InstallService@"http:êêwww.webservicemart.comêuszip.asmx?WSDL"DOut[1]= 8ValidateZip


138 webMathematica User Guide- - - - - - - - - .....Entering the WSDL into a browser is a good way to check that the service is running.webMathematica SOAP ServiceswebMathematica supports the publishing of SOAP web services. There are a number of examplesthat demonstrate this functionality. These are discussed in this section.Echo ExampleThe first example is one that simply echos its input. Note that if you had a toolkit for callingSOAP web services you could use that, but it is quite simple to use Mathematica, as is donehere.


End[]webMathematica User Guide 139The source for this example can be found in the webMathematica web application in thedirectory Examples/WebServices/Echo.m (the full path in Tomcat would be webapps/webMathematica/Examples/WebServices/Echo.m). If your server is configured and running,you can test this example from within Mathematica with the URL http://localhost:8080/webMathematica/Examples/WebServices/Echo.m?wsdl. (You may have some other URL foraccessing your server.)This installs the service, returning a list of Mathematica functions.In[1]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêEcho.m?wsdl"DOut[1]= 8EchoBase64Binary, EchoBoolean, EchoDate, EchoDateTime, EchoDatum, EchoDatumArray,EchoExpression, EchoInteger, EchoIntegerArray, EchoMathML, EchoReal, EchoString, EchoTime


ServiceReturn[EchoString] = _String140 webMathematica User GuideServiceReturn[EchoInteger] = _IntegerEchoReal[real_Real] := realServiceReturn[EchoReal] = _RealEnd[]EndPackage[]This is written as a Mathematica package: the contents are encapsulated with BeginPackageand EndPackage. You can read more about this in the tutorial on setting up packages. Howeverit has a few additional elements: you need to also import the WebServicesServer` andXMLSchema` packages. Also the public functions, which will be published as web services, needto have input patterns that the server accepts, and the return value of the function needs to begiven with the ServiceReturn setting. Typical Mathematica functions do not need to specifyany type information, because the system is dynamically typed. However, SOAP web servicesneed this information.Plot ExampleThis example provides a web service that returns a plot of a function over a range. Note that ifyou had a toolkit for calling SOAP web services you could use that, but it is quite simple to useMathematica, as is done here.The source for this example can be found in the webMathematica web application in thedirectory Examples/WebServices/Plot.m (the full path in Tomcat would be webapps/webMathematica/Examples/WebServices/Plot.m). If your server is configured and runningyou can test this example from within Mathematica with the URL http://localhost:8080/webMathematica/Examples/WebServices/Plot.m?wsdl. (You may have some other URL foraccessing your server.)This installs the service and returns a list of Mathematica functions.In[2]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêPlot.m?wsdl"DOut[2]= 8PlotExpression, PlotString


webMathematica User Guide 141This calls PlotString passing the argument Sin[x] as a string and the number 10. The resultis a GIF bitmap of the image (returned as a list of bytes). A summary is shown in the following.In[4]:= res = PlotString@ "Sin@xD", 10D;Short@resDOut[5]//Short= SchemaBase64Binary@871, 73, 70, 56, 57, 97, 104, 1, á3495à, 126, 9, 44, 129, 0, 0, 59


esult = With[{var = Symbol["x"]}, Plot[e, {var, 0, limit}]];SchemaBase64Binary[ToCharacterCode[ExportString[result, "GIF"]]]]ServiceReturn[PlotString] = _SchemaBase64Binary142 webMathematica User GuideEnd[]EndPackage[]One important detail here is how the implementation uses MSPToExpression to convert thestring input into a Mathematica expression. This is necessary for security. If the service isinvoked with an input that does not pass the security test, a failure results.In[7]:=res = PlotString@ "ReadList@xD", 10DOut[7]= $FailedInvokeServiceOperation::rspnsflt : SOAPFault occurred: ServiceException@SecurityErrorD àOne of the advantages of using SOAP is that it has standards for how error conditions should behandled and reported. Any client toolkit can support these errors, which takes the burden awayfrom the developer.Excel ExampleThis example demonstrates how to call a Mathematica web service from Excel. The Mathematicacode is Integrator.m, and the source can be found in the webMathematica web applicationin the directory Examples/WebServices/Plot.m (the full path in Tomcat would be webapps/webMathematica/Examples/WebServices/Plot.m). The Excel spreadsheet file, WebServicesExÖample.xls, can be found in the Extras directory in your webMathematica distribution.This shows the implementation of the Integrator web service.BeginPackage["IntegrateService`", {"WebServicesServer`", "MSP`"}]IntegrateString::usage = "Integrates an equation with respect to x.The function is passed in as an InputForm string and the result is anInputForm string."Begin["`Private`"]IntegrateString[str_String] :=Module[{e, result},e = MSPToExpression[str];result = Integrate[e, Symbol["x"]];ToString[result, InputForm]]ServiceReturn[IntegrateString] = _StringEnd[]


e = MSPToExpression[str];result = Integrate[e, Symbol["x"]];webMathematica User Guide 143]ServiceReturn[IntegrateString] = _StringEnd[]EndPackage[]While it would be quite straightforward to call this with the Mathematica web services client, itis more interesting to use the Excel spreadsheet. The example, named WebServicesExample.xls,must be loaded into Excel. You need to allow macros to run, and then it looks somethingas shown below.You enter an input into the Expression field, click the Integrate button and the result of theintegration comes into the Answer field. If this does not work, you should check the URL thatis used, which is written in the script that drives the example.The actual work for this is done in a Visual Basic script that is included with the spreadsheet.While the documentation here does not include a detailed primer on programming in VisualBasic, it reviews the key elements of the script.A first part of the script creates the SOAP message as shown below.Private Sub SetSoapMessage(ByRef Connector As SoapConnector, _ByRef Serializer As SoapSerializer)Connector.Property("EndPointURL") = _"http://localhost:8080/webMathematica/Examples/Webservices/Integrator.m"Call Connector.ConnectCall Connector.BeginMessageSerializer.Init Connector.InputStream


ByRef Serializer As SoapSerializer)144 webMathematica User Guide"http://localhost:8080/webMathematica/Examples/Webservices/Integrator.m"Call Connector.ConnectCall Connector.BeginMessageSerializer.Init Connector.InputStreamSerializer.startEnvelope , ENCSerializer.SoapNamespace "xsi", XSISerializer.SoapNamespace "SOAP-ENC", ENCSerializer.SoapNamespace "xsd", XSDSerializer.startBodySerializer.startElement "IntegrateString","http://localhost:8080/webMathematica/Examples/Webservices/Integrator.m",, "method"Serializer.startElement "str", "", , ""Serializer.writeString Cells(5, 2)Serializer.endElementSerializer.endElementSerializer.endBodySerializer.endEnvelopeConnector.EndMessageEnd SubNote how it does not use the WSDL, but creates the SOAP message directly. It specifies theURL for the example, gives the name of the function, IntegrateString, and the name of theargument of this function, str. The value of the argument is taken from a cell in thespreadsheet.Another part of the script gets the response from the server. This appears in the following.Private Sub GetTagValueArray(ByRef node As MSXML2.IXMLDOMNode)Dim childnode As MSXML2.IXMLDOMNodeIf node.baseName = "IntegrateStringReturn" ThenIf node.childNodes.Length = 3 ThenFor Each childnode In node.childNodesIf childnode.baseName = "element" ThenCells(7, 2) = childnode.TextEnd IfNextEnd IfEnd IfIf node.childNodes.Length > 0 ThenFor Each childnode In node.childNodesGetTagValueArray childnodeNextEnd If


NextEnd IfEnd IfIf node.childNodes.Length > 0 ThenFor Each childnode In node.childNodesGetTagValueArray childnodeNextEnd IfExit SubEnd SubwebMathematica User Guide 145Note how this uses tools to walk down through the resulting XML to find the IntegrateStringReÖ Öturn node and take the text from its element node. This has the result, which is then insertedinto a cell in the spreadsheet.Many languages have their own tools for working with SOAP web services, some of them workwith WSDL and some directly with the SOAP messages. Whatever the toolkit, it should bepossible to call to a Mathematica web service served from webMathematica.Type SpecificationSOAP web services need to specify the type for the input and the type of the result. This is tobe constrasted with normal Mathematica usage that does not use any type information,because the system is dynamically typed.Type information is given by marking up the code with patterns such as shown below for inputand for output.MyFunction[ arg1_spec21, arg2_spec2, ...]ServiceReturn[MyFunction] = _specThe specification for an array of a type is given with a list pattern notation. The following exampletakes an array of integers as an input and returns a list of real numbers.MyFunction[ arg:{___Integer}]ServiceReturn[MyFunction] = {___Real}The ways that types can be specified are summarized in the following table.


146 webMathematica User Guidespecification meaning example_Integer integer 1_Real real number 2.5_String string "a string"True False boolean True_SchemaBase64Binary binary byte data SchemaBase64Binary@81,29,…,12


webMathematica User Guide 147An example of the use of a basic data type is shown below.TestInteger[int_Integer] := MatchQ[ int, _Integer]In this example, TestInteger takes an integer as a parameter and confirms that it is an integer,so the function will always return True when called as a web service.The Echo.m web service also provides a good way to experiment with the different data types.In[1]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêEcho.m?wsdl"DOut[1]= 8EchoBase64Binary, EchoBoolean, EchoDate, EchoDateTime, EchoDatum, EchoDatumArray,EchoExpression, EchoInteger, EchoIntegerArray, EchoMathML, EchoReal, EchoString, EchoTime


148 webMathematica User GuideIn[2]:=EchoDateTime@ SchemaDateTime@82000, 10, 1, 5, 10, 1


webMathematica User Guide 149In[1]:=ExportString@Sin@xD, "XML"DOut[1]= SinxIt would be possible to work with this XML format in a system that was not Mathematica.When Mathematica converts a SchemaExpr back into a Mathematica expression, the currentsecurity system is used to validate the result. If it fails then a security exception results.So that SchemaExpr can be used to transmit Mathematica expressions without their evaluating,it has the attribute HoldAllComplete.The Echo.m web service also provides a good way to experiment with the different data types.In[1]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêEcho.m?wsdl"DOut[1]= 8EchoBase64Binary, EchoBoolean, EchoDate, EchoDateTime, EchoDatum, EchoDatumArray,EchoExpression, EchoInteger, EchoIntegerArray, EchoMathML, EchoReal, EchoString, EchoTime


150 webMathematica User GuideAlternatively, you can represent the MathML as symbolic XML, as shown in below.In[2]:=mathml = XML`MathML`ExpressionToSymbolicMathML@Sin@xDDOut[2]= XMLElement@math, 8xmlns Ø http:êêwww.w3.orgê1998êMathêMathML


webMathematica User Guide 151The Echo.m web service also provides a good way to experiment with the different data types.In[1]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêEcho.m?wsdl"DOut[1]= 8EchoBase64Binary, EchoBoolean, EchoDate, EchoDateTime, EchoDatum, EchoDatumArray,EchoExpression, EchoInteger, EchoIntegerArray, EchoMathML, EchoReal, EchoString, EchoTime


152 webMathematica User GuideNow EchoExpression is called, but it will pass something that could be a security error. This isdetected by the server and a SOAP error is returned.In[3]:=EchoExpression@SchemaExpr@ReadListDDOut[3]= $FailedInvokeServiceOperation::rspnsflt :SOAPFault occurred: ServiceException@Expression HoldComplete@ReadListD failed the security test.D àFinally, the function itself can return an error. This is shown with the ErrorHandling.m service.First, the service is installed.In[2]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêErrorHandling.m?wsdl"DOut[2]= 8DayOfTheWeek


webMathematica User Guide 153Web services introduce two security issues: processing the SchemaExpr data type and interpretingstrings.If you use SchemaExpr to transmit input to a webMathematica web service, its input will bevalidated by the security system before it reaches the code that implements the web service.The Echo.m web service also provides a good way to experiment with the different data types.In[1]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêEcho.m?wsdl"DOut[1]= 8EchoBase64Binary, EchoBoolean, EchoDate, EchoDateTime, EchoDatum, EchoDatumArray,EchoExpression, EchoInteger, EchoIntegerArray, EchoMathML, EchoReal, EchoString, EchoTime


154 webMathematica User GuideThis installs the Plot.m web service.In[3]:=InstallService@"http:êêlocalhost:8080êwebMathematicaêExamplesêWebServicesêPlot.m?wsdl"DOut[3]= 8PlotExpression, PlotString


Advanced TopicsThis section discusses a variety of more complicated and advanced details of a webMathematicasite.VariablesThis section discusses the use of variables in webMathematica pages. It covers the way thatinput variables are processed as well as issues, such as scoping, that concern the use of localvariables in code that appears in webMathematica pages.There are three kinds of variables in webMathematica: input variables, page variables, andsession variables. Variables that start with $$ are input variables; they are given values fromthe HTTP request and are cleared when the kernel is cleaned when the page is finished. Variablesthat do not start with $$ only get values if they are assigned values. These assignmentslast until the page is cleared if they are page variables, and for the lifetime of an HTTP sessionif they are session variables.The details of these variables are now discussed.Input VariablesInput variables are named to start with $$ and are given values if their names are sent with theHTTP request. They have a special name because it is important to know which are the inputvariables. In the example below, the input variable $$setting will get the value entered intothe input element (because the input element uses the name setting). You can test if avariable has a value with the MSP function MSPValueQ.If[ MSPValueQ[ $$setting],....]


156 webMathematica User GuideOne important decision governs whether the value of input variables should or should not beinterpreted. If the actual string value of the variable is suitable for your uses, you should use it.Alternatively, the string value may represent some input to a Mathematica command and it willbe necessary to interpret it. For interpretation, it must be something that Mathematica caninterpret and the result must pass validation by the security system. If you find that you arestarting to modify the security system, you should consider working with the uninterpretedvalues.Interpretation of Input VariablesIf you want Mathematica to compute with an input variable, it must be interpreted. webMathematicaprovides various functions to help interpretation. It is important that you use thesefunctions because they make use of the security features. If you try to bypass them, you couldcompromise the security of your system.MSPBlock and MSPToExpression are provided to obtain expressions from input variables. Thisis, of course, completely essential for any type of interactivity. There are two stages to thisprocess: the first stage involves interpretation and the second stage involves validation. Interpretationdetermines the input to Mathematica, and validation ensures that the Mathematica commandsto be executed do not endanger the security of your site.Interpretation is based on the Mathematica function ToExpression that calls a parser to try todetermine input to Mathematica. Valid input for MSPBlock and MSPToExpression can be regularMathematica input or MathML. The following examples demonstrate input processing withMSPToExpression, showing both Mathematica and MathML input.First, load the MSP application and then lock down the security system. Security is described inits own section.In[1]:=In[2]:=Needs@ "MSP`"DSetSecurity@D;Now you can use MSPToExpression to interpret some Mathematica input.In[3]:= $$e1 = "x^y"Out[3]= x^yIn[4]:=MSPToExpression@ $$e1DOut[4]= x y


webMathematica User Guide 157Here the input is MathML.In[5]:= $$e2 = "x2"Out[5]= x2In[6]:=MSPToExpression@ $$e2DOut[6]= x 2MSPBlock provides additional functionality to work with the interpreted value of an input variable.This is described further in the Mathematica Function Reference section.webMathematica carries out validation to ensure the security of the system. Validation involveschecking any input that was sent to the server to see if it is safe to be used in a Mathematicacomputation. You can find more information on the topic in the Security section.Interpreted versus Noninterpreted ValuesAs described above, whenever you work with an input variable, you need to decide how to workwith its value. You can work with the noninterpreted value and make choices based uponits setting. (This will be a string.) Alternatively, you can interpret the value so that it canbe used for computation in Mathematica. This section gives an example of working withboth interpreted and noninterpreted values. If you installed webMathematica as describedabove, you should be able to connect to this JSP via http://localhost:8080/webMathematica/Examples/SimplifyIntegrate.jsp.Here is a listing of the form element from the JSP SimplifyIntegrate.jsp.Input:integrand = Null;If[ MSPValueQ[ $$expr],integrand = MSPToExpression[ $$expr]] ;


158 webMathematica User GuideIf[ integrand =!= Null,res = Integrate[ integrand,x] ;If[ $$simplify === "on", res = Simplify[ res]] ;MSPFormat[res,StandardForm]]Simplify result:In this example, there are two input variables, simplify and expr, that may be submitted witha request. The first of these is not interpreted and is used to select the action to be taken. Onlyexpr is actually interpreted as Mathematica input ($$expr is used inside MSPToExpression).This is necessary because it represents a general Mathematica expression and will be used asinput to Mathematica's Integrate function. The setting of the checkbox is carried by the variable$$simplify, and this is tested to see if it has the value "on". There is thus no need tointerpret it. In general it is better not to interpret if it can be avoided.MSPBlock versus MSPToExpressionwebMathematica provides two MSP functions for interpreting input variables: MSPBlock andMSPToExpression. This section contrasts and compares them.MSPBlock is probably the simpler of the two. It offers a compact and simple way to interpretand use the value of an input variable, as shown below.MSPBlock[ {$$expr, $$num},Expand[ $$expr^$$num]]Remember that the $$expr in the body, used here in an Expand computation, refers to theinterpreted value of the input variable $$expr. If the value of $$expr cannot be interpreted orfails a security test, an exception will be thrown. If $$expr has no value, then the MSPBlock willnot be evaluated, and a null result will be returned.


webMathematica User Guide 159An alternative way to interpret input is to use MSPToExpression. This can use page variables tohold the result of interpretation. It is not quite as neat as the use of MSPBlock, but is somewhatmore expressive. Here is an example.poly = Null;exponent = Null;If[ MSPValueQ[ $$expr, $$num],poly = MSPToExpression[ $$expr] ;exponent = MSPToExpression[ $$num]] ;If[ poly =!= Null && exponent =!= Null,Expand[ poly^exponent]]This example shows how webMathematica extracts the interpreted value of $$expr and stores itwith the page variable poly. This is especially useful if you use the interpreted value in a numberof different places.Page VariablesStandard Mathematica programming constructs such as Block, Module, and Function all workin their typical ways with regard to localization and scoping issues. You can find more informationon their operation in standard Mathematica references.You can use variables in Mathematica code inside of msp:evaluate tags; they can store intermediatevalues and be used for computation. Since these variables will be cleared when the kernelis cleared, it is not important to put these variables into a normal Mathematica program structuresuch as Module or Block. Consequently these are called page variables.In the example below the page variable tmp holds the value Null; it then gets the result ofcalling MSPToExpression on the input variable $$expr. If MSPToExpression was unable tocomplete its task, for example, because of a security error, it will throw an exception and tmpwill still have the value Null. Later, if tmp is not set to Null, you can be certain that the inputwas processed without problems and you can use it for calculations.


160 webMathematica User Guidetmp = Null;tmp = MSPToExpression[ $$expr] ;If[ tmp =!= Null,....]When the page is finished, tmp will be cleared.Session VariablesIf you want to save any values from one request to the next, you can use MSPSessionVariableto make a session variable. These will be stored in the server and can be used in pages that arepart of different requests. They use HTTP sessions and so the session variables for one user arenot visible to those of another user (just as the shopping cart at an e-commerce site is for oneuser and is not visible to another).In the code fragment below there are two variables; savedInput is a session variable, declaredwith MSPSessionVariable, while xInput is a page variable. In the second evaluation, if xInputhas a value, this is added to savedInput.MSPSessionVariable[ savedInput, {}];xInput = Null;xInput = MSPToExpression[ $$expr] ;If[ xInput =!= Null, savedInput = Append[ savedInput, xInput]];You can work with session variables in just the same way that you work with page variables;assigning them the results of calculations and then later retrieving them. The difference is thatsession variables last after the page is finished.


webMathematica User Guide 161An example of MSPSessionVariable is shown in Session.jsp.SecuritywebMathematica security can be divided into two parts. First, there is security concerned withgeneral web server security. Secondly, there is security concerned with the use of Mathematicalanguage programs inside a web server.Server SecuritywebMathematica is based on standard web server technology: Java Servlet and JavaServerPages (JSPs). Typically, it runs in a server called a servlet container such as Apache Tomcat.This greatly facilities security issues, because these technologies already have many welldocumentedand well-understood security features.The Apache Tomcat wiki site, http://wiki.apache.org/tomcat/FAQ/Security, states "There havebeen no public cases of damage done to a company, organization, or individual due to a Tomcatsecurity issue." Many other servlet containers have similar security records.To decide how much security to add to your server, start by checking the security policy of yourorganization. You can then decide whether you want to add features such as restricting serveraccess to users within your organization, locating the server in some special network, setting upauthentication, and using HTTPS for communication.These security features, and many others, are all well supported for many types of servers.Remember that some of these solutions, such as restricting access, might not be available to allwebMathematica licenses.Mathematica Program SecurityMathematica is a general programming language with many features and tools for interactingwith the computer on which it runs. For example, it can add, delete, and modify files as well aslaunch and run programs. Since webMathematica executes Mathematica programs on theserver, this means there are security implications. It is necessary to prevent unintended executionof Mathematica code.


162 webMathematica User GuideThe Mathematica programming language is a very dynamic language, and consequently, it isvery straightforward for one Mathematica program to construct another. In fact, it is quite easyto pass a textual form of a Mathematica program as a string, turn it into a program, and executeit. This dynamic nature is an important security issue to consider.webMathematica provides a security process to guard against such problems. The main focus isto prevent input from the external world from being accepted by a webMathematica programand executed. The security process analyzes input from the server and accepts or rejects itbased on a set of criteria. The webMathematica developer writing scripts in Mathematica usesfunctions from the security system, and this ensures the security of the server.MSPBlockMSPBlock is one of the key security functions for webMathematica. It is useful for taking inputto the server and converting it to be used in a computation. A typical script, taken from theexample Expand.jsp, is shown below.MSPBlock[ {$$expr, $$num},Expand[$$expr^$$num]]Remember that variables starting with $$, such as $$expr, are input variables. These havebeen transmitted as part of the web request and are potential sources of attack. In fact, givingthem a special naming convention, which draws attention to them, is one security feature.Using MSPBlock avoids security problems because it applies the security test to its variables, inthis case $$expr and $$num. If either fails the test, a security exception is thrown and the bodyis never evaluated; in fact a page error results. (The section on handling errors shows how youcan custom the exact behavior of page errors.)MSPToExpressionMSPToExpression is the other key security function for webMathematica. It is used for takinginput to the server and turning it into a Mathematica expression that can be used for computing.A typical script, taken from the example Integrate.jsp, is shown below.integrand = Null;If[ MSPValueQ[ $$expr],integrand = MSPToExpression[ $$expr]] ;


webMathematica User Guide 163If the variable $$expr failed the security test, then MSPToExpression will throw a securityexception and the page will be terminated. You can modify the treatment of page errors asdiscussed in the section on handling errors.Avoid ToExpressionOne of the key functions to avoid is ToExpression, the command that turns a string into aMathematica program. In fact, well-written Mathematica programs rarely need to actually usethis. One case might be when an input has been passed with the web request. But this isexactly what MSPToExpression is for, and ToExpression should not be used.webMathematica still provides a check to prevent users from calling ToExpression on input tothe server. For example, in the following the security test is still applied to the input.val = ToExpression[ $$num]This provides an extra level of security, though it would be better to use MSPToExpression.You can disable this check. This is described in the section on ToExpression Validation.Security ValidationThis section describes how the security validation process works and how it can be customized.The Validation ProcessThe validation process works in a straightforward manner, and you can customize it to givemore or less security. You can investigate its operation in the following steps.First, load the MSP Mathematica application and then lock down the security model, whichcannot be modified after SetSecurity is called. When the server initializes Mathematica, it callsSetSecurity.In[1]:=In[2]:=Needs@"MSP`"DMSP`Utility`SetSecurity@ "SecurityConfiguration.m"D;Now you can test expressions for validity. The first example shows a harmless mathematicalexpression that is found to be secure.In[3]:= MSP`Utility`SecurityFunction@InsecureExprQ@ HoldComplete@ Sin@6DDDDOut[3]= False


164 webMathematica User GuideHere is a less-than-friendly expression, the sort of thing that could be sent as an attack.In[4]:= MSP`Utility`SecurityFunction@InsecureExprQ@ HoldComplete@ Run@ "telnetd"DDDDOut[4]= TrueValidation works by collecting all the symbols into a list and steadily reducing the list. If anysymbols remain after reduction, the expression is not secure. The reduction process works withlists of symbol and context names that either can be allowed or disallowed according to thefollowing steps.1. If AllowedContexts is set, remove symbols with these contexts, otherwise remove symbolswith contexts not in DisallowedContexts.2. If DisallowedSymbols is set, remove symbols not in DisallowedSymbols, otherwiseremove symbols that are in AllowedSymbols.3. If no symbols remain, the expression is secure; otherwise it is not secure.These tests allow you to be restrictive or flexible. If you use the allowed lists, you are restrictiveand have more security, whereas if you use the disallowed lists, you are less restrictive andhave less security. It is up to each individual site to decide the appropriate balance.When the server is started, a default security model is installed. This default security modellooks like this.This is the value of AllowedContexts.In[5]:=MSP`Utility`SecurityFunction@SecurityDataD@@1DDOut[5]= 8Global`


webMathematica User Guide 165EulerE, GegenbauerC, ChebyshevT, ChebyshevU, JacobiP, BetaRegularized, GammaRegularized,InverseBetaRegularized, InverseGammaRegularized, Pochhammer, LerchPhi, PolyLog,RiemannSiegelTheta, RiemannSiegelZ, LogIntegral, LegendreQ, Hypergeometric1F1Regularized,HypergeometricU, Hypergeometric2F1Regularized, JacobiCD, JacobiCN, JacobiCS, JacobiDC,JacobiDN, JacobiDS, JacobiNC, JacobiND, JacobiNS, JacobiSC, JacobiSD, JacobiSN,InverseJacobiCD, InverseJacobiCN, InverseJacobiCS, InverseJacobiDC, InverseJacobiDN,InverseJacobiDS, InverseJacobiNC, InverseJacobiND, InverseJacobiNS, InverseJacobiSC,InverseJacobiSD, InverseJacobiSN, EllipticTheta, EllipticThetaPrime, WeierStrassP,WeierstrassPPrime, InverseWeierstrassP, WeierstrassSigma, WeierstrassZeta, MathieuC,MathieuS, MathieuCPrime, MathieuSPrime, ProductLog, Piecewise, ReleaseHold, $Failed, RootDDisallowedContexts has the value Null.In[7]:=MSP`Utility`SecurityFunction@SecurityDataD@@3DDDisallowedSymbols has the value Null.In[8]:=MSP`Utility`SecurityFunction@SecurityDataD@@4DDThis model will allow any symbol in Global` context, in addition to a number of other specificsymbols. This is a fairly restrictive model that provides a higher level of security.Configuring a Security ModelTo make your own security definitions you should put them into a file in the /WEB-INF directory.The name of the file is set in the MSPConfiguration.xml file with the configuration parameterSecurityConfigurationFile, which refers to the name relative to the base web application.For example, if the configuration information is in a file called ComputeSiteSecurity.m, insideof WEB-INF, the following should be added./WEB-INF/ComputeSiteSecurity.mA sample security configuration file is shown below. This only allows symbols in the Global`context in addition to Plus, Times, and Power. This is a particularly restrictive security systemthat might be appropriate in some circumstances.{"AllowedContexts" -> {"Global`"},"AllowedSymbols" ->HoldComplete[ Plus, Times, Power, HoldComplete]}As described in the section on Multiple Kernel Pools, it is possible to use different configurationdetails for different request URLs. Each pool has its own configuration file and its own securitysystem.


166 webMathematica User GuideWhen each Mathematica kernel is launched, the security data is sent to the log system at theDEBUG level.ToExpression ValidationThe webMathematica security system adds a security test to ToExpression when it is used oninput from the server. This is described in the section on avoiding ToExpression.You can disable this security test by setting the Mathematica variable MSP`Utility`CheckToExÖpression to False. In addition, you can disable the test in the MSPConfiguration.xml file withthe configuration parameter CheckToExpression.falseIt is probably an exceptional site that disables this security feature.Of course, if the string input to ToExpression comes from an input sent with the request, but ismodified in some way, the call to ToExpression will not carry out any validation. Therefore, itis highly recommended that you never use ToExpression, but instead use MSPToExpression.Security and Kernel PoolsThe security system is configured as part of a kernel pool. This means you can have differentstyles of security configuration for different types of access. More information can be found inthe section on kernel pools.Access RestrictionsYou may wish to restrict access to certain parts of your system such as the Kernel Monitor,which is provided for monitoring and debugging your system. In this case, refer to the sectionson Logging and the Kernel Monitor. The installation section on Apache and Tomcat describeshow this can be done when webMathematica is used from the Apache web server.


webMathematica User Guide 167Evaluation FormattingThe output of an msp:evaluate tag is inserted into the page that is returned as part of the webrequest. This section will describe the different types of formatting output. This topic is relatedto the placement of Mathematica commands into webMathematica pages and more informationis found in Appendix: evaluate.Automatic FormattingAny result that is computed by an msp:evaluate tag that is not a string will be formatted into astring that will use the necessary HTML escapes. An example is shown below.Range[5]This type of formatting is equivalent to MSPFormat with a format type of OutputForm.MSPFormatDifferent styles of formatting output can be generated with MSPFormat. The example belowuses MSPFormat with a format type of TraditionalForm.MSPFormat[ Sqrt[ Sin[x]], TraditionalForm]Output can be generated that is formatted into HTML, MathML, or an image. The latter gives aconvenient way to show typeset mathematics.String FormattingIf the result of evaluate is a string, it is left unmodified and added to the output page. This isoften useful for constructing HTML, as shown in the example below.StringJoin[ "", ToString[ x], ""]If you have a string and you want it to be formatted with HTML escapes, then you can wrap itin MSPFormat.


168 webMathematica User GuideGraphics and Image FormattingThere are several convenient functions for formatting graphics objects so that a picture appearsin the output. The example below uses MSPShow to display a plot.MSPShow[ Plot[Sin[x],{x,0,2Pi}]]Suppressing OutputYou may want to use the msp:evaluate tag to evaluate something without leaving output inthe resulting page. This can be done by adding a semicolon ';' after the computation, as shownbelow.Needs[ "MyPackage"];Adding a semicolon causes the Mathematica symbol Null to be returned, and this is formattedto leave no trace in the output.Output is suppressed whatever the computation, whether it uses one of the formatting functions,a graphics function, or a function that returns Print or Message output. In the followingexample, no output will be seen from the message output function because it is followed by asemicolon.MSPGetMessages[];Multiple CalculationsTo calculate more than one result in an msp:evaluate tag, the different steps must be separatedwith a semicolon ';'. The result of the last computation will be formatted and appear inthe output page. In the example below, the numerical result of x+y computation will appear.x = Sin[5.6];y = Sqrt[x];x+yIf you wish to suppress the result of the last computation, you can use a semicolon ';' asdescribed in the section on Suppressing Output.


webMathematica User Guide 169Multiple Kernel PoolsFor some applications, it is useful to use several pools of Mathematica kernels to serve differentrequests. You can configure the kernels in each pool differently, perhaps with different timeoutparameters or different initialization files. Another possibility would be to use a pool with oneMathematica kernel as a demonstration server and another pool with four Mathematica kernelsto serve customer requests. This would ensure that the customers received priority. Anotherbenefit of multiple pools is the guarantee that one set of computations is completely isolatedfrom another. Disadvantages, however, are the additional administration and the need for extrawebMathematica licenses.The different pools are all configured in the MSPConfiguration.xml file. By default, one pool iscreated, called the General pool. If you wish to configure for additional pools, add a KernelPoolsection to the MSPConfiguration.xml file, as shown below.LongerC:\Program Files\<strong>Wolfram</strong><strong>Research</strong>\Mathematica\7.060000/Longer/*This creates a pool called Longer, with a time limit of 60 seconds. Any URL that starts withLonger will use this pool. The documentation on MSPConfiguration.xml describes the configurationparameters that can be placed in these files.If you wish to work with multiple pools, you need to have webMathematica licenses for all thekernels you wish to run. The Kernel Monitor contains information on all the pools, so this is agood place to confirm that a pool has been properly initialized. The servlet log files also containinformation about each pool, as the section on Logging describes.


170 webMathematica User GuideMultiple Web ApplicationsYet another way to divide requests is to install multiple web applications. This might be beneficialif your server provides special configuration tools for web applications. For this you wouldrepeat the installation process for the webMathematica web application, giving each new installationa different name. All web applications that are run in the same instance of the Java VirtualMachine will share the same Kernel Monitor.Mapping URLs onto JSPsThe way that webMathematica maps URLs onto JSPs is very straightforward. The URL names aJSP that lives directly in the webMathematica web application or in a subdirectory. Some examplesare shown in this section.In the first table, the MSP Script.jsp is located in the top of the webMathematica web applicationdirectory, for example, /usr/local/tomcat/webapps/webMathematica. It can be accessedby the URL http://host/webMathematica/Script.jsp.script namescript locationURLlocating in the root directoryScript.jspêusrêlocalêtomcatêwebappsêwebMathematicahttp:êêhostêwebMathematicaêScript.jspIn this second table, Script1.jsp is located in a subdirectory of the webMathematica webapplication directory, for example, /usr/local/tomcat/webapps/webMathematica/Test. TheURL http://host/webMathematica/Test/Script1.jsp will find this JSP.script namescript locationURLlocating in a subdirectoryScript1.jspêusrêlocalêtomcatêwebappsêwebMathematicaêTesthttp:êêhostêwebMathematicaêTestêScript1.jspRemember that you should not place JSPs inside the WEB-INF directory. If you do, they will notbe accessible.


webMathematica User Guide 171Handling ErrorsThere are a number of ways that webMathematica computations can lead to an error. An inputmight fail the security test, the computation might take too long so that the Mathematica kernelis restarted, or there might be some type of page logic error. You can learn about certain typesof errors and, often, solve them using the logging system. However, it is not possible to avoidall errors, for example you cannot predict all inputs to the server, so some of them might failthe security test. In these cases you might want to customize the way the error is handled.When an error is generated webMathematica deals with it in one of two ways. For serious errorsthat require the Mathematica kernel to be restarted, the request results in an HTTP error ofstatus 403, indicating that the server could not complete the request. Alternatively, other errorsresult in a Mathematica exception being thrown and this leads to a normal page being returned,but with some special text being inserted for the error.If you want to customize the handling of these errors, you can do this with Mathematica code tocatch the Mathematica exceptions and by adding an error page to handle the HTTP error.Catching Mathematica Error ExceptionswebMathematica throws errors in Mathematica as MSPException expressions, and you can addcode to catch these. The exceptions that can be caught are listed below.MSPException@" ParseError "DMSPException@" SecurityError "DMSPException@" ValueError "DMSPException@" VariableError "DMSPException@" NoValueError "DMSPException@" VersionError "Dif the value cannot be interpreted by Mathematicaif the value does not pass the security testif the value is not a string, this indicates a programmaticerror by the page authorif the variable is not a Mathematica symbol, this indicates aprogrammatic error by the page authorif a variable has no valueif a version mismatch problem is foundSome sample code that uses Catch to catch a security exception is shown below.Catch[ expr, MSPException["SecurityError"], errorFunction]


172 webMathematica User GuideA sample implementation for errorFunction is shown below. As you can see, its signature getstwo arguments; the actual exception expression is the second argument.errorFunction[_, MSPException[ "SecurityError"]] :=tidyUpSecurityError[]Adding an HTTP Error PageYou can catch the HTTP errors by adding an error page. This can be done by adding code to theweb.xml file that is found in the WEB-INF folder. The following should redirect to a page/Resources/Tools/Error.jsp; in fact, this is a sample page found in the webMathematicalayout.403/Resources/Tools/Error.jspInside the error page you need to reset the error. You can also get an integral listing of theerror and an error string. Sample code is shown in the following.Displaying Mathematics and GraphicsIn order to display typeset mathematics and graphics, the server can generate images. Theseprovide a simple way to view the results of computations. However, they suffer from the seriousdefect that they cannot be used by the client. They cannot be resized, drawn with differentfonts, or viewed in some alternative way. It is also hard for a computer program to extract anymeaning from an image. Alternatives to images exist. In the case of mathematics you can useMathML, for graphics you can use SVG, and the LiveGraphics3D applet can be deployed forthree-dimensional graphics. These alternatives are not always the appropriate solution and, forthis reason, functions for generating images are provided.


webMathematica User Guide 173When a Mathematica kernel generates an image, it is stored in a file on the server and adds areference in the HTML file that is returned. For example, the following img element may begenerated.The SRC attribute references the MSP servlet through a URL, which includes a parameter thatgives the name of the file. The MSP servlet returns the contents of the file and periodicallydeletes old image files. The actual location in which image files are saved is a workspace directoryprovided by the servlet container.More information about generating images can be found in the function pages for MSPFormatand MSPShow.An alternative way to generate images is to use the Mathematica command Export, availablefor use with the function MSPExportImage. This provides more features, such as transparentbackgrounds, but takes longer to generate. MSPExportImage always makes use of the Mathematicafront end.MSP Functions Returning ImagesThere are various MSP functions that return images: MSPShow, MSPShowAnimation, andMSPExportImage; in addition MSPFormat may return an image. It should be noted that these allwork by returning a string that contains the necessary img tag to reference the image file thatis stored on the server. An example is shown below.MSPShow[ graphics]Therefore, if the MSP function is followed by a semicolon ';', as shown below, the output issuppressed. The use of a semicolon to suppress output is discussed in the section on EvaluationFormatting.MSPShow[ graphics];Another use of these functions is to embed their results into some other formatting functionsuch as those in the HTML Package. The example below will return an HTML table with twoimages.


174 webMathematica User GuideNeeds["MSP`HTML`"]HTMLTableForm[ {MSPShow[ g1], MSPShow[ g2]}]LiveGraphics3DThe LiveGraphics3D applet displays Mathematica three-dimensional graphics and providessupport for features such as interactive rotation and resizing. A simple example that shows howto use MSPLive3D to embed a three-dimensional graphics object into a web page follows.MSPLive3D[ Graphics3D[ Line[ {{0, 0, 0}, {1, 1, 1}}]]]A bigger example that shows more of the applet is discussed in Live 3D Plotting: Plot3DLive.jsp.Reference information is found in the appendix LiveGraphics3D.Including Static FileswebMathematica involves returning dynamically generated material. However, the web pagesthat webMathematica generates may include static images, which might have been generatedby a designer. webMathematica comes with a number of images, such as banners and buttons,which you may use. This section discusses how webMathematica pages can use static files. Itwill focus on image files, but the principles apply in general to other files.Images are placed in HTML pages with an img tag. It is convenient for these tags to use arelative URL to refer to the server from which the HTML page originated. Web pages that userelative URLs are easy to move from one server to another. There are two types of relativeURLs: those that start with a '/' character and those that do not. The following URL starts with a'/' character.If webMathematica returns an HTML page containing this URL, the browser will try to load theimage from the Images directory within the webMathematica web application. The servlet


webMathematica User Guide 175container is capable of returning this image, which should appear correctly. If these imagerequests do not work and you are using a servlet container as a backend to another webserver, you should make certain that it forwards requests for images to the servlet engine.An alternative is a relative URL that does not start with a '/' character. For example, an HTMLpage, which is generated by a URL such as http://server/webMathematica/Demo/Test.jsp,may contain an img tag such as the following.In this case, the browser will try to retrieve the image with the URL http://server/webMatheÖmatica/Demo/folder/bullet.gif, which can be processed by the servlet container to returnthe appropriate image file. This is convenient because you can place images and JSPs togetherin the same directory.


TroubleshootingThis section describes techniques for addressing problems and errors. You should first workthrough the Initial Checks section, which will help track down any general problems. If this doesnot help, study the Specific Problems section. Further information can be obtained from the<strong>Wolfram</strong> <strong>Research</strong> support website, http://support.wolfram.com. Finally, if you have notresolved your problem and are eligible for support, you should look at the Reporting Problemssection.Initial ChecksIf you try to use a browser to connect to a webMathematica server and it does not operate inthe expected way, try the following steps.Check the ServerMake absolutely certain that your servlet container is working correctly. If you cannot connectto the demonstration examples that come with your container, then webMathematica is unlikelyto work. Furthermore, <strong>Wolfram</strong> <strong>Research</strong> will not be able to give more than minimal assistanceuntil your servlet container is working.Check the URLIf your servlet container works but webMathematica does not, make sure you are usinga correct URL. These are case sensitive, so make sure you use capital letters in the sameplaces as the documentation describes. For example, http://localhost:8080/webMathematica/Examples/Hello.jsp is the appropriate usage. Make sure that this URL is consistent with the wayyou connect to your servlet container. If you need to specify a port number for your servletcontainer, you will need to use this for webMathematica. For example, the default settings fordirect access for Tomcat is port 8080. A URL for a different servlet container might be different.The URLs in this document are all specified for Tomcat.If you do not specify the URL correctly, you may see a Not Found (404) error in your browser.


webMathematica User Guide 177Check the Initial PageIf the initial page that is returned to your browser in response to a webMathematica URL, suchas http://localhost:8080/webMathematica/Examples/Hello.jsp, contains some other indicationof an error, study it carefully. Some typical problems include configuration errors, such asfailure to locate a configuration file or failure to launch Mathematica. Studying the initial pageand rereading the installation instructions or looking at the specific problems listed later in thissection may help to resolve the problem.If no initial page is returned, your server is not operating. As noted above, if your server doesnot work, webMathematica cannot work.If the initial page does not help resolve your problem, please save the page. It may be useful atsome later stage.Check the Kernel MonitorThe kernel monitor contains information on the configuration of the webMathematica site andalso can print out information if your server is misconfigured. You should be able to find themonitor via http://localhost:8080/webMathematica/Resources/Tools/KernelMonitor.jsp. (Youmay have some different URL for accessing your server.) The monitor is described in moredetail in a previous section.Check the Logging SystemThe logging system is a good place to start to search for information on problems.Check the Console ShellSome servlet containers are launched from a command line in a console shell, and this maycontain relevant information on any problems.


178 webMathematica User GuideCheck MathematicaRun Mathematica in the same way that it is run from the servlet container. For example, underUnix, the servlet container often runs as tomcat, so this should be used to run Mathematica. Dothis for both the Mathematica kernel and front end.Under Unix, a typical command to run the Mathematica kernel as tomcat is as follows.[user> su -c 'su tomcat -c math'Here is a typical command to run the Mathematica front end as tomcat.[user> su -c 'su tomcat -c mathematica'Under Windows, it is possible to run the Mathematica kernel and front end from the Start menu.Running Mathematica like this will help to identify problems that may prevent the web systemfrom launching Mathematica. One source of problems is caused by a failure to find a license torun Mathematica. You can resolve this by making sure that the valid Mathematica license ispresent in the Mathematica layout, probably by placing a mathpass file into$InstallationDirectory/Configuration/Licensing.Specific ProblemsThis section describes a number of specific problems you might find when installing or runningwebMathematica. In addition to this section, you may wish to look at the sections on Loggingand the Kernel Monitor, as well as the section on Debugging webMathematica.Problems Running the KernelIf the Mathematica kernel cannot run, this is a fatal error for your server. There are two commoncauses for this.A first cause is that the Mathematica installation cannot be found; this might happen if youinstalled Mathematica in a non-standard location. You can resolve this by setting the KernelExeÖcutable parameter in MSPConfiguration.xml; this is discussed in detail in Installing the web-Mathematica Web Application.


webMathematica User Guide 179A second cause is that Mathematica cannot find its license and so cannot run. You can test forthis with the Check Mathematica test.Problems Running the Front EndCertain operations require the Mathematica front end, for example, the rendering of typesetimages and graphics or the use of any Mathematica notebook API functions. If you are runningon a Unix machine and using the X Window System, make sure you have studied the section onConfiguring for the X Window System.Problems Testing Xvnc (Unix only)This is only an issue for running webMathematica under the X Window System.As described in the section on installation, it is typical to run a virtual frame buffer X server,Xvnc, to run the Mathematica front end. If this does not seem to be running correctly (e.g.graphics do not work), you can query the running of the frame buffer by using the vncviewerutility.vncviewer :1You will need to enter the password for the Xvnc server, and then you will see a view of thescreen that the server provides. You should see the Mathematica front end running. If there areany problems, you may see dialog boxes describing the problems.Problems Testing Xvfb (Unix only)This is only an issue for running webMathematica under the X Window System.Xvfb is a virtual frame buffer X server that can run the Mathematica front end. If it does notseem to be running correctly (e.g. graphics do not work), you can query the running of theframe buffer by using the xwd utility.xwd -display :1 -root | xwudUnder certain configurations, this can be very slow. You can improve the performance by modifyingthe bit depth of the virtual server, for example, from 24 to 16. The following will run theserver with bit depth of 24.


180 webMathematica User Guidesu tomcat -c "/usr/X11R6/bin/Xvfb :1 -screen 0 800x600x24 "&The command to run the server with a bit depth of 16 follows.su tomcat -c "/usr/X11R6/bin/Xvfb :1 -screen 0 800x600x16 "&Images Do Not WorkIf you find that pages that should hold images, such as the plotting examples, do not actuallyshow any pictures, you should check the logging system; problems will be recorded here.If you find that typeset images are failing, then you should confirm that the front end is properlyconfigured.Mathematica Packages and ApplicationsIf you find that you have problems using functions from Mathematica packages or applications,then study the section on Mathematica Packages and Applications. A problem may occur if youtry to use code that does not use the Mathematica package format, since the postprocessingcode for each request will remove any symbols in the default context.Kernel InitializationIf you make definitions for symbols that are in the default context with the KernelInitializeÖCode configuration setting, they will be cleared and the symbols removed by the postprocessingcode for each request. This also applies to packages that are loaded from the KernelInitializeÖCode and that are not written in the Mathematica package format to make proper use of contexts.Any definitions must use their own context for names. You can do this by prepending thename with a context (for example TestNameSpace`Compute) or by making appropriate use ofBeginPackage[] and EndPackage[].Another point about the use of the KernelInitializeCode parameter is that certain packagesmay require the front end in order to be initialized correctly. You can load these packages intowebMathematica with Developer`UseFrontEnd; this is shown below.Developer`UseFrontEnd[Needs[ "MyApplication`"]]


webMathematica User Guide 181Vertical Alignment in FormattingIf you find that formatted output has vertical text (such as superscript, subscripts, or fractions)that does not line up, the problem may be that you are formatting into a text-based output andnot using a fixed-width font. The text-based formatting requires a fixed-width font for verticalalignment.Timeout ProblemsYou can confirm that your computations are failing to complete, due to the request timing outby inspecting the log system. In this case you should first check the computations. Perhapsthere is some problem in the code being executed that causes it to take longer than anticipated.To check this, you could try to run the input in a normal session of Mathematica. If youthink the code is running correctly, you could try to increase the KernelTimeLimit configurationparameter.UnsatisfiedLinkErrorIf you find that webMathematica does not work, you may notice an UnsatisfiedLinkErrorexception in the log files.Exception in thread "main" java.lang.UnsatisfiedLinkError:MLOpenat com.wolfram.jlink.NativeLink.MLOpen(Native Method)at com.wolfram.jlink.NativeLink.


182 webMathematica User GuideTomcat, can load native libraries from inside a web application. For these, the version of J/Linkinside webMathematica should work. If you see this problem you should contact support forassistance.Cannot Load JLink`If you find that webMathematica does not work, you may notice in the servlet log that JLink`has not been loaded.Error:: Mathematica cannot load JLink`.Check that the JLink Mathematica application has beeninstalled as described in the JLink documentation.This means that you did not install J/Link correctly, specifically that the Mathematica applicationJ/Link has not been located by Mathematica. Since webMathematica contains its own version ofJ/Link, this problem should not be observed, and you should contact support for assistance.NoClassDefFoundError: TryCatchFinallyIf you find that webMathematica does not work, you may notice in the servlet log a report of aNoClassDefFoundError exception for TryCatchFinally.500 Internal Server Error/webMathematica/Examples/Hello.jsp:javax/servlet/jsp/tagext/TryCatchFinallyjava.lang.NoClassDefFoundError: javax/servlet/jsp/tagext/TryCatchFinallyat java.lang.ClassLoader.defineClass0(Native Method)at java.lang.ClassLoader.defineClass(ClassLoader.java:509)at java.lang.ClassLoader.defineClass(ClassLoader.java:438)This error is found when the webMathematica custom JSP tags are used on older servlet containersthat do not support the JSP 1.2 API.NoClassDefFoundError: JLink ClassesIf you find that webMathematica does not work, you may notice in the initial web page or in theservlet log a report of a NoClassDefFoundError exception. An example is shown below.


webMathematica User Guide 183java.lang.NoClassDefFoundError: com/wolfram/jlink/MathLinkExceptionat java.lang.Class.newInstance0(Native Method)at java.lang.Class.newInstance(Class.java:237)This means that J/Link is not installed correctly; specifically the J/Link Java archive has notbeen located by the Java system. This archive is called JLink.jar. Since webMathematicacontains its own version of J/Link, this problem should not be observed, and you should contactsupport for assistance.NoSuchMethodError: KernelDataIf you find that webMathematica does not work, you may notice in the initial web page or in theservlet log a report of a NoSuchMethodError exception that is generated inside of the starÖtInit method of the KernelData class. An example is shown below.java.lang.NoSuchMethodError atcom.wolfram.kerneltools.KernelData.startInit(Unknown Source) atcom.wolfram.kerneltools.KernelPool.initKernels(Unknown Source) atcom.wolfram.kerneltools.KernelPoolManager.acquireKernelPool(UnknownSource)This will occur if you try to run webMathematica with an older version of J/Link. This can hap-pen if, at some time in the past, a copy of JLink.jar was installed directly into the Java run-time. In general, it is not a good idea to install classes into your Java runtime, because theseclasses will always be loaded even if a newer version is made available, as happens with thiserror. The solution is to search in your copy of Java for JLink.jar and remove it. You shouldalso search for and remove the native library JLinkNativeLibrary, which is often found in theSystemFiles directory. webMathematica has its own copy of J/Link and there is no need toinstall J/Link into the Java runtime.Debugging webMathematicawebMathematica involves running computations inside a server. This poses a number of problemsand constraints for investigating why it does not work as you intend. The best way totrack down issues is to use <strong>Wolfram</strong> Workbench to connect to the server and debug your code.


184 webMathematica User GuideNot Using <strong>Wolfram</strong> WorkbenchIf you do not want to use <strong>Wolfram</strong> Workbench, you can use messages and print statements toresolve your problems. You can get message output returned in your web page with MSPGetMesÖsages and the output of print statements with MSPGetPrintOutput. The capture of messageand print output is described in the example Messages.jsp. It is probably a good idea to confirmthat your calculations work correctly in an interactive Mathematica session.In addition to message and print output, you can use the logging and monitor features providedby the system. These are described in more detail in the sections on Logging and the KernelMonitor. The simplest technique is to look at the files written by the servlet engine. A moresophisticated way is to use the monitor, which can be accessed via a URL, for example, http://localhost:8080/webMathematica/Resources/Tools/KernelMonitor.jsp. If you increase the level oflog output by setting VerboseLogs to true, you will generate more output.Using <strong>Wolfram</strong> WorkbenchYou can use <strong>Wolfram</strong> Workbench to debug your Mathematica code as it runs in the server. Withthis you can do things such as set breakpoints, examine the stack, and catch messages. In thisway you can gain a deeper understanding of how your code runs, thereby helping you todevelop more quickly. You can do this for code loaded into a JSP and for code that runs as aweb service. For more information, see the debugging with the Workbench sections of thedocumentation.LoggingAn administrator needs to confirm correct operation of a server and track down problems asthey occur. webMathematica helps by providing a variety of different types of logging systems.webMathematica LoggingwebMathematica provides a flexible logging system that allows you to learn about the runningof your server. This can be useful as a way to track down errors. The system is built on top of


webMathematica User Guide 185the popular log4j logging services. The system is configured with files loaded when the serverlaunches, and can record different levels of event, FATAL, ERROR, WARN, INFO, DEBUG, and TRACE,ranging from serious to not serious.Configuration for the webMathematica logging system is found in the file log4j.propertieslocated in webMathematica/WEB-INF/classes. The default provides four loggers, which collectdifferent types of log information. By default, logging only records events that are at level INFOand above. Output for all the loggers goes into /logs.webMathematica.logKernelEvents.logJobEvents.logcore webMathematica log filekernel events, such as evaluations, messages, and printoutputlogging for jobs that support queuesDefault webMathematica log files.The core webMathematica log file is the core main logger that records many different types ofevent. The request log file contains logging for each request, and is a simple way to see activityto the site. The kernel log file shows information about how the kernel is used. In particular, itcontains message output (at the WARN level) and print output (at the INFO level).The folder webMathematica/WEB-INF/classes/samples contains a sample logging configurationfile, log4j.properties.DEBUG, which turns on logging at the DEBUG level. It also containslog4j.properties-sample, a logging file with more comments, and the original file,log4j.properties.BACK. To activate one of these, copy it to webMathematica/WEB-INFÖ/classes, rename it to log4j.properties, and restart the server. The log files will collectinformation at the new level. This might be a good way to track down problems in your webMathematicaserver.To configure the logging system at more detail, you could study log4j.properties-sample;then you should probably consult one of the many references that exist for log4j.Server LoggingOne key place to search for information on problems is the server logging system. Under Tomcat,typical logging files are /logs/localhost_log.YYYY-MM-DD.txt, wherethe filename includes the date. For other servlet containers you will need to study the relevant


186 webMathematica User Guidedocumentation. If the log file is empty, it may indicate that the user running the servlet containerdoes not have permission to write to the log file directory.The log file records serious errors; if your system does not function correctly at startup time, itwould be good to look here. For example, if the configuration file is not found or the kernelcannot be launched, this will be recorded in the log file. Later, if there is a serious error thatrequires shutting down a kernel, this is also recorded.Note that the server logs do not show webMathematica specific logging. This comes in thewebMathematica logging system.The Kernel MonitorThe kernel monitor is a servlet that collects information on the running of your site. You shouldbe able to find the monitor via the URL http://localhost:8080/webMathematica/Resources/Tools/KernelMonitor.jsp. (You may have some different URL for accessing your server.) Uponaccess, the monitor brings up a page showing the current status of webMathematica, describingvarious parameters of the site, and giving status information for each kernel. If you look at thispage, access some JSPs, and then look at the page again, you should see updates, such as achange in the number of times kernels have been accessed.For security purposes it would be sensible to restrict access to the kernel monitor. If the servletengine is accessed via an Apache web server, access can be restricted in the server configurationfiles. The section on Apache and Tomcat describes how this can be done.Reporting ProblemsIf you have been unable to resolve your problem, and you are eligible for support, you shouldprepare the following information. The more detailed the information, the easier it will be totrack down the problem.1. The version of webMathematica you are using2. The version of Mathematica you are using3. Your computer operating system version (e.g., Windows 2000)4. The servlet engine you are using


webMathematica User Guide 1875. The HTTP server you are using (if applicable, e.g., Apache)6. A one- or two-line summary of the problem, including any steps that may be necessary toreproduce itIn addition, for installation problems, the following items will be very useful7. A copy of the initial HTML page8. A copy of the log filesThis information should then be supplied with any request for support.


Configuration


webMathematica User Guide 191CheckToExpressionCheckToExpressionwhether a security check should be applied to ToExpressionMORE INFORMATION† CheckToExpression is a configuration setting that specifies whether a security check should beapplied to the Mathematica function ToExpression. The default value is true and it is not commonthat this should be changed. More information on this and other security issues can be found in theAdvanced Topics: Security section.EXAMPLESBasic Examples (1)A sample setting for CheckToExpression is shown below.falseTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide† Security in webMathematica User Guide


192 webMathematica User GuideCollectStreamsCollectStreamswhether streams opened during a request should be automatically closedMORE INFORMATION† CollectStreams is a configuration setting that specifies whether streams opened in the requestshould be closed when the request ends. By default, this is true, which helps to limit the increase inresources used by Mathematica and boost reliability.EXAMPLESBasic Examples (1)A sample setting for CollectStreams is shown below.falseTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 193FileUploadSizeLimitFileUploadSizeLimitthe limit on the size of files that can be uploadedMORE INFORMATION† FileUploadSizeLimit is a configuration setting that specifies the maximum size of files that areuploaded to the server.EXAMPLESBasic Examples (1)A sample setting for FileUploadSizeLimit is shown below.1000000TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


194 webMathematica User GuideFrontEndExecutableFrontEndExecutablethe path to the front end executableMORE INFORMATION† FrontEndExecutable is a configuration setting that sets the path of the front end executable. Typically,the front end is found in the same location as the Mathematica kernel and there is no need tomodify this setting.EXAMPLESBasic Examples (1)A sample setting is shown below.D:\Applications\<strong>Wolfram</strong>\Mathematica\7.0\Mathematica.exeTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 195FrontEndLaunchFlagsFrontEndLaunchFlagsflags to use when the front end is launchedMORE INFORMATION† FrontEndLaunchFlags is a configuration setting that gives any special flags you want to set on thecommand line for the launch of the Mathematica front end. Typically this is not needed, but oneexample is that you might want to set the password file that is used.EXAMPLESBasic Examples (1)A sample setting is shown below.-display :1 -nogui -geometry 1000x500+10+10TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


196 webMathematica User GuideJLinkNativeLibraryDirectoryJLinkNativeLibraryDirectorysets the location of the J/Link native libraryMORE INFORMATION† JLinkNativeLibraryDirectory is a configuration setting that specifies the location of the J/Linknative library. Typically, webMathematica finds the J/Link native library automatically so it is notnecessary to use this setting.EXAMPLESBasic Examples (1)A sample setting for JLinkNativeLibraryDirectory is shown below.d:\Mathematica\JLink\SystemFiles\Libraries\WindowsTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 197KeepFrontEndAliveKeepFrontEndAlivewhether the front end should be kept running after usageMORE INFORMATION† KeepFrontEndAlive is a configuration setting that sets whether the front end is kept running after ithas been launched and used. By default, it is kept running and this leads to improved performance.Only special circumstances would cause it to shut down.EXAMPLESBasic Examples (1)A sample setting is shown below. This will make the front end exit after it has been used.falseTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


198 webMathematica User GuideKernelAcquireCodeKernelAcquireCodeMathematica code to run when a kernel is acquiredMORE INFORMATION† KernelAcquireCode is a configuration setting giving Mathematica code that runs when a kernel isacquired by the server to start a new computation.EXAMPLESBasic Examples (1)A sample setting is shown below.MyApplication`SetupPage[]TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 199KernelAcquireLimitKernelAcquireLimitthe number of requests a kernel can serveMORE INFORMATION† KernelAcquireLimit is a configuration setting that sets the number of requests a kernel can serve.After this limit is reached, the kernel is shut down and a new one is started.EXAMPLESBasic Examples (1)A sample setting is shown below. This means that the kernel will be restarted every 100 times it is used.100TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


200 webMathematica User GuideKernelBaseMemoryLimitKernelBaseMemoryLimitmemory limit for continuous usageMORE INFORMATION† KernelBaseMemoryLimit is a configuration setting that sets the limit in bytes for the base amount ofmemory that a Mathematica kernel can use. The base amount of memory is measured as the memoryusage at the start or end of a computation, and is not influenced by temporary usages of memoryinside of a calculation. When the memory limit is exceeded the kernel is restarted. To limit temporaryusages you should use KernelPeakMemoryLimit.EXAMPLESBasic Examples (1)A sample setting is shown below. This sets the limit to 40000000 bytes.40000000TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 201KernelConnectLimitKernelConnectLimitthe length of time for the kernel to connectMORE INFORMATION† KernelConnectLimit is a configuration setting that sets the maximum amount of time that the serverwaits for the kernel to connect. It is unlikely that you would need to change this. If the kernel has notconnected within this time an error is found, this problem needs to be resolved since the servercannot operate if the kernel cannot be launched.EXAMPLESBasic Examples (1)A sample setting is shown below, which waits for a maximum of 100000ms.100000TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


202 webMathematica User GuideKernelDestroyCodeKernelDestroyCodeMathematica code to run during kernel shutdownMORE INFORMATION† KernelDestroyCode is a configuration setting giving Mathematica code that runs when a kernel isbeing shutdown by the server. Note that this code is not run if the kernel is shut down due to anexception, such as a timeout or a memory limit.EXAMPLESBasic Examples (1)A sample setting is shown below.MyApplication`ShutdownConnection[]TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 203KernelExecutableKernelExecutablethe path to the kernel executableMORE INFORMATION† KernelExecutable is a configuration setting that sets the path the kernel executable. If Mathematicais installed in a standard location for your platform there is no need to set this. However, if you haveinstalled Mathematica for your web server in a non-standard location, then you will need to setKernelExecutable.EXAMPLESBasic Examples (1)A sample setting is shown below.D:\Applications\<strong>Wolfram</strong>\Mathematica\7.0\MathKernel.exeTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


204 webMathematica User GuideKernelInitializeCodeKernelInitializeCodeMathematica code to run during kernel startupMORE INFORMATION† KernelInitializeCode is a configuration setting giving Mathematica code that runs when a kernel islaunched by the server. It can be used to load common packages and tools that are used by theserver.EXAMPLESBasic Examples (1)A sample setting is shown below. This loads an application and then uses a function from the application.Notice how it has to use the fully qualified name for the function.Needs[ "MyApplication`"];MyApplication`LaunchConnection[];TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 205KernelLaunchFlagsKernelLaunchFlagsflags to use when the kernel is launchedMORE INFORMATION† KernelLaunchFlags is a configuration setting that gives any special flags that you want to set on thecommand line for the launch of the Mathematica kernel. Typically this is not needed, but one exampleis that you might want to set the password file that is used.EXAMPLESBasic Examples (1)A sample setting is shown below.-pwfile /home/users/webserver/pwfileTUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


206 webMathematica User GuideKernelNumberKernelNumberthe number of kernels in a poolMORE INFORMATION† KernelNumber is a configuration setting that sets the number of kernels that are used by a kernelpool. A kernel pool is a group of Mathematica kernels that can be specially configured and is documentedin the Advanced Topics: Multiple Kernel Pools section.EXAMPLESBasic Examples (1)If you increase the number of kernels in a pool, then you would use this setting. A sample setting is shownwhich sets the number to 4.4TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide† Kernel Pools in webMathematica User Guide


webMathematica User Guide 207KernelPeakMemoryLimitKernelPeakMemoryLimitmemory limit for temporary usageMORE INFORMATION† KernelPeakMemoryLimit is a configuration setting that sets the limit in bytes for the peak amount ofmemory that a Mathematica kernel can use. The peak amount of memory means any temporaryusage of memory that might happen during a calculation. When the memory limit is exceeded thekernel is restarted. To limit the base amount of memory you should use KernelBaseMemoryLimit.EXAMPLESBasic Examples (1)A sample setting is shown below. This sets the limit to 60000000 bytes.60000000TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


208 webMathematica User GuideKernelPoolKernelPoolconfiguration section for a particular kernel poolMORE INFORMATION† KernelPool specifies the configuration to use for a new kernel pool. A kernel pool is a group ofMathematica kernels that can be specially configured and is documented in the Advanced Topics:Multiple Kernel Pools section.EXAMPLESBasic Examples (1)A sample setting for a kernel pool is shown below. A kernel pool needs to specify at least the name of thepool and the pattern for URLs that will use this pool.General/*2TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide† Kernel Pools in webMathematica User Guide


webMathematica User Guide 209KernelPoolNameKernelPoolNamethe name of a kernel poolMORE INFORMATION† KernelPoolName is a configuration setting that specifies the name of a kernel pool. A kernel pool is agroup of Mathematica kernels that can be specially configured and is documented in the AdvancedTopics: Multiple Kernel Pools section.EXAMPLESBasic Examples (1)A sample setting for a kernel pool is shown below. This shows how the name is set.General/*2TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide† Kernel Pools in webMathematica User Guide


210 webMathematica User GuideKernelReleaseCodeKernelReleaseCodeMathematica code to run when a kernel is releasedMORE INFORMATION† KernelReleaseCode is a configuration setting giving Mathematica code that runs when a kernel isreleased by the server at the end of a computation. Note that this code is not run if the kernel is shutdown due to an exception, such as a timeout or a memory limit.EXAMPLESBasic Examples (1)A sample setting is shown below.MyApplication`TeardownPage[]TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


webMathematica User Guide 211KernelTimeLimitKernelTimeLimitthe maximum time for each computationMORE INFORMATION† KernelTimeLimit is a configuration setting that sets the maximum amount of time for which a kernelcan run a computation. This is an important feature that maintains the reliability of the server.EXAMPLESBasic Examples (1)A sample setting is shown below, which allows any calculation that takes less than 100000ms.100000TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide


212 webMathematica User GuideSecurityConfigurationFileSecurityConfigurationFilethe name of the security configuration fileMORE INFORMATION† SecurityConfigurationFile is a configuration setting that specifies the location of the securityconfiguration file for a kernel pool.† The setting is relative to the base of the web application.EXAMPLESBasic Examples (1)A sample setting is shown below. This sets the security file to be the file ComputeSiteSecurity.m found inthe WEB-INF directory./WEB-INF/ComputeSiteSecurity.mA sample contents for the security file is shown below. This is a very conservative security model, whichallows all symbols in Global` context as well as a small number of system symbols.{"AllowedContexts" -> {"Global`"},"AllowedSymbols" ->HoldComplete[ Plus, Times, Power, HoldComplete]}


webMathematica User Guide 213TUTORIALS† webMathematica User Guide† Security in webMathematica User Guide† Configuration in webMathematica User Guide† Kernel Pools in webMathematica User Guide


214 webMathematica User GuideURLPatternURLPatternthe pattern to map URLs to a kernel poolMORE INFORMATIONEXAMPLESBasic Examples (1)A sample setting for a kernel pool is shown below. This shows that the URLPattern will use this pool forany URL that has Compute after the web application base. For example, the URL http://webMathematica/Compute/special/tool.jsp will use this kernel pool.General/Compute2TUTORIALS† webMathematica User Guide† Configuration in webMathematica User Guide† Kernel Pools in webMathematica User Guide


Functions


webMathematica User Guide 217HTMLCheckboxHTMLCheckbox@nameDreturns an HTML input tag of type checkboxHTMLSelect@name, True FalseDchecks/unchecks the checkboxMORE INFORMATION† The HTML functions are contained in a package, MSP`HTML`, which is loaded as part of the webMathematicalayout.† The function HTMLCheckbox provides a useful way to generate an input checkbox tag with webMathematica.† HTMLCheckbox takes the name to use when the checkbox is submitted as an argument.† If a second argument is given, it is used to determine whether or not the box is checked.EXAMPLESBasic Examples (1)You can demonstrate how the function works by loading the package.In[1]:=Needs@ "MSP`HTML`"DIn[2]:=HTMLCheckbox@ boxnameDOut[2]= In[3]:=If a second argument is given, it is used to determine whether or not the box is checked. In the followingexample the checkbox is checked.HTMLCheckBox@boxname, 10 > 5DOut[3]= SEE ALSOHTMLFormat ‰ HTMLTableForm ‰ HTMLSelect


218 webMathematica User GuideTUTORIALS† webMathematica User Guide† HTML Formatting in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 219HTMLFormatHTMLFormat@exprDformats an expression into HTML such that numbers and powers use superscript notationMORE INFORMATION† The HTML functions are contained in a package, MSP`HTML`, which is loaded as part of the webMathematicalayout.† HTMLFormat provides some useful formatting functions into HTML. It is suitable for formatting smallexpressions such as numbers as shown below.† HTMLFormat is less suitable for formatting large expressions, since everything will come out inInputForm.† For larger expressions it is recommended to use one of the versions of the formatting function MSPForÖmat to gain a result in an image format or MathML.EXAMPLESBasic Examples (1)You can demonstrate how the function works by loading the package.In[1]:=Needs@ "MSP`HTML`"DIn[2]:=HTMLFormat@ x^2DOut[2]= x2In[3]:=HTMLFormat@10.!DOut[3]= 3.6288&Ò160;106It is less suitable for formatting large expressions, since everything will come out in InputForm.In[4]:=Out[4]=Nest@ 1 ê H1 - ÒL &, x, 5D11 -111-11-11-1-x


220 webMathematica User GuideIn[5]:=HTMLFormat@% DOut[5]= 1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;1&Ò160;-&Ò160;x-1-1-1-1-1SEE ALSOHTMLTableForm ‰ HTMLSelect ‰ HTMLCheckboxTUTORIALS† webMathematica User Guide† HTML Formatting in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 221HTMLSelectHTMLSelect@options, nameDreturns an HTML select tag with the given set of optionsHTMLSelect@options, name, defaultDsets the defaultMORE INFORMATION† The HTML functions are contained in a package, MSP`HTML`, which is loaded as part of the webMathematicalayout.† The function HTMLSelect provides a useful way to generate select tags with webMathematica.† It is also possible to set selections by using the option SelectedOptions.† HTMLTableForm takes the following options.SelectedValuesSelectedOptionsOptionAttributesinitial selection based on valuesinitial selection based on optionsattributes to apply to the HTML select tagEXAMPLESBasic Examples (1)You can demonstrate how the function works by loading the package.In[1]:=Needs@ "MSP`HTML`"DIn[2]:=The function HTMLSelect provides a useful way to generate select tags with webMathematica. It takes a listof the different options and the name to be used when the selection is submitted. Its operation is shownbelow.HTMLSelect@ 8"a", "b", "c"


222 webMathematica User GuideIn[3]:=It is also possible to set selections by using the option SelectedOptions. In this example, the optionlabeled "a" will be selected.HTMLSelect@ 8"a", "b", "c"


webMathematica User Guide 223TUTORIALS† webMathematica User Guide† HTML Formatting in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


224 webMathematica User GuideHTMLTableFormHTMLTableForm@data, optsDformats data into an HTML tableHTMLTableForm@data, fun, optsDuses the function fun to format each elementMORE INFORMATION† The HTML functions are contained in a package, MSP`HTML`, which is loaded as part of the webMathematicalayout.† If you wish to use it in Mathematica outside of webMathematica, you will need to install and load itseparately.† The default formatting function for HTMLTableForm is HTMLFormat.† Any string arguments to HTMLTableForm are assumed to be already formatted and no more formattingis applied. This allows it to take the output of other MSP functions such as MSPShow orHTMLFormat.† HTMLTableForm takes the following options.TableHeadingsTableAttributesheadings for the tableattributes to apply to the HTML tableEXAMPLESBasic Examples (1)You can demonstrate how the function works by loading the package.In[1]:=Needs@"MSP`HTML`"D


webMathematica User Guide 225In[2]:=The function HTMLTableForm takes an input and formats it into an HTML table.HTMLTableForm@ 88a, b, c


226 webMathematica User Guidesin&Ò8289;HxLxSEE ALSOHTMLFormat ‰ HTMLSelect ‰ HTMLCheckBoxTUTORIALS† webMathematica User Guide† HTML Formatting in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 227MSPBlockMSPBlock@8var i , …


228 webMathematica User GuideHere the variable $$var is assigned to the value "5+7"; note that the value is a string.In[3]:= $$var = "5+7";When MSPBlock evaluates, all occurrences of $$var are replaced by its interpreted value.In[4]:= MSPBlock@ 8$$var


webMathematica User Guide 229TUTORIALS† webMathematica User Guide† MSP Functions: Expand.jsp in webMathematica User Guide† Security in webMathematica User Guide† Input Variables in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


230 webMathematica User GuideMSPExceptionMSPException@typeDan exception that can be thrown by webMathematica page commandsMORE INFORMATION† A number of MSP commands throw an MSPException when some error situation occurs. These arecaught by the page processing code, but it would be permissible for a page author to catch them andprocess them in some intermediate step.† The following exceptions can be thrown by MSPBlock.MSPException@" ParseError "DMSPException@" SecurityError "DMSPException@" ValueError "DMSPException@" VariableError "DMSPException@" NoValueError "DMSPException@" VersionError "Dif the value cannot be interpreted by Mathematicaif the value does not pass the security testif the value is not a string, this indicates a programmatic errorby the page authorif the variable is not a Mathematica symbol, this indicates aprogrammatic error by the page authorif a variable has no valueif a version mismatch problem is foundEXAMPLESBasic Examples (1)In[1]:=Needs@"MSP`"D;If a variable cannot be interpreted, a ParseError exception is thrown. Since the values may be enteredfrom the client, this does not indicate an author error.In[2]:=Catch@ MSPToExpression@"f@"D, _MSPException, ListDToExpression::sntx : Syntax error in or before "f@".Out[2]= 88f@, f@


webMathematica User Guide 231In[4]:=If a variable that is not a Mathematica symbol is encountered, a VariableError exception is thrown. Thisusually indicates an author error.Catch@ MSPValue@x@1DD, _MSPException, ListDOut[4]= 8x@1D, MSPException@VariableErrorD


232 webMathematica User GuideMSPFormatMSPFormat@exprDformat expr in the format style $MSPFormatTypeMSPFormat@expr, fmtDformat expr in the format style fmtMSPFormat@expr, fmt, typeDformat expr in the format style fmt, using type as the content typeMORE INFORMATION† MSPFormat is the key function for formatting results from Mathematica.† The formatted result can appear in the different format types that Mathematica provides for outputsuch as OutputForm, InputForm, StandardForm, TraditionalForm, and MathMLForm.† The result can be returned as HTML, an image format, or as MathML.† The second argument of MSPFormat is a symbol that selects the Mathematica format type, and thethird argument is a string that sets the actual content type of the result.† 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.† An alternative way to format expressions into HTML is provided by the HTML functions.EXAMPLESBasic Examples (1)You can simulate how the functions work by loading the package.


webMathematica User Guide 233The following demonstrates formatting output into HTML using the format OutputForm; it is formatted to apage width set by the variable $PageWidth.In[1]:=Needs@"MSP`"DIn[2]:=MSPFormat@ x + y^2, OutputFormDOut[2]= &Ò160;&Ò160;&Ò160;&Ò160;&Ò160;2x&Ò160;+&Ò160;yAn alternative to formatting into text is to format into an image; this is done for StandardForm and TradiÖtionalForm, creating an image file and saving it on the server. An img tag, which can be used to retrievethe image, is then returned as the result.In[3]:=Out[3]=MSPFormat@ x + y, StandardFormDBy default, the images are in GIF format. This can be changed by specifying the format as a third argument.Here the image is stored in JPEG format.In[4]:=Out[4]=MSPFormat@ x + y, StandardForm, "JPEG"DIt is also possible, though rather strange, to get a text-based format type (for example OutputForm)rendered into an image.In[5]:=Out[5]=MSPFormat@ x + y, OutputForm, "GIF"DThe width that is used for typeset images is set by the variable $TypesetImageWidth.An alternative way to generate images is with the function MSPExportImage. For information on imagegeneration, see the section Displaying Mathematics and Graphics.


234 webMathematica User GuideIf the format is set to MathMLForm, the system will format the expression into MathML.In[6]:=Needs@"MSP`"DIn[7]:=MSPFormat@ Sin@xD^2, MathMLFormDOut[7]= sin2&af;HxLIn[8]:=In addition, you can specify a content type of RawMathML. This can be useful to get the MathML for theStandardForm rendering of an expression. This output is raw in the sense that it does not use any referenceto a plug-in, applet, or special browser that would be necessary to activate the MathML.MSPFormat@ Sin@xD^2, StandardForm, "RawMathML"DOut[8]= Sin&af;@xD2More information on working with MathML is provided in the section MathML.TUTORIALS† webMathematica User Guide† Formatting in webMathematica User Guide† Displaying Mathematics and Graphics in webMathematica User Guide† HTML Formatting in webMathematica User Guide† MathML in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 235MSPGetMessagesMSPGetMessages@Dreturn all messages generated by evaluations in the current kernelMORE INFORMATION† MSPGetMessages gives a way to obtain any messages that have been generated by evaluations in thecurrent kernel. It returns a list of strings, where each string contains the formatted contents of themessage.EXAMPLESBasic Examples (1)This function cannot be demonstrated in a normal evaluation; it must be part of a running server. Theexample Messages.jsp demonstrates the use of MSPGetMessages.SEE ALSOMSPGetPrintOutputTUTORIALS† webMathematica User Guide† Getting Messages: Messages.jsp in webMathematica User Guide† Logging in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


236 webMathematica User GuideMSPGetPrintOutputMSPGetPrintOutput@Dreturn the text of all print statements evaluated by the current kernelMORE INFORMATION† MSPGetPrintOutput gives a way to obtain the output of all print statements that have been processedby the current kernel. It returns a list of strings, where each string contains the formatted contents ofthe message.EXAMPLESBasic Examples (1)This function cannot be demonstrated in a normal evaluation; it must be part of a running server. Theexample Messages.jsp demonstrates the use of MSPGetMessages.SEE ALSOMSPGetMessagesTUTORIALS† webMathematica User Guide† Getting Messages: Messages.jsp in webMathematica User Guide† Logging in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


238 webMathematica User GuideIn[1]:=In[2]:=Needs@"MSP`"DMSPGetUploadFile@DOut[2]= 9FileName Ø 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.In[3]:= "FileName" ê. %Out[3]= MSPStore2349287_ 0 _ 1SEE ALSOMSPGetUploadFileListTUTORIALS† webMathematica User Guide† Uploading Data: Upload.jsp in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 239MSPGetUploadFileListMSPGetUploadFileList@Dreceive information on several HTTP upload filesMORE INFORMATION† This provides a useful utility function for uploading files from the client to the server using multipart/form-data submissions.† The contents of files are saved in new files on the server.† Files on the server will eventually be cleared in a way similar to the clearing of image and othertemporary files.† The result of MSPGetUploadFileList is a list of lists of rules that show filenames on the server,original filenames on the client, and content types." FileName " the name of the file on the server" OriginalFileName " the original name of the file before upload" ContentType " the content type of the fileNote that parameters that are present in the HTTP headers become available as $$ variables after the useof 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.This is set by the configuration parameter FileUploadSizeLimit.† The following exception can be thrown by MSPGetUploadFile.MSPException@" FileUploadError "Dif an error is encountered while retrieving the upload fileEXAMPLESBasic Examples (1)The function cannot be demonstrated since it must really be part of an actual HTTP transaction with appropriateinformation sent from the client. This example just simulates the way that the function can be used withMathematica programming.


240 webMathematica User GuideIn[1]:=In[2]:=Needs@"MSP`"DMSPGetUploadFileList@DOut[2]= 99FileName Ø MSPStore2349287_0_1, OriginalFileName -> C:\last1.dat, ContentType -> textêplain=,9FileName Ø MSPStore2349287_0_2, OriginalFileName -> C:\last2.dat, ContentType -> textêplain==SEE ALSOMSPGetUploadFileTUTORIALS† webMathematica User Guide† Uploading Data: Upload.jsp in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 241MSPLive3DMSPLive3D@ graphicsDinclude a LiveGraphics3D graphical applet in an HTML pageMORE INFORMATION† MSPLive3D is a convenient way to work with the LiveGraphics3D graphics applet.† The applet displays Mathematica three-dimensional graphics and provides support for features suchas interactive rotation and resizing.EXAMPLESBasic Examples (1)The following example embeds the LiveGraphics3D applet in a web page, passing a simple three-dimensionalgraphics object as input.MSPLive3D[ Graphics3D[ Line[ {{0, 0, 0}, {1, 1, 1}}]]]TUTORIALS† webMathematica User Guide† Live 3D Plotting: Plot3DLive.jsp in webMathematica User Guide† LiveGraphics3D in webMathematica User Guide† Appendix: LiveGraphics3D in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


242 webMathematica User GuideMSPManipulateMSPManipulate@expr, 8u, u min , u max


webMathematica User Guide 243† MSPManipulate takes the following options.ContainerStyleControlPlacementControlTypeFormatTypeOutputSizeformatting for the web page containerplacement of controlstype of controls to usethe type of formatting to usethe size in pixels for the entire interactive control† ControlType and ControlPlacement Ø pos options can be given separately for each control.† The option setting ControlPlacement Ø pos specifies that controls should be placed at position posrelative to expr. Possible settings forpos are Bottom, Left, Right, and Top.† The option setting ContainerStyle Ø 8styles…< gives styles for the web container. Possible stylesettings are:"BorderColor" Black color to draw the border"BorderThickness" 1 thickness for the border"BorderStyle" solid style to draw the border"PaddingTop" 10 padding on the top"PaddingBottom" 10 padding on the bottom"PaddingLeft" 10 padding on the left"PaddingRight" 10 padding on the right† The option setting ControlsRendering Ø type specifies the style used to render sliders. The defaultsetting forpos is "Generic" which gives standard Flash sliders. Alternatively, it can be set to"FrontEnd.Windows" or "FrontEnd.Macintosh" which will display with the sliders similar to thoseused by the notebook front end on Windows or Macintosh respectively. A setting of "FrontEnd" willdisplay with Macintosh sliders in browsers on Macintosh platforms otherwise it will use the front endWindows style.EXAMPLESBasic Examples (1)The following creates an interactive plot controlled by a slider and a checkbox.MSPManipulate[Plot[ Cos[var+x], {x,0,2Pi}, Frame -> frame],{var, 0,20}, {frame, {True,False}}]


244 webMathematica User GuideYou can change the default style of some of the controls using the ControlType option. The followingexample uses a PopupMenu to represent the choices; without the option a SetterBar would be used.MSPManipulate[ Plot[ fun[x],{x,0,20}], {fun, {Sin, Cos}},ControlType -> PopupMenu]MSPManipulate always formats its argument into an image; by default it uses StandardForm. However, itcan be changed to format into TraditionalForm; which is shown in the following.MSPManipulate[ Integrate[ 1/(1^-num),x], {num, 1,20,1},FormatType -> TraditionalForm]The size of the finished interactive web output can be controlled by the OutputSize option. This has adefault that tries to keep track of the number of controls. If there is not enough space then scrollbars will beadded automatically. In the following example a size of 800 by 800 pixels is used.MSPManipulate[ Integrate[ 1/(1^-num),x], {num, 1,20,1},OutputSize -> {800,800}]Scope (3)Style (1)The variable can be displayed in different styles using a Style specification.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}],{{var,0,Style[var, FontSize ->15, FontColor -> Red]}, 0,2Pi}]Static Labels (1)You can include static expressions that do not render to controls in the list. These are useful for labeling.MSPManipulate[ Plot[Sin[ x+phase],{x,0,2Pi}],"Control Parameter for Phase",{phase, 0,2Pi}]


webMathematica User Guide 245The label can be displayed in different styles using a Style specification.MSPManipulate[ Plot[Sin[fact x+phase],{x,0,2Pi}],Style[ "Control Parameter for Phase", FontFamily ->"Times"],{phase, 0,2Pi},Style[ "Control Parameter for Factor", FontFamily ->"Times"],{fact, 1,20}]Control Label Formatting (1)If you want to use typesetting or extended font characters in the label for the control you can use StandardÖForm or TraditionalForm as a wrapper.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}],{{var,0,TraditionalForm[Subscript[F,1]]}, 0,2Pi}]Options (4)ContainerStyle (1)The ContainerStyle option can be used to change the border style. Here no border is shown.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}], {var, 0,2Pi},ContainerStyle -> {"BorderStyle" -> "none"}]ControlPlacement (1)The ControlPlacement option can be used to change the location of the controls.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}],{var, 0,2Pi},ControlPlacement -> Left]


246 webMathematica User GuideYou can give settings to individual controls.MSPManipulate[ Plot[Sin[fact x+var],{x,0,2Pi}],{var, 0,2Pi,ControlPlacement -> Left},{fact, 1,20,ControlPlacement -> Right}]ControlsRendering (1)The ControlsRendering option can be used to change the appearance of sliders. The following gives theappearance of a Macintosh type slider.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}],{var, 0,2Pi},ControlsRendering -> "FrontEnd.Macintosh"]The following use the front end style for Macintosh in browsers on Macintosh platforms. Otherwise it usesthe front end style for Windows.MSPManipulate[ Plot[Sin[x+var],{x,0,2Pi}],{var, 0,2Pi},ControlsRendering -> "FrontEnd"]FieldSize (1)The FieldSize option can be used to change the size of input fields. The following uses a longer input field.MSPManipulate[ Plot[fun[x],{x,0,2Pi}],{{fun,Sin}, FieldSize -> 30}]SEE ALSOMSPManipulateHeader ‰ Manipulate


webMathematica User Guide 247TUTORIALS† webMathematica User Guide† Interactive Web: SliderPlot.jsp in webMathematica User Guide† Interactive Web Tools in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


248 webMathematica User GuideMSPManipulateHeaderMSPManipulateHeader@ $$updateArgs, $$manipulateNumberDinitializes the webMathematica interactive toolsMORE INFORMATION† MSPManipulateHeader initializes the webMathematica interactive tools.† You must load the MSPManipulate` package to use the webMathematica interactive tools.EXAMPLESBasic Examples (1)This intializes the interactive web tools.MSPManipulateHeader[$$updateArgs, $$manipulateNumber]SEE ALSOMSPManipulate ‰ ManipulateTUTORIALS† webMathematica User Guide† Interactive Web: SliderPlot.jsp in webMathematica User Guide† Interactive Web Tools in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 249MSPPageDirectoryMSPPageDirectory@Dreturns the full path of the directory in which the current script is being processedMORE INFORMATION† MSPPageDirectory can be used to load data files that live in the same directory as the current script.† It should be noted that locating files in the script directory may mean that they are visible to an HTTPrequest.EXAMPLESBasic Examples (1)You can simulate how the function works by loading the package.In[1]:=In[2]:=Needs@"MSP`"DMSPPageDirectory@DOut[2]= C:\Program Files\jakarta-tomcat\webapps\webMathematica\ExamplesTUTORIALS† webMathematica User Guide† File I/O in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


250 webMathematica User GuideMSPPageOptionsMSPPageOptions@optsDset global options about the current pageMORE INFORMATION† The following options can be set by MSPPageOptions.ContentTypesets the content type of the returned pageMinimumVersion requires that the page runs in particular versions of webMathe -matica† The following exceptions can be thrown by MSPPageOptions.MSPException@" VersionError "Dif an older version of webMathematica is requestedThe ContentType option provides similar functionality to MSPReturn. It is different in that it returns theentire page, whereas MSPReturn returns only its first argument.EXAMPLESBasic Examples (1)In this example the ContentType option is set to return MathML. If the browser is configured correctly, itwill launch an appropriate MathML helper application.MSPPageOptions[ ContentType -> "text/mathml"]MSPFormat[ Integrate[ 1/(1-x^3),x], StandardForm, RawMathML]


252 webMathematica User GuideMSPReturnMSPReturn@result, contentDreturn the result with the specified MIME content typeMSPReturn@result, content, filenameDset the filename associated with the responseMORE INFORMATION† MSPReturn allows a page to return something that is not an HTML result.† The three-argument form of MSPReturn is useful when you wish to set the filename associated withthe response.EXAMPLESBasic Examples (1)This example returns a Mathematica notebook directly to the client.MSPReturn[ Notebook[ Cell[ "Hello", "Title"]],"application/mathematica"]This example returns an XML fragment. These techniques can be useful for making informal web servicesfor working with technologies such as Flash or JavaScript that have convenient tools for processing XML.MSPReturn[ ExportString[XMLElement["arg1", {}, {"5 6"}], "XML"],"text/xml"]


webMathematica User Guide 253The three-argument form of MSPReturn is useful when you wish to set the filename associated with theresponse.MSPReturn[ Notebook[ Cell[ "Hello", "Title"]],"application/mathematica", "mynotebook.nb"]In this case the client might try to use a filename of mynotebook.nb. It should also be noted that for someclients, such as Internet Explorer, setting the filename header can cause the display of two Open or Savedialog boxes.TUTORIALS† webMathematica User Guide† Returning General Content in webMathematica User Guide† XML Applications in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


254 webMathematica User GuideMSPRootDirectoryMSPRootDirectory@Dreturn the full path of the root directory of webMathematicaMORE INFORMATION† MSPRootDirectory returns the full path of the root directory of the webMathematica web application.EXAMPLESBasic Examples (1)You can simulate how the function works by loading the package.In[1]:=In[2]:=Needs@"MSP`"DMSPRootDirectory@DOut[2]= C:\Program Files\jakarta-tomcat\webapps\webMathematicaTUTORIALS† webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


webMathematica User Guide 255MSPSessionVariableMSPSessionVariable@ symDdeclare the variable sym to be a session variable, with the initial value NullMSPSessionVariable@ sym, valueDset the initial value of the session variable sym to be valueMORE INFORMATION† This is a scoping construct for declaring a variable to be a session variable.† The values of a session variable will be stored in a session managed by the servlet container.† Sessions are a standard feature of modern web servers/browsers and are used to store information ona server.† A session value will live from one call of the server to another.TUTORIALS† webMathematica User Guide† Session Storage of Data: Session.jsp in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


256 webMathematica User GuideMSPSetDefaultMSPSetDefault@ var, valueDset the variable var to value if it does not have a valueMORE INFORMATION† This is a utility function for setting the default values of variables.† The following exceptions can be thrown by MSPSetDefault.MSPException@" ParseError "DMSPException@" SecurityError "DMSPException@" ValueError "DMSPException@" VariableError "Dif the value cannot be interpreted by Mathematicaif the value does not pass the security testif the value is not a string, this indicates a programmatic errorby the page authorif the variable is not a Mathematica symbol, this indicates aprogrammatic error by the page authorEXAMPLESBasic Examples (1)You can simulate how the function works by loading the package.In[1]:=Needs@"MSP`"DHere $$var has a value, so its value is not modified.In[2]:= $$var = "5.6"; MSPSetDefault@ $$var, "foo"D; $$varOut[2]= 5.6If $$var has no value, MSPSetDefault will set it.In[3]:= Clear@$$varD; MSPSetDefault@ $$var, "foo"D; $$varOut[3]= foo


webMathematica User Guide 257SEE ALSOMSPValueTUTORIALS† webMathematica User Guide† Input Variables in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


258 webMathematica User GuideMSPShowMSPShow@ graphicsDinclude a graphical image in an HTML pageMORE INFORMATION† MSPShow is the main way to include graphical results from Mathematica for inclusion in an HTML page.† The argument to MSPShow can be something that evaluates to a graphics object, such as a Plotcommand.EXAMPLESBasic Examples (1)You can simulate how the function works by loading the package.In[1]:=Needs@"MSP`"DThe argument to MSPShow can be something that evaluates to a graphics object, such as a Plot command.In[2]:=Out[2]=In[3]:=Out[3]=MSPShow@ Plot@ Sin@xD, 8x, 0, 2


webMathematica User Guide 259MSPToExpressionMSPToExpression@varDinterprets the variable varMSPToExpression@var, fmtDuses the format fmt to interpret varMSPToExpression@ var, fmt, headDreturns the result wrapped in headMORE INFORMATION† MSPToExpression is the webMathematica version of ToExpression; it provides the same functionalityfor turning strings into Mathematica input, but it also carries out a security check.† You should always use MSPToExpression rather than ToExpression in your code because it providesadditional security.† The following exceptions can be thrown by MSPToExpression.MSPException@" ParseError "DMSPException@" SecurityError "DMSPException@" ValueError "Dif the value cannot be interpreted by Mathematicaif the value does not pass the security testif the value is not a string, this indicates a programmatic errorby the page authorMSPException@" NoValueError "D if the variable does not have a value, this indicates a program -matic error by the page authorMSPException@" VariableError "Dif the variable is not a Mathematica symbol, this indicates aprogrammatic error by the page authorEXAMPLESBasic Examples (1)You can simulate how the functions work by loading the package and setting the security content.In[1]:=In[2]:=Needs@"MSP`"DSetSecurity@D;


260 webMathematica User GuideHere the variable $$var is assigned to the value "5+7"; note that the value is a string.In[3]:= $$var = "5+7";When MSPToExpression evaluates, the parsed value of $$var is returned.In[4]:=MSPToExpression@ $$varDOut[4]= 12If a variable has no value, an MSPException is thrown.In[5]:=Clear@ $$varD; MSPToExpression@ $$varDThrow::nocatch :Uncaught Throw@$$var, MSPException@NoValueErrorDD returned to top level.Out[5]= Hold@Throw@$$var, MSPException@NoValueErrorDDDLike ToExpression, MSPToExpression can take a format type for interpretation.In[6]:=$$var = "sinHxL"; MSPToExpression@ $$var, TraditionalFormDOut[6]= Sin@xDIf the input value cannot be interpreted, an MSPException is thrown.In[7]:=$$var = "Sin@"; Catch@ MSPToExpression@ $$varD, _MSPException, ListDOut[7]= 88$$var, Sin@


webMathematica User Guide 261MSPToExpression can be used on strings that are computed from input.In[11]:= $$e = "a,b,c"; MSPToExpression@"8" $$e "


262 webMathematica User GuideMSPURLStoreMSPURLStore@data, typeDstore a string of data of the specified type and return a URL referenceMSPURLStore@data, type, filenameDstore a string of data of the specified type and return a URL reference that contains asuggested filenameMORE INFORMATION† MSPURLStore stores a string of formatted data in the MSP servlet and returns a URL that can be usedto retrieve the data.† MSPURLStore is an extension of the mechanism for storing images.† MSPURLStore can be used to hold input for some plug-in or applet in the client or it could be formattedinto an img tag.EXAMPLESBasic Examples (1)You can simulate how the function works by loading the package.In[1]:=In[2]:=Needs@"MSP`"Dm = DisplayString@Graphics@Line@ 880, 0


webMathematica User Guide 263In[4]:=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. Thename is just placed in the URL.MSPURLStore@m, "imageêjpeg", "file.gif"DOut[4]= êwebMathematicaêMSPêfile.gif?MSPStoreID=FileNameBase_846174849&MSPStoreType=imageêjpegTUTORIALS† webMathematica User Guide† Returning General Content in webMathematica User Guide† MSP Functions Returning Images in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


264 webMathematica User GuideMSPValueMSPValue@varDreturns the value of var; it returns a null string if var has no valueMSPValue@var, def Dreturns the value of var; it returns def if var has no valueMORE INFORMATION† MSPValue is a utility function that is useful for extracting the value of variables.† The following exceptions can be thrown by MSPValue.MSPException@" ValueError "DMSPException@" VariableError "Dif the value is not a string, this indicates a programmatic errorby the page authorif the variable is not a Mathematica symbol, this indicates aprogrammatic error by the page authorEXAMPLESBasic Examples (1)You can simulate how the functions work by loading the package.The value of the variable $$expr is returned.In[1]:= $$expr = 56; MSPValue@ $$exprDOut[1]= 56If $$expr has no value, then a null string is returned.In[2]:=Clear@$$exprD; MSPValue@ $$exprDOut[2]=


webMathematica User Guide 265Here a default value is returned.In[3]:= Clear@$$exprD; MSPValue@ $$expr, "x+y"DOut[3]= x+ySEE ALSOMSPValueQTUTORIALS† webMathematica User Guide† Graphics: Plot.jsp in User Guide† Input Variables in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


266 webMathematica User GuideMSPValueQMSPValueQ@var 1 , var 2 , …Dreturns True if all the variables have valuesMORE INFORMATION† MSPValueQ is a utility function that tests whether variables have values.EXAMPLESBasic Examples (1)You can simulate how the functions work by loading the package.In[1]:=Needs@"MSP`"DThe variable $$expr has a value, so the result is True.In[2]:= $$expr = 56; MSPValueQ@ $$exprDOut[2]= TrueNow $$expr has no value, so the result is False.In[3]:= Clear@$$exprD; MSPValueQ@ $$exprDOut[3]= FalseAll the variables must have values for MSPValueQ to return True.In[4]:= $$expr = 56; Clear@ $$varD; MSPValueQ@ $$expr, $$varDOut[4]= FalseSEE ALSOMSPValue


webMathematica User Guide 267TUTORIALS† webMathematica User Guide† Typeset Images: Integrate.jsp in webMathematica User Guide† Input Variables in webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide


Guides


webMathematica User Guide 271ConfigurationwebMathematica has a number of ways it can be configured so that its operation can be customized.These are some of the settings that can be changed.KernelPoolName ~ the name of a kernel poolKernelNumber ~ the number of kernels in a poolKernelExecutable ~ the path to the kernel executable for a poolKernelTimeLimit ~ the maximum time for each computationKernelInitializeCode ~ Mathematica code to run during startupKernelDestroyCode ~ Mathematica code to run during shutdownKernelAcquireCode ~ Mathematica code to run when a kernel is allocatedKernelReleaseCode ~ Mathematica code to run when a kernel is releasedTUTORIALS† webMathematica User Guide† Configuration in webMathematica User GuideRELATED LINKS† webMathematica product page


272 webMathematica User GuideFormattingwebMathematica provides a number of important ways to format output for finished web pages. Thisincludes formatting into text, HTML, GIF, XML, MathML, and other formats.MSPFormat ~ format results into text or image formatsMSPShow ~ format graphics by creating an imageMSPLive3D ~ format 3D graphics to allow interactive viewingMSPGetMessages ~ display any messagesMSPGetPrintOutput ~ display any print outputHTMLTableForm ~ format into an HTML tableHTMLSelect ~ format into an HTML selectTUTORIALS† webMathematica User GuideRELATED LINKS† webMathematica product page


webMathematica User Guide 273webMathematica TagswebMathematica provides a number of tags for embedding Mathematica results into a web page.evaluate ~ halt processing of the current page and return a different resultget ~ halt processing of the current page and return a different resultset ~ halt processing of the current page and return a different resultevaluateQueued ~ halt processing of the current page and return a different resultTUTORIALS† webMathematica User GuideRELATED LINKS† webMathematica product page


274 webMathematica User GuideProcessing InputHTTP input variables are a key way to control the operation of a dynamic website. These are typicallyembedded in your input page with tags. webMathematica provides a number of functions forworking with and processing input. This needs to be done carefully to avoid any security problems.MSPBlock ~ secure scoping construct for HTTP inputMSPToExpression ~ interpret input in a secure wayMSPValue ~ return the value of an HTTP input variableMSPValueQ ~ test if an HTTP input variable as a valueTUTORIALS† webMathematica User GuideRELATED LINKS† webMathematica product page


webMathematica User Guide 275Web InteractionwebMathematica provides a number of key functions for working with web features such as HTTP sessionsand file upload.MSPReturn ~ halt processing of the current page and return a different resultMSPSessionVariable ~ scope a variable to an HTTP sessionMSPGetUploadFile ~ get the name of a file uploaded with the HTTP requestMSPURLStore ~ store a result on the server that can be retrieved with a URLTUTORIALS† webMathematica User GuideRELATED LINKS† webMathematica product page


276 webMathematica User GuidewebMathematicawebMathematica is a web server version of Mathematica. It allows you to build websites with interactivecalculations and visualizations driven by Mathematica. It is a key way to deliver technical computingsolutions in a networked environment.† Processing Input »MSPBlock ‰ MSPToExpression ‰ MSPValue ‰ MSPValueQ† Web Formatting »MSPFormat ‰ MSPLive3D ‰ MSPGetMessages ‰ MSPGetPrintOutput† Web Interaction »MSPReturn ‰ MSPSessionVariable ‰ MSPGetUploadFile ‰ MSPURLStore† webMathematica Tags »evaluate ‰ set ‰ get ‰ evaluateQueued† Configuration »KernelPoolName ‰ KernelNumber ‰ KernelExecutable ‰ KernelTimeLimitTUTORIALS† webMathematica User GuideRELATED LINKS† webMathematica product page


Tags


webMathematica User Guide 279evaluateevaluatetag that evaluates input to Mathematica and insert the formatted result in the output pageMORE INFORMATION† The evaluate tag is one of the most important tags for creating web material with webMathematica.A user places the tag inside of a web Mathematica JSP page, the body of the tag is evaluated, theresult is formatted and placed into the response to the web response. More information on the operationof the tags can be found in the section webMathematica Tags.† There is a large collection of Mathematica commands that can be used inside the tags such as evaluÖate. These provide useful functionality for creating web material with Mathematica. They are useful invarious ways such as processing request parameters that are the input from a web user, formattingresults, and using web features such as uploading files and HTTP sessions. More information can befound in the section Mathematica Web Functions.† The results of the computation of the body of an evaluate tag can be formatted in a variety of ways,such as into text, HTML fragments, or images. More information on formatting can be found in thesection on formatting.EXAMPLESBasic Examples (1)The following example evaluates an integral, and inserts the formatted result in the web page.Integrate[ expr, {var, 0, Infinity}]SEE ALSOevaluateQueued ‰ get ‰ set


280 webMathematica User GuideTUTORIALS† webMathematica User Guide† Mathematica Web Functions in webMathematica User Guide† webMathematica Tags in webMathematica User Guide† Evaluation Formatting in webMathematica User Guide


webMathematica User Guide 281evaluateQueuedevaluateQueuedtag that queues input to Mathematica to be evaluated laterMORE INFORMATION† The evaluateQueued tag is necessary to carry out computations with webMathematica that takelonger than a single web request. When the evaluateQueued tag is processed, webMathematicacreates a job object that waits in a queue until a kernel is available to do the calculation and the HTTPrequest returns immediately probably before the computation has even started. At some time in thefuture, the request is run and any results are saved. The web client can make a request to the server,using an identifier for the job, at any time to find out what has happened to the request. More informationcan be found in the section on Queuing of Long Calculations.† The evaluateQueued tag takes the following optional attributes.poolvarattribute that specifies the pool the computation should useattribute that specifies the name of a page variable to hold theID of the jobEXAMPLESBasic Examples (1)The following example queues up a long calculation to be run at a later date. It sets the pool for thecomputation to use and stores the id of the job in a page variable called jobID.longCalculation[]SEE ALSOevaluate ‰ get ‰ set


282 webMathematica User GuideTUTORIALS† webMathematica User Guide† Queueing of Long Calculations in webMathematica User Guide† webMathematica Tags in webMathematica User Guide


webMathematica User Guide 283setsetset a Mathematica variable with the value of a page expressionMORE INFORMATION† The set tag is necessary to interact between Mathematica and page expressions. It sets a variable inMathematica from a value of a page variable. Page variables can be used with other tag libraries andthe expression language features of webMathematica pages. More information on this can be found inthe section on Extended Page Language.† The set tag requires the following attributes.namevalueattribute that specifies the name of the page variable to holdthe resultattribute that specifies the value to setEXAMPLESBasic Examples (1)In the following example, the Mathematica variable var is set by the Java variable num.SEE ALSOevaluate ‰ evaluateQueued ‰ getTUTORIALS† webMathematica User Guide† Extended Page Language in webMathematica User Guide† webMathematica Tags in webMathematica User Guide


284 webMathematica User Guidegetgetgets the value of a Mathematica expression and sets a page context attribute with itMORE INFORMATION† The get tag is necessary to interact between Mathematica and page expressions. It gets a result fromMathematica and stores it in a page context attribute. Page context attributes can be used with othertag libraries and the expression language features of webMathematica pages. More information onthis can be found in the section on Extended Page Language.† The get tag takes the following required attributes.namevalueattribute that specifies the name of the page context attributeto hold the resultattribute that specifies the Mathematica command to beevaluatedEXAMPLESBasic Examples (1)In the following example, the variable dValue is set to the result of the Mathematica function Random[].SEE ALSOevaluate ‰ evaluateQueued ‰ setTUTORIALS† webMathematica User Guide† Extended Page Language in webMathematica User Guide† webMathematica Tags in webMathematica User Guide


Appendix


webMathematica User Guide 287Processing a JSPThis section will describe the different stages that are involved in processing a JSP forwebMathematica.A JSP is processed as part of an HTTP transaction. A client sends a request to the server, whichreplies with a response. One feature of HTTP requests is that they can send parameters andvalues to the server. This is essential for any dynamic behavior, because parameters are usedto select and control the response. The response could be an HTML page. However, it could besome other content type, such as an image, a Mathematica notebook, or some form of XML.The JSP is processed by the servlet container in which it is running, it is processed in a topdownmethod, so that commands at the top are evaluated before commands lower down. A JSPinteracts with webMathematica by means of the custom tags defined in the webMathematicatags. A sample page is shown below.pageeval1eval2The first evaluate tag allocates a Mathematica kernel to use for computations, assigning inputvariables and parameters, and other initialization. Note that the kernel that was allocated willbe available in a clean state.The evaluate tags then use the allocated Mathematica kernel to evaluate their input. Note thatany assignments or definitions made in one evaluate tag will be visible in another.


288 webMathematica User GuideWhen the page is finished the Mathematica kernel is released, first cleaning it of any definitionsthat were made. If any special processing is needed, for example, to deal with exceptions it willbe carried out at this point.It should be noted that there are a number of other special tags that can be used; these aredetailed in the section on the webMathematica tags, as are more details on the working of theevaluate tag.


webMathematica User Guide 289Mathematica InitializationThis section will briefly describe the initialization process for Mathematica kernels as they arelaunched by webMathematica and how it can be specially configured.Each Mathematica kernel is launched and initialized as follows.1. The Mathematica $Path is set so that code inside webMathematica can be loaded.2. The MSP application is loaded3. The security system is loaded4. The image system is set up5. The memory constraint parameters are set6. The logging, message, and print systems are set7. Kernel initialization code is evaluatedKernel initialization code is set with the KernelInitializeCode configuration parameter, whichis set in MSPConfiguration.xml. A sample setting follows.Needs[ "MyApplication`"];MyApplication`LaunchConnection[];The KernelInitializeCode setting is passed to the Mathematica kernel for evaluation as a laststep of initialization. It can contain extra commands for loading special packages.


290 webMathematica User GuidewebMathematica TagsThere are a number of tags that are provided by webMathematica. The key tags are those thatallow web pages to interact with Mathematica. The way they operate is discussed in this section.evaluateevaluateQueuedsetgetevaluate input to Mathematica and insert the result in theoutput pagequeue input to Mathematica to be evaluated laterset a Mathematica variable with the value of a pageexpressionget the result of a Mathematica computation and use it toset a page expressionMathematica tags.These tags are typically embedded in a JSP page, as shown in the following.pageeval1eval2webMathematica contains many examples of these pages; several are described in detail in theExamples section.Request InitializationThe first instance of an evaluate tag causes the kernel to be allocated and initialized.


webMathematica User Guide 291Determine the PoolThe first task is to determine which pool is to be used for the request. This is based on the fullname of the JSP using the URLPattern configuation setting.Allocate the KernelA Mathematica kernel is requested from the kernel pool. The pool maintains a collection ofMathematica kernels waiting for computations. If no kernel is available, the system waits untilone is ready. Using a pool allows the system to share Mathematica kernels across multiplerequests, which leads to a faster response time for the system.Note that each request may get a completely different kernel. You cannot rely on saving anythingin your Mathematica kernel and restoring it the next time.Assign Input VariablesAny input variables that were sent with the request are then passed to the Mathematica kernelwith their values. For a variable sym and value fun, a Mathematica assignment $$sym = "fun"is made. This ensures that the value is a Mathematica string, an inert object that will not evaluatewithout some special action. Note that input elements are not the only sources of variables.For example, an image map may cause transmission of variables. webMathematicarenames these input variables, and this helps to ensure that they do not interfere with yourMathematica code.Each variable is scanned to verify that it is a valid Mathematica symbol. Any "." character isreplaced by a backquote (`), and any underscore (_) is replaced with a "U". This mapping ofnames is consistent with the way that J/Link maps names.Here are some samples of renamed variables.Server Variableinputname.xvar_xMathematica Symbol$$inputname`$$x$$varUx


292 webMathematica User GuideEach variable is then validated to ensure it only contains letters or digits as well as the dollar($) and backquote (`) characters. This prevents an attack that sends a variable starting with anexclamation (!) character. This would be potentially dangerous because it might cause Mathematicato launch an operating system shell.Each value is turned into a Mathematica string. For this, any backslash (\) and doublequote (")characters are escaped with additional backslash (\) characters. If the value starts with anexclamation (!), a space is added. Finally, doublequotes (") are added around the result.Server ValueMathematica ValueSin@x+yD " Sin@x+yD "!myBoolean" !myBoolean""\foo\bar " " \" \\ foo \\ bar \" "Assign ParametersAssignments to $ServletRequest, $ServletResponse, $ScriptName, $PathInfo, and$QueryString appropriate for this request are made in the kernel.InitializationThe settings of $Context and $ContextPath are saved, and the lists used to store messagesand print output are initialized.If the configuration parameter KernelAcquireCode has been set for the pool this will be executedat this time.evaluateThe evaluate tag exists to evaluate Mathematica commands inside of a JSP. The body of thetag is evaluated by Mathematica. You can use the full range of MSP functions inside an evaluÖate tag. Each tag uses the kernel that was allocated by the first evaluate tag.If any MSPException is thrown, it will be caught by the processing code, and some suitableerror message will be inserted. Some of these turn into page errors.


webMathematica User Guide 293If any MSPReturn command is evaluated, processing of the current evaluation and all otherevaluations is terminated immediately, and its argument is returned directly from the JSP. If noMSPReturn command is encountered, the result of the evaluation is inserted into the outputstream.The processing of each evaluation is subject to various constraints.If Mathematica generates any messages or print output, these are stored so they can beretrieved with MSPGetMessages and MSPGetPrintOutput respectively.The result of the evaluate tag will be formatted and returned in the result. In the examplebelow, the current date will appear in the output page.Date[]If you wish to calculate more than one result in an evaluate tag, the different steps must beseparated with a semicolon ';'. The result of the last computation will be formatted and appearin the output page. In the example below, the numerical result of x+y will appear.x = Sin[5.6];y = Sqrt[x];x+yMore information on formatting of the result of evaluate appears in the section on EvaluationFormatting.It should be noted that until the request is finished and the kernel is released, the same kernelwill be used for all the tags evaluate, set, and get, thus any definitions and commands madein one will be visible in others. These definitions are cleared out when the request is finished.Request TerminationWhen the request is finished, all the evaluate tags will have been processed. At this time therequest will be terminated and the following steps carried out for postprocessing.


294 webMathematica User GuideJava ExceptionsIf any Java exceptions were thrown while processing the JSP, these are caught and the kernel isshut down and restarted. The exception is then rethrown and it may be returned with the HTTPrequest.MSPReturnIf a MSPReturn was encountered during an evaluation, its argument is returned instead of thenormal output of the JSP.Set ContentTypeThe content type is set. It is specified by a setting of the ContentType option of MSPPageOpÖtions or by MSPReturn. The default is text/html.Clean the KernelIf the configuration parameter KernelReleaseCode has been set for the pool, this will be executedat this time. Note that if the kernel has been terminated due to a restart the release codewill not be executed.The kernel is cleaned so that it can be used again. This involves clearing the values of parametersthat were sent with the request and removing all symbols in the default context. In addition$Context and $ContextPath are restored to their initial values, any Java object referencesare removed, and any open streams are closed.Release the KernelThe kernel is released to the pool so that it can be used again.setThe set tag exists to use Java to set a Mathematica symbol. Each set tag uses the kernel thatwas allocated by request initialization to evaluate its contents.


webMathematica User Guide 295The tag takes the following required attributes.namevaluethe name of the Mathematicavariable to hold the resultJava valueAttributes of the set tag.In the following example, the Mathematica variable var is set by the Java variable num.An example of set is given above.It should be noted that until the request is finished the same kernel will be used for all the tagsevaluate, set, and get, thus any definitions and commands made in one will be visible inothers. These definitions are cleared out when the request is terminated.getThe get tag exists to get a value from Mathematica into Java. Each get tag uses the kernel thatwas allocated by request initialization to evaluate its contents.The tag takes two required attributes, which are described below.namevaluethe name of the page variable to hold the resultthe Mathematica command to be evaluatedAttributes of the get tag.In the following example, the page variable dValue with type Double is set to the result of theMathematica function Random[].An example of get is given above.It should be noted that until the request is finished the same kernel will be used for all the tagsevaluate, set, and get, thus any definitions and commands made in one will be visible inothers. These definitions are cleared out when the request is terminated.


296 webMathematica User GuideevaluateQueuedThe evaluateQueued tag exists to carry out long running computations with webMathematica.It is described in detail in the section on queuing of long calculations.The tag takes two attributes, which are described below.varpoolthe name of a page variable to hold the job idthe pool to use for the computationAttributes of the evaluateQueued tag.


webMathematica User Guide 297Mathematica Web FunctionswebMathematica contains a large number of Mathematica commands that can be used insidethe webMathematica tags that provide useful functionality for creating web material with Mathematica.These are useful in various ways such as processing request parameters that are theinput from a web user, formatting results, and using web features such as uploading files andHTTP sessions.Typically, these commands are used inside of an evaluate tag; more information on these tagsis found in the webMathematica tags section. An example, which calculates an integral and usesthe function MSPFormat to format the result into TraditionalForm, is shown below.MSPFormat[ Integrate[ expr, {var, 0, Infinity}], TraditionalForm]The different functions are shown in the following sections.Processing InputHTTP input variables are a key way to control the operation of a dynamic website. These aretypically embedded in your input page with tags. webMathematica provides a numberof functions for working with and processing input. This needs to be done carefully to avoid anysecurity problems. The functions are summarized in the following table.MSPBlockMSPToExpressionMSPValueMSPValueQsecure scoping construct for HTTP inputinterpret input in a secure wayreturn the value of an HTTP input variabletest if an HTTP input variable has a value


298 webMathematica User GuideFormattingwebMathematica provides a number of important ways to format output for finished web pages.These include formatting into text, HTML, GIF, XML, MathML, and other formats. These aresummarized in the following table.MSPFormatMSPShowMSPLive3DMSPGetMessagesMSPGetPrintOutputHTMLTableFormHTMLSelectformat results into text or image formatsformat graphics by creating an imageformat 3D graphics to allow interactive viewingdisplay any messagesdisplay any print outputformat into an HTML tableformat into an HTML selectWeb InteractionwebMathematica provides a number of key functions for working with web features such asHTTP sessions and file upload. These are summarized in the following table.MSPReturnMSPSessionVariableMSPGetUploadFileMSPURLStorehalt processing of the current page and return a differentresultscope a variable to an HTTP sessionget the name of a file uploaded with the HTTP requeststore a result on the server that can be retrieved with aURL


webMathematica User Guide 299Site ConfigurationThis section summarizes how to configure a webMathematica site. Most configuration informationis held in the file MSPConfiguration.xml. The contents of this file are used to initialize theserver and individual Mathematica kernels.MSPConfiguration.xmlMSPConfiguration.xml is the central configuration file for webMathematica. A sample file isshown below.GeneralD:\Mathematica\MathKernel.exe1/*This shows the configuration for a kernel pool called General. A kernel pool is a group of Mathematicakernels that can be specially configured and is documented in the Advanced Topics:Multiple Kernel Pools section. You need to have at least one pool; webMathematica comes witha pool called General configured by default.If you want to change some configuration information, for example, adding some code for thekernel to run when it is launched, you could add this to the configuration file. If you put it insidethe KernelPool section, then the change will only apply to that pool. An example is shownbelow....LoadPackage[]


300 webMathematica User GuideHowever, if you want to make the change apply to any pool then you can put the code outsideall the pools. This is shown in the following.LoadPackage[]...If you are not sure what to do, then add the changes inside the pool definition.The different configuration parameters are shown in the tables below.KernelExecutableKernelLaunchFlagsKernelNumberKernelTimeLimitKernelAcquireLimitKernelConnectLimitKernelInitializeCodeKernelDestroyCodeKernelAcquireCodeKernelReleaseCodeKernelBaseMemoryLimitKernelPeakMemoryLimitthe path to the kernel executableflags to use when the kernel is launchedthe number of kernels in a poolthe maximum time for each computationthe number of requests a kernel can servethe length of time for the kernel to wait to connectMathematica code to run during kernel startupMathematica code to run during kernel shutdownMathematica code to run when a kernel is acquiredMathematica code to run when a kernel is releasedmemory limit for continuous usagememory limit for temporary usageKernel configuration.FrontEndExecutableFrontEndLaunchFlagsKeepFrontEndAlivethe path to the front end executableflags to use when the front end is launchedwhether the front end should be kept running after usageFront end configuration.KernelPoolKernelPoolNameURLPatternconfiguration section for a particular kernel poolthe name of a kernel poolthe pattern to map URLs to a kernel poolKernel pool configuration.


webMathematica User Guide 301SecurityConfigurationFileCheckToExpressionCollectStreamsFileUploadSizeLimitJLinkNativeLibraryDirectorythe name of the security configuration file ToExpressionwhether a security check should be applied to ToExpresÖsionwhether streams opened during a request should beautomatically closedthe limit on the size of files that can be uploadedthe location of the J/Link native libraryGeneral site configuration.Logging SystemThe logging system for webMathematica can be customized. This is described in the Loggingsection.Security ConfigurationThe security system for webMathematica can be customized. This is described in the Securitysection.X Server ConfigurationSpecial configuration is often required to allow the front end to connect an X server. This isdescribed in the Installation section under Configuring for the X Window System (Unix only).This is only an issue for running webMathematica under Unix.


302 webMathematica User GuideLiveGraphics3DOne of the useful features of webMathematica is its integration with the LiveGraphics3Dapplet. This applet displays Mathematica three-dimensional graphics and provides support forfeatures such as interactive rotation and resizing. It is shipped with webMathematica and isused by the command MSPLive3D. The applet has been carefully developed so that it works in awide range of different Java-enabled browsers.The interface is given below.user actiondrag and press theleft mouse buttonrelease the left mousebutton while draggingpress the SHIFT keyand drag verticallypress the SHIFT keyand drag horizontallypress the CONTROLkey and drag verticallypress the CONTROL keyand drag horizontallypress the META HALTL keyIor the right mouse buttonMand drag verticallypress the ' o' keypress the ' s' keypress the HOME keyapplet reactionrotate about an axis in the picturespin about an axis in the picturezoomrotate about an axis perpendicular to the picturechange the focal lengthchange the strength of the stereo effectstrip parts of the graphicswrite parameter settings in the Java consoletoggle between single and stereo viewsrestore the original perspective Hno spinningL


webMathematica User Guide 303In addition, the MSPLive3D command can set the Magnification parameter for the applet asfollows.MSPLive3D[ Plot3D[ Sin[x y],{x,0,3},{y,0,3}], Magnification -> 0.4]More information on the LiveGraphics3D applet is available from the website maintained by itsauthor, Martin Kraus, at http://wwwvis.informatik.uni-stuttgart.de/~kraus/LiveGraphics3D.


304 webMathematica User GuideDynamic HTMLWhen the web was first developed, it supported only the distribution of static pages. The technol -ogy was extended to allow interactive access for dynamic content generation.Fundamentally, the web is driven by its main protocol, HTTP (Hyper Text Transfer Protocol),which imposes certain constraints. Under HTTP, a client sends a request to a server that replieswith a response. A crucial feature of HTTP is that it is stateless; that is, after processing arequest, no record of that request is kept. Of course, state information can be maintained viasome other mechanism; for example, the servlet API has methods for keeping state that can beused with MSPSessionVariable.This reference section reviews server and client technologies for dynamic web content. Becausethis field changes very rapidly, the survey is not intended to be exhaustive.Server TechnologyThere are several server-side technologies for dynamic content. These include CGI scripting,Active Server Pages, server plug-ins, Perl scripting, and Java servlets and JavaServer Pages.CGI ScriptingCGI scripts provided the original server technology for dynamic content. Under CGI, an executable,such as a shell script or compiled binary, is launched on every request.This mechanism is limited in a number of key ways. It is relatively expensive since it requireslaunching a new CGI process for every request, which can cause scalability problems. Onesolution is to make the actual CGI script a lightweight process that communicates with its ownserver; many web solutions actually do this. Of course this requires nontrivial development andcan result in something that is more complicated to use than other dynamic solutions.


webMathematica User Guide 305Active Server PagesActive Server Pages (ASPs) are a scripting language for dynamic web content, developed byMicrosoft. They are quite common and powerful. At present, ASPs are not supported, but thiswill be continually reviewed.Server Plug-insMost HTTP servers provide some type of extensibility that can be used to support special featuresfor interactivity. The problem with this approach is that it is not very portable.Perl ScriptingPerl is often used as a scripting language either with CGI or a server plug-in. Technologies existto link Mathematica to Perl, but these are not as developed as is the technology for linking toJava.Java Servlets and JavaServer PagesJava Servlet technology provides a high-level API (programming interface) for working withHTTP requests. There are many ways that web servers can be enhanced to add a servletengine. Solutions exist for all web servers and run on all major platforms.The Servlet API is a high-level interface that provides functions both for maintaining informationwhile the server is running and for working with HTTP requests and responses.JavaServer Pages (JSPs) are a closely related technology that make it very convenient forservlets to return HTML; the server converts a JSP into a servlet, which is then executed.webMathematica is implemented with a mixture of Java Servlet and JSP technology.Client TechnologyUltimately, any content is downloaded to a client where it is rendered. In a sense, the purposeof server technology is to prepare input for a client. In the client there are also various dynamiccontent technologies. These include HTML, JavaScript, and applets.


306 webMathematica User GuideHTMLThe fundamental content delivered by web servers is HTML, a tree-structured language formedfrom tags. At present, HTML is being transitioned into a stricter language, XHMTL, an XMLapplication.HTML is fundamental to the topic of dynamic web content, so here is a short primer on dynamicweb content with HTML.First, start with a basic HTML document.My PageMy PageWelcome to my page.This could be downloaded from a web server and rendered in a web browser.Active elements are added to HTML by form and input elements, which can be included insidean HTML document. Here is a form element.The form has two attributes, an action attribute and a method attribute. When the form isactivated, it will make a connection to this URL and use the post method.Often the URL will be located on the same server from which the page was downloaded. In thiscase it is common to use a relative URL.A form element may contain input elements, which add various buttons and input fields. Hereis an example of a form with two input tags: the first allows text to be entered, and the secondcauses the form to be submitted.


webMathematica User Guide 307When the form is activated by the submit input tag, the browser makes a request to the URLreferred to by the action attribute. It sends the name and value pairs from all of the inputtags in the form. This is the most basic way to activate HTML.One thing to remember about form elements is that the name/value pairs can bespecified in the URL. You may have seen them in something like http://myserver/document?ARG1=10&ARG2=20.JavaScriptJavaScript is a compact object-based scripting language for developing client and server internetapplications. JavaScript code can be embedded directly in an HTML page. It can, for example,embellish the operation of form and input elements. One problem with JavaScript is that itis not uniform across different browsers. JavaScript can manipulate the browser and the documentsthat the browser holds. It can also interact with applets and plug-ins.Some of the examples included with webMathematica work with JavaScript.AppletsApplets are programs written in Java that can run in a Java-enabled browser. They are lesstightly integrated with HTML than JavaScript but are probably easier to develop and can call onmuch of Java technology. As with JavaScript, some (especially older) browsers give incompleteand poor support for applets. Applets can call on the large collection of functions that are availablein the Java programming language and can actually draw into the browser.Some of the examples are designed to work with applets.


308 webMathematica User GuideFuture DevelopmentsThe major browsers, Internet Explorer, Mozilla, and Netscape Navigator, continue to developnew interactive technologies at a rapid pace. It may be advantageous for webMathematicausers to consider new technologies as they become available.


webMathematica User Guide 309LinksThe links listed here were valid at the time this documentation was written.Mathematica TechnologyMain <strong>Wolfram</strong> <strong>Research</strong> site:http://www.wolfram.comwebMathematica:http://www.wolfram.com/products/webmathematicawebMathematica release notes:http://www.wolfram.com/products/webmathematica/releasenoteswebMathematica documentation updates:http://www.wolfram.com/products/webmathematica/resources/?tab=UpdatesMathematica:http://www.wolfram.com/products/mathematica<strong>Wolfram</strong> Workbench:http://www.wolfram.com/products/workbenchMathematica products:http://www.wolfram.com/productsJ/Link:http://www.wolfram.com/solutions/mathlink/jlinkDatabaseLink:http://reference.wolfram.com/mathematica/DatabaseLink/tutorial/Overview.htmlWeb Services Package:http://reference.wolfram.com/mathematica/WebServices/tutorial/Overview.htmlLiveGraphics3D:http://wwwvis.informatik.uni-stuttgart.de/~kraus/LiveGraphics3D


310 webMathematica User GuideMathematica PackagesWriting packages:http://reference.wolfram.com/mathematica/tutorial/SettingUpMathematicaPackages.htmlJavaSun Java information:http://java.sun.comSun JDK download for Windows, Linux, and Solaris:http://java.sun.com/javase/downloads/index.jspTomcatLinks to current versions:http://www.wolfram.com/products/webmathematica/resources/?tab=UpdatesApache Tomcat download section:http://jakarta.apache.org/site/downloads/index.htmlMain Apache site:http://jakarta.apache.orgServers JSPs and ServletsMain site for servlet technology:http://java.sun.com/products/servlet/Uses of servlets:http://java.sun.com/products/servlet/industry.htmlMain site for JSP technology:http://java.sun.com/products/jsp/Apache, HTTP server:http://httpd.apache.org


webMathematica User Guide 311Web Browser TechnologiesHTML 4.0:http://www.w3.org/TR/REC-html40/XHTML:http://www.w3.org/TR/xhtml1/JavaScript:http://www.w3schools.com/js/default.aspAJAX:http://www.w3schools.com/ajax/default.aspFlash:http://www.adobe.com/products/flashplayer/XML, MathML, and SVGXML:http://www.w3.org/XML/MathML:http://www.w3.org/Math/MathML characters:http://www.w3.org/TR/MathML2/chapter6.htmlUnicode characters:http://www.unicode.org/MathPlayer:http://www.dessci.com/webmath/mathplayer/Mozilla:http://www.mozilla.orgAmaya:http://www.w3.org/Amaya/


312 webMathematica User GuideSVG:http://www.w3.org/Graphics/SVG/Adobe SVG:http://www.adobe.com/svg/PDF ToolsPStill:http://www.pstill.comps2pdf:http://www.cs.wisc.edu/~ghost/doc/AFPL/8.00/Ps2pdf.htmThe X Window SystemRealVNC:http://www.realvnc.com/TightVNC:http://www.tightvnc.com/Xvfb:http://www.xfree86.org/4.3.0/Xvfb.1.htmlLogginglog4j:http://logging.apache.org/log4j/docs/index.html

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!