]> matita.cs.unibo.it Git - helm.git/blob - helm/uwobo/src/ocaml/uwobo.ml
334255b408e69d60414908bbdeb51dd442c010ef
[helm.git] / helm / uwobo / src / ocaml / uwobo.ml
1
2 (* Copyright (C) 2002, HELM Team.
3  * 
4  * This file is part of HELM, an Hypertextual, Electronic
5  * Library of Mathematics, developed at the Computer Science
6  * Department, University of Bologna, Italy.
7  * 
8  * HELM is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  * 
13  * HELM is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with HELM; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  * MA  02111-1307, USA.
22  * 
23  * For details, see the HELM World-Wide-Web page,
24  * http://cs.unibo.it/helm/.
25  *)
26
27 open Printf;;
28 open Uwobo_common;;
29
30  (* debugging settings *)
31 let debug = true;;
32 let debug_level = `Debug;;
33 let debug_print s = if debug then prerr_endline s;;
34 let http_debug = false;;
35 Http_common.debug := http_debug;;
36
37   (* environment settings *)
38 let daemon_name = "UWOBO OCaml";;
39 let default_port = 8082;;
40 let port_env_var = "UWOBO_PORT";;
41 let port =
42   try
43     int_of_string (Sys.getenv port_env_var)
44   with
45   | Not_found -> default_port
46   | Failure "int_of_string" ->
47       prerr_endline "Warning: invalid port, reverting to default";
48       default_port
49 in
50
51   (* facilities *)
52 let pp_error = sprintf "<html><body><h1>Error: %s</h1></body></html>" in
53 let invocation_error msg outchan =
54   (* return an ok (200) http response, which display in html an invocation error
55   message *)
56   Http_daemon.respond ~body:(pp_error msg) outchan
57 in
58 let bad_request body outchan =  (* return a bad request http response *)
59   Http_daemon.respond_error ~status:(`Client_error `Bad_request) ~body outchan
60 in
61
62   (* values common to all threads *)
63 let syslogger = new Uwobo_logger.sysLogger ~level:debug_level () in
64 syslogger#enable;
65 let styles = new Uwobo_styles.styles in
66 let usage_string = "Help message: not yet written!!" in (* TODO *)
67
68   (* thread action *)
69 let callback req outchan =
70     (* perform an 'action' that can be applied to a list of keys or, if no
71     keys was given, to all keys *)
72   let act_on_keys req styles outchan per_key_action all_keys_action logmsg =
73     let log = new Uwobo_logger.processingLogger () in
74     let keys =
75       try
76         Pcre.split ~pat:"," (req#param "keys")
77       with Http_request.Param_not_found _ -> []
78     in
79     (match keys with
80     | [] -> (* no key provided, act on all stylesheets *)
81         log#log "reloading all stylesheets ...";
82         (try all_keys_action () with e -> log#log (Printexc.to_string e))
83     | keys ->
84         List.iter
85           (fun key -> (* act on a single stylesheet *)
86             log#log (sprintf "%s stylesheet %s" logmsg key);
87             (try per_key_action key with e -> log#log (Printexc.to_string e)))
88           keys);
89     Http_daemon.respond ~body:log#asHtml outchan
90   in
91   let parse_apply_params =  (* parse parameters for '/apply' action *)
92     let is_global_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){1}$" x in
93     let is_local_param x = Pcre.pmatch ~pat:"^param(\\.[^.]+){2}$" x in
94     let is_property x = Pcre.pmatch ~pat:"^prop\\.[^.]+$" x in
95     List.fold_left
96       (fun (old_params, old_properties) (name, value) ->
97         match name with
98         | name when is_global_param name ->
99             let name = Pcre.replace ~pat:"^param\\." name in
100             ((fun x -> (old_params x) @ [name, value]), old_properties)
101         | name when is_local_param name ->
102             let pieces = Pcre.extract ~pat:"^param\\.([^.]+)\\.(.*)" name in
103             let (key, name) = (pieces.(1), pieces.(2)) in
104             ((function
105               | x when x = key -> [name, value] @ (old_params x)
106               | x -> old_params x),
107              old_properties)
108         | name when is_property name ->
109             let name = Pcre.replace ~pat:"^prop\\." name in
110             (old_params, ((name, value) :: old_properties))
111         | _ -> (old_params, old_properties))
112       ((fun _ -> []), []) (* no parameters, no properties *)
113   in
114   try
115     syslogger#log `Debug (sprintf "Received request: %s" req#path);
116     (match req#path with
117     | "/add" ->
118         (let bindings = req#paramAll "bind" in
119         if bindings = [] then
120           invocation_error "No [key,stylesheet] binding provided" outchan
121         else begin
122           let log = new Uwobo_logger.processingLogger () in
123           List.iter
124             (fun binding -> (* add a <key, stylesheet> binding *)
125               let pieces = Pcre.split ~pat:"," binding in
126               match pieces with
127               | [key; style] ->
128                   log#log (sprintf "adding binding <%s,%s>" key style);
129                   (try
130                     styles#add key style;
131                   with e ->
132                     log#log (Printexc.to_string e))
133               | _ -> log#log (sprintf "invalid binding %s" binding))
134             bindings;
135           Http_daemon.respond ~body:log#asHtml outchan
136         end)
137     | "/list" ->
138         (let log = new Uwobo_logger.processingLogger () in
139         log#log "Stylesheet list:";
140         List.iter (fun s -> log#log s) styles#list;
141         Http_daemon.respond ~body:log#asHtml outchan)
142     | "/remove" ->
143         act_on_keys
144           req styles outchan
145           styles#remove (fun () -> styles#removeAll) "removing"
146     | "/reload" ->
147         act_on_keys
148           req styles outchan
149           styles#reload (fun () -> styles#reloadAll) "reloading"
150
151     | "/apply" ->
152         (let logger = new Uwobo_logger.processingLogger () in
153         let xmluri = req#param "xmluri" in
154         let keys = Pcre.split ~pat:"," (req#param "keys") in
155         (* notation: "local" parameters are those defined on a per-stylesheet
156         pasis (i.e. param.key.param=value), "global" parameters are those
157         defined for all stylesheets (i.e. param.param=value) *)
158         let (params, props) = parse_apply_params req#params in
159         syslogger#log `Debug (sprintf "Parsing input document %s ..." xmluri);
160         let domImpl = Gdome.domImplementation () in
161         let input = domImpl#createDocumentFromURI ~uri:xmluri () in
162         let output =
163           Uwobo_engine.apply ~logger ~styles ~keys ~input ~params ~props
164           (* TODO uhm ... what to do if Uwobo_failure is raised? *)
165         in
166         syslogger#log `Debug logger#asText;
167         let tempfile = (* temporary file on which save XML output *)
168           (* TODO I don't need a tempfile, but gdome seems not to permit to
169           return the string representation of a Gdome.document *)
170           let inchan = Unix.open_process_in "tempfile --prefix=uwobo" in
171           let name = input_line inchan in
172           close_in inchan;
173           name
174         in
175         syslogger#log
176           `Debug
177           (sprintf "saving output document to %s ..." tempfile);
178         let res = domImpl#saveDocumentToFile ~doc:output ~name:tempfile () in
179         if not res then
180           raise (Uwobo_failure ("unable to save output to file " ^ tempfile));
181         syslogger#log `Debug "sending output to client ....";
182         Http_daemon.send_basic_headers ~code:200 outchan;
183         (* TODO set Content-Type *)
184         Http_daemon.send_CRLF outchan;
185         Http_daemon.send_file ~name:tempfile outchan;
186         Unix.unlink tempfile)
187     | "/help" -> Http_daemon.respond ~body:usage_string outchan
188     | invalid_request ->
189         Http_daemon.respond_error ~status:(`Client_error `Bad_request) outchan)
190   with
191   | Http_request.Param_not_found attr_name ->
192       bad_request (sprintf "Parameter '%s' is missing" attr_name) outchan
193   | exc ->
194       Http_daemon.respond
195         ~body:(pp_error ("Uncaught exception: " ^ (Printexc.to_string exc)))
196         outchan
197 in
198
199   (* daemon initialization *)
200 syslogger#log
201   `Notice
202   (sprintf "%s started and listening on port %d" daemon_name port);
203 syslogger#log `Notice (sprintf "current directory is %s" (Sys.getcwd ()));
204 Http_daemon.start' ~port ~mode:`Thread callback;
205 syslogger#log `Notice (sprintf "%s is terminating, bye!" daemon_name)
206