Annotation of java/classes/org/w3c/rdf/examples/SiRPACServlet.java, revision 1.17

1.1       barstow     1: /**
                      2:  * SiRPACServlet - Simple RDF Parser & Compiler Servlet wrapper
                      3:  *
                      4:  * Copyright © World Wide Web Consortium, (Massachusetts Institute of
                      5:  * Technology, Institut National de Recherche en Informatique et en
                      6:  * Automatique, Keio University).
                      7:  *
                      8:  * All Rights Reserved.
                      9:  *
                     10:  * Please see the full Copyright clause at
                     11:  * <http://www.w3.org/Consortium/Legal/copyright-software.html>
                     12:  *
1.3       barstow    13:  * This servlet is a wrapper for the SiRPAC RDF parser.  The servlet 
1.7       barstow    14:  * expects the following variables through the POST method:
1.3       barstow    15:  *
1.16      barstow    16:  * 1. RDF - the RDF/XML document 
                     17:  * 2. BAGS - if "on", each Description should have its own Bag;
                     18:  *      the default is not to do this.
                     19:  * 3. STREAM if "on", the stream mode is turned off so that aboutEach
                     20:  *      and aboutEachPrefix are supported.
                     21:  * 4. SAVE_RDF if "on", the RDF will be copied to a file.
                     22:  * 5. URI - the URI to parse [instead of the RDF]; may not be specified
1.1       barstow    23:  *
1.7       barstow    24:  * @author Art Barstow <barstow@w3.org>
1.1       barstow    25:  *
1.7       barstow    26:  * The graphics package is AT&T's GraphVis tool.
1.1       barstow    27:  */
                     28: 
                     29: package org.w3c.rdf.examples;
                     30: 
                     31: import java.io.*;
1.16      barstow    32: import java.net.MalformedURLException;
                     33: import java.net.URL;
1.1       barstow    34: import java.util.StringTokenizer;
                     35: import java.util.Enumeration;
                     36: import javax.servlet.*;
                     37: import javax.servlet.http.*;
                     38: 
                     39: import org.xml.sax.InputSource;
                     40: import org.xml.sax.Parser;
                     41: import org.xml.sax.SAXException;
                     42: import org.xml.sax.helpers.*;
                     43: 
                     44: import org.w3c.rdf.model.*;
                     45: import org.w3c.rdf.syntax.*;
                     46: import org.w3c.rdf.syntax.RDFConsumer;
                     47: import org.w3c.rdf.util.xml.DumpConsumer;
                     48: import org.w3c.rdf.util.xml.ErrorStore;
