/** * SiRPACServlet - Simple RDF Parser & Compiler Servlet wrapper * * Copyright © World Wide Web Consortium, (Massachusetts Institute of * Technology, Institut National de Recherche en Informatique et en * Automatique, Keio University). * * All Rights Reserved. * * Please see the full Copyright clause at * * * This servlet is a wrapper for the SiRPAC RDF parser. The servlet * expects two incoming variables through the POST method: * * 1. The RDF/XML document via the 'RDF' variable * 2. The checkbox status via the 'BAGS' variable (='on' when activated) * * @author Janne Saarela * * Major re-write to support AT&T GraphVis tool by Arthur Barstow * */ package org.w3c.rdf.examples; import java.io.*; import java.util.StringTokenizer; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import org.xml.sax.InputSource; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.helpers.*; import org.w3c.rdf.model.*; import org.w3c.rdf.syntax.*; import org.w3c.rdf.syntax.RDFConsumer; import org.w3c.rdf.util.xml.DumpConsumer; import org.w3c.rdf.util.xml.ErrorStore; import org.w3c.rdf.implementation.model.StatementImpl; import org.w3c.rdf.implementation.model.NodeFactoryImpl; import org.w3c.rdf.implementation.syntax.sirpac.*; public class SiRPACServlet extends HttpServlet { final static public String REVISION = "$Id: SiRPACServlet.java,v 1.3 2000/10/05 03:56:30 barstow Exp $"; // @@ private static final String MAIL_TO = "barstow@mediaone.net"; // Names of the servlet's parameters private static final String SIRPAC_TMP_DIR = "SIRPAC_TMP_DIR"; private static final String DOT_PATH = "DOT_PATH"; private static final String DOT_LIB_DIR = "DOT_LIB_DIR"; private static final String DOT_FONT_DIR = "DOT_FONT_DIR"; // Variables for the servlet's parameters private static String m_SiRPACTmpDir = null; private static String m_DotPath = null; private static String m_DotFontDir = null; private static String m_DotLibDir = null; // The parser private SiRPAC m_sirpac = null; // The error handler private ErrorStore m_errorHandler; /* * Create a temporary PrintWriter object * *@return a PrintWriter object if a temporary file is created; * null otherwise */ /* private String getTempFileName (PrintWriter pw) { } */ /* * Generate a graph of the RDF data model * *@param out *@param rdf *@param req */ private void generateGraph (ServletOutputStream out, String rdf, HttpServletRequest req) { try { out.println("
"); out.println("

Graph of the data model

"); // No need to continue if any of the parameters are missing if (m_SiRPACTmpDir == null || m_DotPath == null || m_DotFontDir == null || m_DotLibDir == null) { out.println("Servlet initialization failed. A graph cannot be generated."); return; } // Must generate a unique file name that the Dot consumer // will use File f; try { File d = new File(m_SiRPACTmpDir); f = File.createTempFile("sirpac_", ".dot", d); } catch (Exception e) { out.println("Failed to create a temporary file. A graph cannot be generated (" + e.getMessage() + ")."); return; } // Create a PrintWriter for the GraphViz consumer FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw); // Run the parser using the DOT consumer to capture // the output in a file StringReader sr = new StringReader (rdf); InputSource is = new InputSource (sr); GraphVizDumpConsumer consumer = new GraphVizDumpConsumer(pw); try { m_sirpac.parse(is, consumer); } catch (Exception e) { out.println("An attempt to generate the graph data failed (" + e.getMessage() + ")."); return; } // Pass the DOT data file to the GraphViz dot program // to create the GIF file String dotFileName = f.getAbsolutePath(); // Close the file pw.close(); // @@ Delete the DOT file // @@ Delete the GIF file out.println(""); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } /* * Search the given string for substring "key" * and if it is found, replace it with string "replacement" * *@return if no substitutions are done, input is returned; otherwise * a new string is returned. */ private String replaceString(String input, String key, String replacement) { StringBuffer sb = new StringBuffer(""); StringTokenizer st = new StringTokenizer(input, key); // Must handle the case where the input string begins with the key if (input.startsWith(key)) sb = sb.append(replacement); while (st.hasMoreTokens()) { sb = sb.append(st.nextToken()); if (st.hasMoreTokens()) sb = sb.append(replacement); } if (sb.length() >= 1) return sb.toString(); else return input; } /* * Print the document's header info * *@param out the servlet's output stream */ private void printDocumentHeader (ServletOutputStream out) { try { out.println(""); out.println(""); out.println("RDF creation"); out.println(""); out.println(""); out.println(""); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } /* * Print the rdf listing * *@param out the servlet's output stream *@param rdf the RDF code */ private void printListing (ServletOutputStream out, String rdf) { try { out.println("
"); out.println("

The original RDF/XML document

"); out.println("
");

            String s = replaceString(rdf, "<", "<");
            StringTokenizer st = new StringTokenizer(s, "\n");

            // Now output the RDF one line at a time with line numbers
            int lineNum = 1;
            while (st.hasMoreTokens()) {
                out.print ("" + lineNum +
                          ": " + st.nextToken());
                lineNum++;
            }

            out.println("
"); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } /* * Print the header for the triple listing * *@param out the servlet's output stream */ private void printTripleHeader (ServletOutputStream out) { try { out.println("
"); out.println("

Triples of the data model

"); // The output for each triple will be pre-formatted out.println("
");
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
        }
    }

    /*
     * Print the footer info for the triple listing
     *
     *@param out the servlet's output stream
     */
    private void printTripleFooter (ServletOutputStream out) {
        try {
            out.println("
"); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } /* * Print the document's footer info * *@param out the servlet's output stream *@param rdf the RDF code */ private void printDocumentFooter (ServletOutputStream out, String rdf) { try { out.println("
"); out.println("

Feedback

"); out.println("

If you suspect that SiRPAC produced an error, please enter an explanation below and then press the Submit problem report button, to mail the report (and listing) to " + MAIL_TO + "

"); out.println("
"); out.println(""); out.println("

"); // The listing is being passed as a parameter so the '<' // and '"' characters must be replaced with < and ", // respectively String s1 = replaceString(rdf, "<", "<"); String s2 = replaceString(s1, "\"", """); out.println(s2 + "\">"); out.println(""); out.println("

"); out.println("
Back to main page."); out.println(""); out.println(""); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } /* * Servlet's get info method */ public String getServletInfo () { return "Servlet Wrapper for SiRPAC. This is revision " + REVISION; } /* * Servlet's init method * *@param config the servlet's configuration object */ public void init(ServletConfig config) throws ServletException { super.init (config); m_sirpac = new SiRPAC(); m_errorHandler = new ErrorStore(); m_sirpac.setErrorHandler(m_errorHandler); // Cache the parameters m_SiRPACTmpDir = config.getInitParameter(SIRPAC_TMP_DIR); m_DotPath = config.getInitParameter(DOT_PATH); m_DotFontDir = config.getInitParameter(DOT_FONT_DIR); m_DotLibDir = config.getInitParameter(DOT_LIB_DIR); } /* * Servlet's destroy info method */ public void destroy () { super.destroy (); } /* * Servlet's doGet info method * *@param req the request *@param res the response */ public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream (); res.setContentType ("text/html"); out.println ("

GET is NOT supported!

\n\n

Please send RDF through POST!

\n"); } /* * Servlet's doPost method * *@param req the request *@param res the response */ public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream out = res.getOutputStream (); String sRDF = req.getParameter ("RDF"); String sBags = req.getParameter ("BAGS"); StringReader sr = new StringReader (sRDF); InputSource is = new InputSource (sr); boolean error = false; SiRPACServletDumpConsumer consumer = new SiRPACServletDumpConsumer(); printDocumentHeader (out); printListing (out, sRDF); printTripleHeader (out); try { // Override the default triple output handler consumer.setOutputStream(out); if (sBags != null && sBags.equals ("on")) m_sirpac.createBags (true); m_sirpac.parse(is, consumer); generateGraph(out, sRDF, req); } catch (SAXException e) { error = true; } catch (Exception e) { error = true; e.printStackTrace (); } printTripleFooter(out); res.setContentType ("text/html"); if (error) { out.println ("

Errors during parsing

\n"); out.println ("
\n");

            // Make the line number a link to the listing
            out.println ("Fatal error: " + m_errorHandler.getErrorMessage());
            out.println ("   (Line number = " + "" + 
                         m_errorHandler.getLineNumber() + "" +
                         ", Column number = " + 
                         m_errorHandler.getColumnNumber() + ")");

	    out.println ("
\n\n"); } printDocumentFooter(out, sRDF); } }