1.16      barstow    49: import org.w3c.rdf.util.xml.GenericParser;
1.1       barstow    50: import org.w3c.rdf.implementation.model.StatementImpl;
                     51: import org.w3c.rdf.implementation.model.NodeFactoryImpl;
                     52: import org.w3c.rdf.implementation.syntax.sirpac.*;
                     53: 
                     54: public class SiRPACServlet extends HttpServlet
                     55: {
1.17    ! barstow    56:     final static public String REVISION = "$Id: SiRPACServlet.java,v 1.16 2000/12/18 20:07:31 barstow Exp $";
1.1       barstow    57: 
1.7       barstow    58:     // The email address for bug reports
1.4       barstow    59:     private static final String MAIL_TO = "barstow@w3.org";
1.10      barstow    60: 
                     61:     // Names of the POST parameters
                     62:     //   The XML'ized RDF
                     63:     private static final String POST_TEXT            = "RDF";
                     64:     //   Flag for turning on treating each Description as a bag
                     65:     private static final String POST_BAG             = "BAGS";
                     66:     //   Flag for turning off SiRPAC's stream parsing mode
                     67:     private static final String POST_STREAM_MODE     = "STREAM";
1.14      barstow    68:     //   Flag to indicate that the RDF should be copied to a file
                     69:     private static final String POST_SAVE_RDF        = "SAVE_RDF";
1.16      barstow    70:     //   The URI of the RDF to parse
                     71:     private static final String POST_URI             = "URI";
1.3       barstow    72:  
                     73:     // Names of the servlet's parameters
1.5       barstow    74:     private static final String SIRPAC_TMP_DIR       = "SIRPAC_TMP_DIR";
                     75:     private static final String GRAPH_VIZ_ROOT       = "GRAPH_VIZ_ROOT";
                     76:     private static final String GRAPH_VIZ_PATH       = "GRAPH_VIZ_PATH";
                     77:     private static final String GRAPH_VIZ_LIB_DIR    = "GRAPH_VIZ_LIB_DIR";
                     78:     private static final String GRAPH_VIZ_FONT_DIR   = "GRAPH_VIZ_FONT_DIR";
1.3       barstow    79: 
                     80:     // Variables for the servlet's parameters
1.5       barstow    81:     private static String m_SiRPACTmpDir      = null;
                     82:     private static String m_GraphVizPath      = null;
                     83:     private static String m_GraphVizFontDir   = null;
                     84:     private static String m_GraphVizLibDir    = null;
1.4       barstow    85: 
                     86:     // Names of environment variable need by GraphVis
                     87:     private static String DOTFONTPATH     = "DOTFONTPATH";
                     88:     private static String LD_LIBRARY_PATH = "LD_LIBRARY_PATH";
                     89: 
                     90:     // Names used for temporary files
                     91:     private static final String TMP_FILE_PREFIX = "sirpac_";
                     92:     private static final String TMP_DIR_SUFFIX  = ".tmp";
                     93:     private static final String DOT_SUFFIX      = ".dot";
                     94:     private static final String GIF_SUFFIX      = ".gif";
1.14      barstow    95:     private static final String RDF_SUFFIX      = ".rdf";
1.3       barstow    96: 
1.6       barstow    97:     // Default GraphViz parameter names and their default values
                     98:     private static final String NODE_COLOR         = "NODE_COLOR";
                     99:     private static final String DEFAULT_NODE_COLOR = "black";
                    100: 
                    101:     private static final String NODE_TEXT_COLOR         = "NODE_TEXT_COLOR";
                    102:     private static final String DEFAULT_NODE_TEXT_COLOR = "black";
                    103: 
                    104:     private static final String EDGE_COLOR         = "EDGE_COLOR";
                    105:     private static final String DEFAULT_EDGE_COLOR = "black";
                    106: 
                    107:     private static final String EDGE_TEXT_COLOR         = "EDGE_TEXT_COLOR";
                    108:     private static final String DEFAULT_EDGE_TEXT_COLOR = "black";
                    109: 
                    110:     private static final String ORIENTATION         = "ORIENTATION";
                    111:     private static final String DEFAULT_ORIENTATION = "TB";  // Top to Bottom
                    112: 
                    113:     private static final String FONT_SIZE         = "FONT_SIZE";
                    114:     private static final String DEFAULT_FONT_SIZE = "10";
                    115: 
                    116:     // Fonts are not currently configurable
                    117:     private static final String DEFAULT_FONT = "arial";
                    118: 
1.8       barstow   119:     // Servlet name
                    120:     private static final String SERVLET_NAME = "SiRPACServlet";
                    121: 
1.3       barstow   122:     // The parser
                    123:     private SiRPAC       m_sirpac = null;
                    124:     // The error handler
                    125:     private ErrorStore    m_errorHandler;
1.1       barstow   126: 
1.3       barstow   127:     /*
1.4       barstow   128:      * Create a File object in the m_SiRPACTmpDir directory
1.3       barstow   129:      *
1.4       barstow   130:      *@param directory the file's directory
                    131:      *@param prefix the file's prefix name (not its directory)
                    132:      *@param suffix the file's suffix or extension name
                    133:      *@return a File object if a temporary file is created; null otherwise
1.3       barstow   134:      */
1.4       barstow   135:     private File createTempFile (String directory, String prefix, String suffix) {
                    136:         File f;
                    137:         try {
                    138:             File d = new File(directory);
                    139:             f = File.createTempFile(prefix, suffix, d);
                    140:         } catch (Exception e) {
                    141:             return null;
                    142:         }
                    143:         return f;
                    144:     }
                    145: 
1.14      barstow   146: 
                    147:     /*
                    148:      * Copy the given string of RDF to a file in the given directory
                    149:      *
                    150:      *@param dir the file's directory
                    151:      *@param rdf the string of RDF
                    152:      *@return void
                    153:      */
                    154: 
                    155:     private void copyRDFStringToFile(String tmpDir, String rdf) 
                    156:     {
                    157:         try {
                    158:             // Generate a unique file name 
                    159:             File tmpFile = createTempFile(tmpDir, TMP_FILE_PREFIX, RDF_SUFFIX);
                    160:             if (tmpFile == null) {
                    161:                 // Not really a critical error, just return
                    162:                 return;
                    163:             }
                    164: 
                    165:             // Create a PrintWriter for the GraphViz consumer
                    166:             FileWriter fw = new FileWriter(tmpFile);
                    167:             PrintWriter pw = new PrintWriter(fw);
                    168: 
                    169:             pw.println(rdf);
                    170:             pw.close();
                    171:         } catch (Exception e) {
                    172:             // Just return - not critical
                    173:             return;
                    174:         }
                    175:     }
                    176: 
1.4       barstow   177:     /*
                    178:      * Invokes the GraphVis program to create a GIF image from the
                    179:      * the given DOT data file
                    180:      *
                    181:      *@param dotFileName the name of the DOT data file
                    182:      *@param gifFileName the name of the GIF data file 
                    183:      *@return true if success; false if any failure occurs
                    184:      */
                    185:     private boolean generateGifFile(String dotFileName, String gifFileName) {
1.5       barstow   186:         String environment[] = {DOTFONTPATH     + "=" + m_GraphVizFontDir,
                    187:                                 LD_LIBRARY_PATH + "=" + m_GraphVizLibDir};
1.4       barstow   188: 
1.5       barstow   189:         String cmdArray[] = {m_GraphVizPath, "-Tgif", "-o", gifFileName, dotFileName};
1.4       barstow   190: 
                    191:         Runtime rt = Runtime.getRuntime();
                    192:         try {
                    193:             Process p = rt.exec(cmdArray, environment);
                    194:             p.waitFor();
                    195:         } catch (Exception e) {
                    196:             return false;
                    197:         }
                    198: 
                    199:         return true;
1.3       barstow   200:     }
1.1       barstow   201: 
1.3       barstow   202:     /*
1.6       barstow   203:      * Returns a parameter from a request or the parameter's default
                    204:      * value.
                    205:      *
                    206:      *@param req a Servlet request
                    207:      *@return if the request contains the specfied parameter its value
                    208:      *  in the request is returned; otherwise its default value is
                    209:      *  returned
                    210:      */
                    211:     private String getParameter(HttpServletRequest req, String param, String defString) {
                    212:         String s = req.getParameter(param);
                    213:         return (s == null) ? defString : s;
                    214:     }
                    215: 
                    216:     /*
                    217:      * If the request contains any graph-related parameters, pass them
                    218:      * to the graph consumer for handling
                    219:      *
                    220:      *@param req the response
                    221:      *@param consumer the GraphViz consumer
                    222:      */
                    223:     private void processGraphParameters (HttpServletRequest req, GraphVizDumpConsumer consumer) {
                    224:         // Look for colors
                    225: 
                    226:        String s;
                    227:        
                    228:         String nodeColor     = getParameter (req, NODE_COLOR, DEFAULT_NODE_COLOR);
                    229:         String nodeTextColor = getParameter (req, NODE_TEXT_COLOR, DEFAULT_NODE_TEXT_COLOR);
                    230:         String edgeColor     = getParameter (req, EDGE_COLOR, DEFAULT_EDGE_COLOR);
                    231:         String edgeTextColor = getParameter (req, EDGE_TEXT_COLOR, DEFAULT_EDGE_TEXT_COLOR);
                    232:         String fontSize = getParameter (req, FONT_SIZE, DEFAULT_FONT_SIZE);
                    233: 
                    234:         // Orientation must be either 
                    235:         String orientation = req.getParameter (ORIENTATION);
                    236:         if (orientation.equals("Left to Right"))
                    237:             orientation = "LR";
                    238:         else
                    239:             orientation = DEFAULT_ORIENTATION;
                    240: 
                    241:         // Add an attribute for all of the graph's nodes
                    242:         consumer.addGraphAttribute("node [fontname=" + DEFAULT_FONT + 
                    243:                                    ",fontsize="  + fontSize +
                    244:                                    ",color="     + nodeColor +
                    245:                                    ",fontcolor=" + nodeTextColor + "]");
                    246: 
                    247:         // Add an attribute for all of the graph's edges
                    248:         consumer.addGraphAttribute("edge [fontname=" + DEFAULT_FONT + 
                    249:                                    ",fontsize="  + fontSize +
                    250:                                    ",color="     + edgeColor +
                    251:                                    ",fontcolor=" + edgeTextColor + "]");
                    252: 
                    253:         // Add an attribute for the orientation
                    254:         consumer.addGraphAttribute("rankdir=" + orientation + ";");
                    255:     }
                    256: 
                    257:     /*
1.3       barstow   258:      * Generate a graph of the RDF data model
                    259:      *
1.4       barstow   260:      *@param out the servlet's output stream
1.6       barstow   261:      *@param rdf the RDF text
                    262:      *@param req a Servlet request
1.3       barstow   263:      */
1.14      barstow   264:     private void generateGraph (ServletOutputStream out, String rdf, HttpServletRequest req, boolean saveRDF) {
1.2       barstow   265:         try {
                    266:             out.println("<hr title=\"visualisation\">");
1.3       barstow   267:             out.println("<h3>Graph of the data model</h3>");
                    268: 
1.4       barstow   269:             // Stop if any of the parameters are missing
1.5       barstow   270:             if (m_SiRPACTmpDir == null || m_GraphVizPath == null || 
                    271:                 m_GraphVizFontDir == null || m_GraphVizLibDir == null) { 
1.8       barstow   272:  
                    273:                 // Put the paths in a comment in the returned content
                    274:                 out.println("<!-- SIRPAC TMP = " + m_SiRPACTmpDir);
                    275:                 out.println("GRAPH VIZ  = " + m_GraphVizPath);
                    276:                 out.println("GRAPH LIB  = " + m_GraphVizLibDir);
                    277:                 out.println("GRAPH FON  = " + m_GraphVizFontDir + " -->");
                    278: 
1.3       barstow   279:                 out.println("Servlet initialization failed.  A graph cannot be generated.");
                    280:                 return;
                    281:             } 
                    282: 
1.4       barstow   283:             // The temporary directory
                    284:             String tmpDir = m_SiRPACTmpDir;
1.3       barstow   285: 
1.4       barstow   286:             // Must generate a unique file name that the DOT consumer
                    287:             // will use 
                    288:             File dotFile = createTempFile(tmpDir, TMP_FILE_PREFIX, DOT_SUFFIX);
                    289:             if (dotFile == null) {
                    290:                 out.println("Failed to create a temporary DOT file. A graph cannot be generated.");
1.3       barstow   291:                 return;
                    292:             }
                    293: 
                    294:             // Create a PrintWriter for the GraphViz consumer
1.4       barstow   295:             FileWriter fw = new FileWriter(dotFile);
1.3       barstow   296:             PrintWriter pw = new PrintWriter(fw);
                    297: 
                    298:             // Run the parser using the DOT consumer to capture
                    299:             // the output in a file
                    300:            StringReader         sr = new StringReader (rdf);
                    301:            InputSource          is = new InputSource (sr);
                    302:             GraphVizDumpConsumer consumer = new GraphVizDumpConsumer(pw);
                    303: 
1.6       barstow   304:             // Process any graph-related parameters in the request
                    305:             processGraphParameters(req, consumer);
1.15      barstow   306: 
                    307:             // Reinitialize the parser's genid counter so the genids
                    308:             // of the triple will match the genids of the graph
                    309:             m_sirpac.setGenidNumber(0);
1.6       barstow   310: 
1.3       barstow   311:            try {
                    312:                 m_sirpac.parse(is, consumer);
                    313:            } catch (Exception e) {
                    314:                 out.println("An attempt to generate the graph data failed ("
                    315:                             + e.getMessage() + ").");
1.4       barstow   316:                 pw.close();
                    317:                 dotFile.delete();
1.3       barstow   318:                 return;
                    319:            }
                    320: 
1.4       barstow   321:             // Must close the DOT input file so the GraphViz can
                    322:             // open and read it
                    323:             pw.close();
                    324: 
                    325:             // Must generate a unique file name for the GIF file
                    326:             // that will be created
                    327:             File gifFile = createTempFile(tmpDir, TMP_FILE_PREFIX, GIF_SUFFIX);
                    328:             if (gifFile == null) {
                    329:                 out.println("Failed to create a temporary GIF file. A graph cannot be generated.");
                    330:                 dotFile.delete();
                    331:                 return;
                    332:             }
                    333: 
1.3       barstow   334:             // Pass the DOT data file to the GraphViz dot program
1.4       barstow   335:             // so it can create a GIF image of the data model
                    336:             String dotFileName = dotFile.getAbsolutePath();
                    337:             String gifFileName = gifFile.getAbsolutePath();
                    338: 
                    339:             if (!generateGifFile(dotFileName, gifFileName)) {
                    340:                 out.println("An attempt to create a graph failed.");
                    341:                 dotFile.delete();
                    342:                 gifFile.delete();
                    343:                 return;
                    344:             }
1.3       barstow   345: 
1.7       barstow   346:             // Cleanup
                    347:             dotFile.delete();
1.3       barstow   348: 
1.9       barstow   349:             // NOTE: Cannot delete the GIF file here because its
                    350:             // pathname is returned to the client
1.8       barstow   351:             String imagePath = SERVLET_NAME +
1.7       barstow   352:                                TMP_DIR_SUFFIX + File.separator + 
                    353:                                gifFile.getName();
1.2       barstow   354: 
1.4       barstow   355:             if (gifFile.length() > 0)
                    356:                 out.println("<img src=\"" + imagePath + "\"/>");
                    357:             else
                    358:                 out.println("The graph image file is empty.");
1.2       barstow   359: 
1.14      barstow   360:             // One last thing to do before exiting - copy the RDF to a file
                    361:             if (saveRDF)
                    362:                 copyRDFStringToFile(tmpDir, rdf);
                    363: 
1.2       barstow   364:         } catch (Exception e) {
                    365:             System.err.println("Exception: " + e.getMessage());
                    366:         }
                    367:     }
                    368: 
                    369:     /*
1.3       barstow   370:      * Search the given string for substring "key"
1.2       barstow   371:      * and if it is found, replace it with string "replacement"
                    372:      *
1.4       barstow   373:      *@param input the input string
                    374:      *@param key the string to search for
                    375:      *@param replacement the string to replace all occurences of "key"
1.2       barstow   376:      *@return if no substitutions are done, input is returned; otherwise 
                    377:      * a new string is returned.
                    378:      */
1.12      barstow   379:     public static String replaceString(String input, String key, String replacement) {
1.2       barstow   380:         StringBuffer sb = new StringBuffer("");
                    381:         StringTokenizer st = new StringTokenizer(input, key);
                    382: 
                    383:         // Must handle the case where the input string begins with the key
                    384:         if (input.startsWith(key))
                    385:             sb = sb.append(replacement);
                    386:         while (st.hasMoreTokens()) {
                    387:             sb = sb.append(st.nextToken());
                    388:             if (st.hasMoreTokens())
                    389:                 sb = sb.append(replacement);
                    390:         }
                    391:         if (sb.length() >= 1)
                    392:             return sb.toString();
                    393:         else
                    394:             return input;
                    395:     }
                    396: 
1.3       barstow   397:     /*
                    398:      * Print the document's header info
                    399:      *
                    400:      *@param out the servlet's output stream
                    401:      */
1.1       barstow   402:     private void printDocumentHeader (ServletOutputStream out) {
                    403: 
                    404:         try {
                    405: 
                    406:             out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"");
                    407:             out.println("      \"http://www.w3.org/TR/REC-html40/loose.dtd\">");
                    408:             out.println("<HTML><HEAD>");
                    409:             out.println("<TITLE>RDF creation</TITLE>");
                    410:             out.println("<LINK HREF=\"rdf.css\" REL=\"stylesheet\">");
                    411:             out.println("</HEAD>");
                    412:             out.println("<BODY>");
                    413: 
                    414:         } catch (Exception e) {
1.2       barstow   415:             System.err.println("Exception: " + e.getMessage());
1.1       barstow   416:         }
                    417:     }
                    418: 
1.3       barstow   419:     /*
                    420:      * Print the rdf listing
                    421:      *
                    422:      *@param out the servlet's output stream
                    423:      *@param rdf the RDF code
                    424:      */
1.16      barstow   425:     private void printListing (ServletOutputStream out, String rdf, boolean needCR) {
1.1       barstow   426:         try {
                    427:             out.println("<hr title=\"original source\">");
                    428:             out.println("<h3>The original RDF/XML document</h3>");
                    429:             out.println("<pre>");
                    430: 
1.2       barstow   431:             String s = replaceString(rdf, "<", "&lt;");
                    432:             StringTokenizer st = new StringTokenizer(s, "\n");
1.1       barstow   433: 
                    434:             // Now output the RDF one line at a time with line numbers
                    435:             int lineNum = 1;
                    436:             while (st.hasMoreTokens()) {
1.16      barstow   437:                 if (needCR) 
                    438:                     out.print ("<a name=\"" + lineNum + "\">" + lineNum +
                    439:                                "</a>: " + st.nextToken() + "\n");
                    440:                 else
                    441:                     out.print ("<a name=\"" + lineNum + "\">" + lineNum +
                    442:                                "</a>: " + st.nextToken());
1.1       barstow   443:                 lineNum++;
                    444:             }
                    445: 
                    446:             out.println("</pre>");
                    447:         } catch (Exception e) {
                    448:             System.err.println("Exception: " + e.getMessage());
                    449:         }
                    450:     }
                    451: 
1.3       barstow   452:     /*
                    453:      * Print the header for the triple listing
                    454:      *
                    455:      *@param out the servlet's output stream
                    456:      */
1.17    ! barstow   457:     private void printTripleTableHeader (ServletOutputStream out) {
1.1       barstow   458:         try {
                    459:             out.println("<hr title=\"triples\">");
                    460:             out.println("<h3>Triples of the data model</h3>");
1.17    ! barstow   461:             out.println("<table border><tr>" +
        !           462:                          "<td><b>Number</b></td>" +
        !           463:                          "<td><b>Subject</b></td>" +
        !           464:                          "<td><b>Predicate</b></td>" +
        !           465:                          "<td><b>Object</b></td>" +
        !           466:                        "</tr>");
1.1       barstow   467:         } catch (Exception e) {
                    468:             System.err.println("Exception: " + e.getMessage());
                    469:         }
                    470:     }
                    471: 
1.3       barstow   472:     /*
                    473:      * Print the footer info for the triple listing
                    474:      *
                    475:      *@param out the servlet's output stream
                    476:      */
1.17    ! barstow   477:     private void printTripleTableFooter (ServletOutputStream out, SiRPACServletDumpConsumer consumer) {
1.1       barstow   478:         try {
1.17    ! barstow   479:             out.println("</table>");
1.14      barstow   480:             if (consumer != null)
                    481:                 out.println("<p>The number of triples = " + consumer.getNumStatements() + "</p>");
1.1       barstow   482:         } catch (Exception e) {
                    483:             System.err.println("Exception: " + e.getMessage());
                    484:         }
                    485:     }
1.3       barstow   486: 
                    487:     /*
                    488:      * Print the document's footer info
                    489:      *
                    490:      *@param out the servlet's output stream
                    491:      *@param rdf the RDF code
                    492:      */
1.1       barstow   493:     private void printDocumentFooter (ServletOutputStream out, String rdf) {
                    494:         try {
                    495: 
                    496:             out.println("<hr title=\"Problem reporting\">");
                    497:             out.println("<h3>Feedback</h3>");
1.2       barstow   498:             out.println("<p>If you suspect that SiRPAC produced an error, please enter an explanation below and then press the <b>Submit problem report</b> button, to mail the report (and listing) to <i>" + MAIL_TO + "</i></p>");
1.1       barstow   499:             out.println("<form enctype=\"text/plain\" method=\"post\" action=\"mailto:" + MAIL_TO + "\">");
                    500:             out.println("<textarea cols=\"60\" rows=\"4\" name=\"report\"></textarea>");
1.2       barstow   501:             out.println("<p><input type=\"hidden\" name=\"RDF\" value=\"&lt;?xml version=&quot;1.0&quot;?>");
1.1       barstow   502: 
1.2       barstow   503:             // The listing is being passed as a parameter so the '<' 
                    504:             // and '"' characters must be replaced with &lt; and &quot, 
                    505:             // respectively
1.16      barstow   506:             if (rdf != null) {
                    507:                 String s1 = replaceString(rdf, "<", "&lt;");
                    508:                 String s2 = replaceString(s1,  "\"", "&quot;");
                    509:                 out.println(s2 + "\">");
                    510:             }
1.1       barstow   511: 
                    512:             out.println("<input type=\"submit\" value=\"Submit problem report\">");
                    513:             out.println("</form>");
1.13      barstow   514:             out.println("<hr/>");
1.1       barstow   515:             out.println("</BODY>");
                    516:             out.println("</HTML>");
                    517: 
                    518:         } catch (Exception e) {
1.2       barstow   519:             System.err.println("Exception: " + e.getMessage());
1.1       barstow   520:         }
                    521: 
                    522:     }
                    523: 
1.3       barstow   524:     /*
1.16      barstow   525:      * Given a URI string, open it, read its contents into a String
                    526:      * and return the String
                    527:      *
                    528:      *@param uri the URI to open
                    529:      *@return the content at the URI or null if any error occurs
                    530:      */
                    531:     private String getByteStream (String uri) {
                    532:         try {
                    533:             URL url = new URL(uri);
                    534:             InputStream is = url.openStream();
                    535:             String s = new String("");
                    536: 
                    537:             int c;
                    538:             int numRead = 0;
                    539: 
                    540:             while ((c = is.read()) != -1) {
                    541:                 s += (char)c;
                    542:                 if (numRead == 15) {
                    543:                     // A server could return content but not the RDF/XML that
                    544:                     // we need.  Check the beginning of s and if it looks like
                    545:                     // a generic HTML message, return an error.
                    546:                     if (s.startsWith("<!DOCTYPE HTML"))
                    547:                         return null;
                    548:                 }
                    549:                 numRead++;
                    550:             }
                    551: 
                    552:             if (s.equals(""))
                    553:                 // Nothing was returned 
                    554:                 return null;
                    555: 
                    556:             return s;
                    557: 
                    558:         } catch (Exception e) {
                    559:             return null;
                    560:         }
                    561:     }
                    562: 
                    563:     /*
1.3       barstow   564:      * Servlet's get info method
                    565:      */
1.1       barstow   566:     public String getServletInfo () {
                    567:        return "Servlet Wrapper for SiRPAC. This is revision " + REVISION;
                    568:     }
                    569: 
1.3       barstow   570:     /*
                    571:      * Servlet's init method
                    572:      *
                    573:      *@param config the servlet's configuration object
                    574:      */
1.1       barstow   575:     public void init(ServletConfig config) throws ServletException {
                    576:        super.init (config);
                    577: 
                    578:        m_sirpac = new SiRPAC();
                    579:         m_errorHandler = new ErrorStore();
1.3       barstow   580:         m_sirpac.setErrorHandler(m_errorHandler);
1.1       barstow   581: 
1.3       barstow   582:         // Cache the parameters
                    583:         m_SiRPACTmpDir = config.getInitParameter(SIRPAC_TMP_DIR);
1.5       barstow   584: 
                    585:         // All of the Graph Viz paths extend from GRAPH_VIZ_ROOT
                    586:         String GraphVizRoot = config.getInitParameter(GRAPH_VIZ_ROOT);
                    587: 
                    588:         m_GraphVizPath = GraphVizRoot + "/" + config.getInitParameter(GRAPH_VIZ_PATH);
                    589:         m_GraphVizFontDir = GraphVizRoot + "/" + config.getInitParameter(GRAPH_VIZ_FONT_DIR);
                    590:         m_GraphVizLibDir = GraphVizRoot + "/" + config.getInitParameter(GRAPH_VIZ_LIB_DIR);
1.1       barstow   591:     }
                    592: 
1.3       barstow   593:     /*
                    594:      * Servlet's destroy info method
                    595:      */
1.1       barstow   596:     public void destroy () {
                    597:        super.destroy ();
                    598:     }
                    599: 
1.3       barstow   600:     /*
1.4       barstow   601:      * Servlet's doGet info method - NOT supported
1.3       barstow   602:      *
                    603:      *@param req the request
                    604:      *@param res the response
                    605:      */
1.1       barstow   606:     public void doGet (HttpServletRequest req, HttpServletResponse res)
                    607:         throws ServletException, IOException {
1.3       barstow   608: 
1.1       barstow   609:        ServletOutputStream out = res.getOutputStream ();
                    610: 
                    611:        res.setContentType ("text/html");
                    612: 
1.3       barstow   613:        out.println ("<h1>GET is NOT supported!</h1>\n\n<p>Please send RDF through POST!</p>\n");
1.1       barstow   614:     }
                    615: 
1.3       barstow   616:     /*
                    617:      * Servlet's doPost method
                    618:      *
                    619:      *@param req the request
                    620:      *@param res the response
                    621:      */
1.1       barstow   622:     public void doPost (HttpServletRequest req, HttpServletResponse res)
                    623:         throws ServletException, IOException {
                    624: 
                    625:        ServletOutputStream out = res.getOutputStream ();
                    626: 
1.16      barstow   627:        String    sRDF        = req.getParameter (POST_TEXT);
                    628:        String    sBags       = req.getParameter (POST_BAG);
                    629:        String    sStreamMode = req.getParameter (POST_STREAM_MODE);
                    630:        String    sSaveRDF    = req.getParameter (POST_SAVE_RDF);
                    631:        String    sURI        = req.getParameter (POST_URI);
                    632: 
                    633:        InputSource   is = null;
                    634: 
                    635:         boolean       error = false;
                    636:         String        sError = null;
                    637: 
1.1       barstow   638:         SiRPACServletDumpConsumer    consumer = new SiRPACServletDumpConsumer();
1.9       barstow   639: 
                    640:         // Re-initialize the parser
                    641:        m_sirpac = new SiRPAC();
                    642:         m_errorHandler = new ErrorStore();
                    643:         m_sirpac.setErrorHandler(m_errorHandler);
1.1       barstow   644: 
1.16      barstow   645:         // If a URI was sent in the request, it takes precedence
                    646:         if (sURI != null && sURI.length() >= 1) {
                    647:             try {
                    648:                is  = GenericParser.getInputSource(sURI);
                    649:                 sRDF = getByteStream(sURI);
                    650:                 if (sRDF == null)
                    651:                     sError = "An attempt to load the RDF from URI '" + sURI + "' failed.  (The file may not exist or the server is down.)";
                    652:             } catch (MalformedURLException e) {
                    653:                 sError = "An attempt to load URI '" + sURI
                    654:                          + "' produced a MalforedURL Exception.\n["
                    655:                          + e.getMessage() + "]";
                    656:             } catch (IOException e) {
                    657:                 sError = "An attempt to load URI '" + sURI
                    658:                          + "' produced an IO Exception.\n["
                    659:                          + e.getMessage() + "]";
                    660:             }
                    661:         } else {
                    662:            StringReader  sr = new StringReader (sRDF);
                    663:            is = new InputSource (sr);
                    664:         }
                    665: 
                    666:         if (sError != null) {
                    667:             printDocumentHeader (out);
                    668:            out.println ("<h1>" + sError + "</h1>\n");
                    669:             printDocumentFooter(out, null);
                    670:             return;
                    671:         }
                    672: 
1.1       barstow   673:         printDocumentHeader (out);
1.16      barstow   674:         printListing (out, sRDF, sURI != null && sURI.length() >= 1);
1.17    ! barstow   675:         printTripleTableHeader (out);
1.1       barstow   676: 
                    677:        try {
1.3       barstow   678:             // Override the default triple output handler
1.1       barstow   679:             consumer.setOutputStream(out);
                    680: 
1.6       barstow   681:             // Toggle Bag handling - always false unless explicitly
                    682:             // included in the request
                    683:             m_sirpac.createBags (false);
1.1       barstow   684:            if (sBags != null && sBags.equals ("on"))
                    685:                m_sirpac.createBags (true);
1.10      barstow   686: 
                    687:             // Set parser's streaming mode
1.11      barstow   688:            if (sStreamMode != null && sStreamMode.equals ("on"))
1.10      barstow   689:                m_sirpac.setStreamMode (false);
1.1       barstow   690: 
                    691:             m_sirpac.parse(is, consumer);
                    692: 
1.17    ! barstow   693:             printTripleTableFooter(out, consumer);
1.12      barstow   694: 
1.14      barstow   695:             generateGraph(out, sRDF, req, (sSaveRDF != null) ? true : false);
1.2       barstow   696: 
1.1       barstow   697:        } catch (SAXException e) {
1.3       barstow   698:             error = true;
1.1       barstow   699:        } catch (Exception e) {
1.3       barstow   700:             error = true;
1.1       barstow   701:            e.printStackTrace ();
                    702:        }
                    703: 
                    704:        res.setContentType ("text/html");
1.3       barstow   705: 
                    706:        if (error) {
1.17    ! barstow   707:             printTripleTableFooter(out, null);
1.1       barstow   708:            out.println ("<h1>Errors during parsing</h1>\n");
                    709:             out.println ("<pre>\n");
1.2       barstow   710: 
                    711:             // Make the line number a link to the listing
1.1       barstow   712:             out.println ("Fatal error: " + m_errorHandler.getErrorMessage());
                    713:             out.println ("   (Line number = " + "<a href=\"#" + 
                    714:                          m_errorHandler.getLineNumber() + "\">" + 
                    715:                          m_errorHandler.getLineNumber() + "</a>" +
                    716:                          ", Column number = " + 
                    717:                          m_errorHandler.getColumnNumber() + ")");
                    718: 
                    719:            out.println ("</pre>\n\n");
                    720:        }
                    721: 
                    722:         printDocumentFooter(out, sRDF);
                    723:     }
                    724: }

Webmaster