001: /*
002: * Created on 23 avr. 2004 by the Message Center Team
003: *
004: */
005: package mc.formgenerator.servlets;
006:
007: import mc.formgenerator.servlets.bonita.RepositoryFacade;
008: import mc.formgenerator.servlets.util.*;
009:
010: import hero.interfaces.*;
011: import hero.util.HeroException;
012:
013: import java.io.BufferedOutputStream;
014: import java.io.ByteArrayInputStream;
015: import java.io.ByteArrayOutputStream;
016: import java.io.File;
017: import java.io.FileNotFoundException;
018: import java.io.FileOutputStream;
019: import java.io.IOException;
020: import java.io.InputStream;
021: import java.io.OutputStream;
022: import java.io.PrintWriter;
023: import java.net.MalformedURLException;
024: import java.net.URISyntaxException;
025: import java.rmi.RemoteException;
026: import java.util.Enumeration;
027: import java.util.HashMap;
028: import java.util.Iterator;
029: import java.util.Map;
030: import java.util.StringTokenizer;
031:
032: import javax.ejb.CreateException;
033: import javax.naming.NamingException;
034: import javax.security.auth.login.LoginException;
035: import javax.servlet.ServletConfig;
036: import javax.servlet.ServletException;
037: import javax.servlet.http.HttpServlet;
038: import javax.servlet.http.HttpServletRequest;
039: import javax.servlet.http.HttpServletResponse;
040: import javax.servlet.http.HttpSession;
041: import javax.xml.parsers.DocumentBuilder;
042: import javax.xml.parsers.DocumentBuilderFactory;
043: import javax.xml.parsers.ParserConfigurationException;
044: import javax.xml.transform.TransformerConfigurationException;
045: import javax.xml.transform.TransformerException;
046:
047: import org.w3c.dom.DOMImplementation;
048: import org.w3c.dom.Document;
049: import org.w3c.dom.Element;
050: import org.w3c.dom.Node;
051: import org.w3c.dom.NodeList;
052: import org.w3c.dom.Text;
053: import org.xml.sax.SAXException;
054:
055: import mc.formgenerator.bonita.BonitaActivityAdapter;
056: import mc.formgenerator.bonita.BonitaActivityExecutor;
057: import mc.formgenerator.bonita.BonitaProjectAdapter;
058: import mc.formgenerator.bonita.BonitaProjectExecutor;
059: import mc.formgenerator.bonita.DocumentParser;
060:
061: import org.apache.log4j.Category;
062: import org.apache.xerces.dom.DOMImplementationImpl;
063: import org.apache.xml.serialize.OutputFormat;
064: import org.apache.xml.serialize.XMLSerializer;
065: import org.chiba.xml.xforms.Model;
066: import org.chiba.xml.xforms.config.Config;
067: import org.chiba.xml.xforms.exception.XFormsException;
068: import org.chiba.adapter.ChibaAdapter;
069:
070: /**
071: * Servlet that will display XForm Look&Feel, without interaction with Bonita.
072: * This servlet is a modification of ChibaServlet
073: */
074: public class ServletLookAndFeel extends HttpServlet {
075:
076: //ServletAdapter instance
077: private ServletAdapter servletAdapter = null;
078:
079: //Allow us to know if we are working with an activity or a project
080: private Boolean isActivity;
081:
082: //Name of the project we are working with
083: private String projectName = null;
084:
085: //Name of the project version we are working with
086: private String projectVersion = null;
087:
088: //Name of the activity we are working with
089: private String activityName = null;
090:
091: //Application mode consumer or exploitant
092: private String mode = null;
093:
094: //forward URL
095: private String forward = null;
096:
097: //init-params
098: private static Category cat = Category
099: .getInstance(ServletLookAndFeel.class);
100: //private static final String FORM_PARAM_NAME = "form";
101: private static final String XSL_PARAM_NAME = "xslt";
102: private static final String CSS_PARAM_NAME = "css";
103: private static final String ACTIONURL_PARAM_NAME = "action_url";
104:
105: /*
106: * It is not thread safe to modify these variables once the
107: * init(ServletConfig) method has been called
108: */
109: // the absolute path to the Chiba config-file
110: private String configPath = null;
111:
112: // the rootdir of this app; forms + documents fill be searched under this root
113: private String contextRoot = null;
114:
115: // where uploaded files are stored
116: private String uploadDir = null;
117:
118: private String stylesPath = null;
119:
120: /**
121: * Returns a short description of the servlet.
122: *
123: * @return - Returns a short description of the servlet.
124: */
125: public String getServletInfo() {
126: return "Servlet Controller for Chiba Bonita's XForms Processor";
127: }
128:
129: /**
130: * Destroys the servlet.
131: */
132: public void destroy() {
133: }
134:
135: /**
136: * Start the server side interpretation of the xforms document
137: * @param document the xforms document we have to interprete
138: * @param writer the servlet's writer
139: */
140: private void xformProcessing(PrintWriter writer,
141: HttpServletRequest request, String actionURL,
142: HttpSession session)
143: throws TransformerConfigurationException, XFormsException,
144: FileNotFoundException, TransformerException, IOException,
145: URISyntaxException {
146:
147: //We must get bonita project name
148: this .projectName = request.getParameter("projectName");
149:
150: //We must get bonita project version name
151: this .projectVersion = request.getParameter("projectVersion");
152:
153: //We must get bonita activity name eventually
154: this .activityName = request.getParameter("activityName");
155:
156: if ((this .activityName == null)
157: || (this .activityName.equals(""))) {
158: this .isActivity = new Boolean(false);
159: } else {
160: this .isActivity = new Boolean(true);
161: }
162:
163: //hostUrl needed by ui.xsl
164: String hostUrl = request.getScheme() + "://"
165: + request.getServerName() + ":"
166: + request.getServerPort();
167:
168: //xmlBase needed by Chiba
169: String xmlBase = request.getScheme() + "://"
170: + request.getServerName() + ":"
171: + request.getServerPort() + request.getContextPath()
172: + "/";
173: Document xformDocument = null;
174: Document langInstance = null;
175: Document instance = null;
176:
177: String xslFile = request.getParameter(XSL_PARAM_NAME);
178:
179: String css = request.getParameter(CSS_PARAM_NAME);
180: if (css == null) {
181: css = "web/styles/admin.css";
182: }
183:
184: String realProjectName = this .projectName.replaceFirst(
185: "_instance.+", "");
186:
187: String formPath = null;
188:
189: //instantiate RepositoryFacade to get form path (if exist)
190: RepositoryFacade repositoryFacade = new RepositoryFacade(
191: getServletConfig().getServletContext().getRealPath("")
192: + File.separator + "web" + File.separator
193: + "repository.xml");
194:
195: if (repositoryFacade == null) {
196: //Exception
197: throw new IOException(
198: "Invalid session - Cannot retrieve repositoryFacade");
199: }
200:
201: if (this .isActivity.booleanValue() == true) {
202: //System.out.println("WORKING WITH ACTIVITY");
203: formPath = repositoryFacade.getActivityFormPath(
204: realProjectName, this .activityName,
205: this .projectVersion);
206: } else {
207: //System.out.println("WORKING WITH PROJECT: " + realProjectName);
208: formPath = repositoryFacade.getProjectFormPath(
209: realProjectName, this .projectVersion);
210: }
211:
212: if (formPath != null) {
213: //xform file exist
214:
215: //get file and parse it to xmlDocument
216: String realFormPath = getServletConfig()
217: .getServletContext().getRealPath("")
218: + formPath;
219: xformDocument = getDocument(realFormPath);
220: //set xmlbase
221: Element xformRoot = xformDocument.getDocumentElement();
222: xformRoot.setAttribute("xml:base", xmlBase);
223:
224: //lookup languages and create language instance
225: String languagePath = null;
226: if (this .isActivity.booleanValue() == true) {
227: //We are working with an activity
228: languagePath = getServletConfig().getServletContext()
229: .getRealPath("")
230: + File.separator
231: + "web"
232: + File.separator
233: + "xforms"
234: + File.separator
235: + realProjectName
236: + File.separator
237: + this .projectVersion
238: + File.separator
239: + this .activityName
240: + File.separator;
241: } else {
242: //We are working with a project
243: languagePath = getServletConfig().getServletContext()
244: .getRealPath("")
245: + File.separator
246: + "web"
247: + File.separator
248: + "xforms"
249: + File.separator
250: + realProjectName
251: + File.separator
252: + this .projectVersion
253: + File.separator;
254: }
255:
256: String languages = request.getHeader("Accept-Language");
257: String userLanguage = "en";
258: if ((languages != null) && (!languages.equals(""))) {
259: userLanguage = getUserLanguage(languages, languagePath);
260: }
261:
262: langInstance = getDocument(languagePath + userLanguage
263: + ".xml");
264:
265: instance = getDocument(languagePath + "instance.xml");
266: //xformDocument = getDocument(realFormPath);
267:
268: //this.servletAdapter = setupServletAdapter(actionURL, session, formPath, xslFile, css);
269: this .servletAdapter = setupServletAdapter(actionURL,
270: hostUrl, session, xformDocument, realFormPath,
271: xslFile, css);
272:
273: } else {
274: //xform file does not exist. Generate xform document
275: System.out
276: .println("ERROR: XForm file does not exist in repository");
277: }
278:
279: //Chiba launching
280: //Build HTML page according to an activity or a project we are working with
281: try {
282: //System.out.println("INSTANCE: " + toString(instance));
283: //System.out.println("XFORM DOCUMENT: " + toString(xformDocument));
284: //if (langInstance!=null) System.out.println("LANG INSTANCE: " + toString(langInstance));
285: if (formPath != null) {
286: updateContext(request, session, instance, langInstance);
287: } else {
288: System.out
289: .println("ERROR: XForm file does not exist in repository");
290: }
291:
292: //add all request params that are not used by this servlet to the context map in ChibaBean
293: storeContextParams(request);
294: this .servletAdapter.init();
295: //this.servletAdapter.executeHandler();
296: this .servletAdapter.dispatch(null);
297: this .servletAdapter.buildUI(writer);
298: } catch (Exception e) {
299: //Error
300: e.printStackTrace();
301: }
302: }
303:
304: /**
305: * Initializes the servlet.
306: *
307: * @param config - the ServletConfig object
308: * @throws javax.servlet.ServletException
309: */
310: public void init(ServletConfig config) throws ServletException {
311: super .init(config);
312:
313: //cat.info("--------------- initing ChibaView... ---------------");
314: //read some params from web-inf
315: contextRoot = getServletConfig().getServletContext()
316: .getRealPath("");
317: if (contextRoot == null)
318: contextRoot = getServletConfig().getServletContext()
319: .getRealPath(".");
320:
321: //get the relative path to the chiba config-file
322: String path = getServletConfig().getInitParameter(
323: "chiba.config");
324:
325: //get the real path for the config-file
326: if (path != null) {
327: configPath = getServletConfig().getServletContext()
328: .getRealPath(path);
329: }
330:
331: //get the path for the stylesheets
332: //path = getServletConfig().getServletContext().getInitParameter("chiba.xforms.stylesPath");
333: path = getServletConfig().getInitParameter(
334: "chiba.xforms.stylesPath");
335:
336: //get the real path for the stylesheets and configure a new StylesheetLoader with it
337: if (path != null) {
338: stylesPath = getServletConfig().getServletContext()
339: .getRealPath(path);
340: //cat.info("stylesPath: " + stylesPath);
341: }
342:
343: //uploadDir = contextRoot + "/" + getServletConfig().getServletContext().getInitParameter("chiba.upload");
344: //uploadDir = getServletConfig().getServletContext().getInitParameter("chiba.upload");
345: uploadDir = getServletConfig().getInitParameter("chiba.upload");
346: //Security constraint
347: if (uploadDir != null) {
348: if (uploadDir.toUpperCase().indexOf("WEB-INF") >= 0) {
349: throw new ServletException(
350: "Chiba security constraint: uploadDir '"
351: + uploadDir + "' not allowed");
352: }
353: }
354: }
355:
356: /**
357: * Servlet reaction on get method:
358: * Display the form generated for filling a valid XML file
359: */
360: protected void doGet(HttpServletRequest request,
361: HttpServletResponse response) throws IOException {
362:
363: this .servletAdapter = null;
364:
365: //set the content-type and character encoding for request and response
366: response.setContentType("text/html; charset="
367: + FormGeneratorConstant.CHARACTER_ENCODING);
368: request
369: .setCharacterEncoding(FormGeneratorConstant.CHARACTER_ENCODING);
370:
371: //Creating a session
372: HttpSession session = request.getSession(true);
373:
374: // get the user language
375: String userLanguage = request.getHeader("Accept-Language");
376:
377: //write the 'forward' parameter in the session
378: if (request.getParameter("forward") != null)
379: session.setAttribute("formgenerator.forward", request
380: .getParameter("forward"));
381: else
382: session.removeAttribute("forward");
383:
384: try {
385: //Getting the writer
386: PrintWriter out = response.getWriter();
387:
388: // build actionURL where forms are submitted to
389: String actionURL = getActionURL(request, response);
390:
391: //Build HTML page according to an activity or a project we are working with
392: //writingUI(out, request, response, actionURL, session);
393: xformProcessing(out, request, actionURL, session);
394:
395: //Stores the state of isActivity attribute in the session
396: session.setAttribute("formgenerator.isActivity",
397: this .isActivity);
398:
399: //Stores the projectname in the session
400: session.setAttribute("formgenerator.projectName",
401: this .projectName);
402:
403: //Stores the project version in the session
404: session.setAttribute("formgenerator.projectVersion",
405: this .projectVersion);
406:
407: //Stores the activity name in the session
408: session.setAttribute("formgenerator.activityName",
409: this .activityName);
410:
411: //Stores the application mode in the session
412: //session.setAttribute("formgenerator.mode", this.mode);
413:
414: //Stores the servletAdapter
415: session.setAttribute("formgenerator.sAdapter",
416: this .servletAdapter);
417:
418: //Closing writer
419: out.close();
420:
421: } catch (Exception e) {
422: //Error
423: e.printStackTrace();
424: }
425: }
426:
427: /**
428: * this method is responsible for passing all context information needed by the Adapter and Processor from
429: * ServletRequest to ChibaContext.
430: *
431: * @param servletAdapter the ChibaAdapter to use
432: * @param request the ServletRequest
433: * @param session the ServletSession
434: */
435: protected void updateContext(HttpServletRequest request,
436: HttpSession session, Document instance,
437: Document langDocument) {
438: this .servletAdapter.setContextProperty(
439: ServletAdapter.USERAGENT, request
440: .getHeader("User-Agent"));
441: this .servletAdapter.setContextProperty(
442: ServletAdapter.HTTP_SERVLET_REQUEST, request);
443: this .servletAdapter.setContextProperty(
444: ServletAdapter.HTTP_SESSION_OBJECT, session);
445: this .servletAdapter.setContextProperty("instance", instance);
446: this .servletAdapter.setContextProperty("lang", langDocument);
447: }
448:
449: /**
450: * Servlet reaction on post method:
451: * Submit information from user
452: */
453: protected void doPost(HttpServletRequest request,
454: HttpServletResponse response) throws ServletException,
455: IOException {
456: //Getting the current session
457: HttpSession session = request.getSession(true);
458: this .servletAdapter = null;
459:
460: try {
461: //set the content-type and character encoding for request and response
462: response.setContentType("text/html; charset="
463: + FormGeneratorConstant.CHARACTER_ENCODING);
464: request
465: .setCharacterEncoding(FormGeneratorConstant.CHARACTER_ENCODING);
466:
467: //Getting servletAdapter from the session
468: this .servletAdapter = (ServletAdapter) session
469: .getAttribute("formgenerator.sAdapter");
470:
471: //Getting isActivity from the session
472: this .isActivity = (Boolean) session
473: .getAttribute("formgenerator.isActivity");
474: //Set isActivity in the session
475: session.setAttribute("formgenerator.isActivity",
476: this .isActivity);
477:
478: //Getting projectName from the session
479: this .projectName = (String) session
480: .getAttribute("formgenerator.projectName");
481: //Set the projectname in the session
482: session.setAttribute("formgenerator.projectName",
483: this .projectName);
484:
485: //Getting projectVersion from the session
486: projectVersion = (String) session
487: .getAttribute("formgenerator.projectVersion");
488: //Set the projectversion in the session
489: session.setAttribute("formgenerator.projectVersion",
490: projectVersion);
491:
492: //Getting activityName from the session
493: this .activityName = (String) session
494: .getAttribute("formgenerator.activityName");
495: //Set the activityname in the session
496: session.setAttribute("formgenerator.activityName",
497: this .activityName);
498:
499: //Getting mode from the session
500: //this.mode = (String)session.getAttribute("formgenerator.mode");
501:
502: //Getting forward from the session
503: this .forward = (String) session
504: .getAttribute("formgenerator.forward");
505:
506: //Set isActivity in the session
507: session.setAttribute("formgenerator.forward", this .forward);
508:
509: if ((this .servletAdapter == null)
510: || (this .isActivity == null)
511: || (this .projectName == null)) {
512: //Exception
513: throw new IOException(
514: "Invalid session - Cannot retrieve servletAdapter or ggf or isActivity or projectName in the session");
515: }
516:
517: updateContextPost(request, session);
518:
519: //this.servletAdapter.executeHandler();
520: this .servletAdapter.dispatch(null);
521:
522: // handle setRedirect <xforms:load show='replace'/>
523: // and redirect from submission as well
524: // NOTE - this needs to be checked *before* the this.getForwardMap()
525: // as a submission handler may force a redirect
526: if (this .servletAdapter.getRedirectUri() != null) {
527: String redirectTo = this .servletAdapter
528: .getRedirectUri();
529: // todo: remove from session ?
530: // shutdown processor
531: this .servletAdapter.getChibaBean().shutdown();
532:
533: // send redirect (after encoding session id if required)
534: response.sendRedirect(response
535: .encodeRedirectURL(redirectTo));
536:
537: // remove redirect uri and terminate
538: this .servletAdapter.setRedirect(null);
539: return;
540: }
541:
542: // handle forward <xforms:submission replace='all'/>
543: Map forwardMap = this .servletAdapter.getForwardMap();
544: InputStream forwardStream = (InputStream) forwardMap
545: .get(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);
546: if (forwardStream != null) {
547: //get instance filled
548: //Document filledDocument = (Document)this.servletAdapter.getChibaBean().getContainer().getModel("model").getInstance("instance").getInstanceDocument();
549: Model model = (Model) this .servletAdapter
550: .getChibaBean().lookup("model");
551: Document filledDocument = (Document) model.getInstance(
552: "instance").getInstanceDocument();
553:
554: if (filledDocument == null) {
555: throw new ServletException(Config.getInstance()
556: .getErrorMessage("session-invalid"));
557: }
558:
559: //Calling the executor
560: //this.callExecutor(filledDocument);
561:
562: //redirect
563: /*
564: if ((this.forward!=null)&&!this.forward.equals("")){
565: //redirection to forward
566: response.sendRedirect(this.forward);
567: }else{
568: if(this.isActivity.booleanValue() == true){
569:
570: if(this.mode.equals("consumer"))
571: //Redirection to todo list
572: response.sendRedirect("/formgenerator/ServletActivityToDoList?projectName=" + projectName);
573: else
574: //Redirection to work list
575: response.sendRedirect("/formgenerator/ServletWorkList");
576: }
577: else{
578: if(this.mode.equals("consumer"))
579: //Redirection to instances projets
580: response.sendRedirect("/formgenerator/ServletInstancesProjects");
581: else
582: //Redirection to work list
583: response.sendRedirect("/formgenerator/ServletWorkList");
584: }
585: }
586: */
587: /*
588: // todo: remove from session ?
589: // shutdown processor
590: this.servletAdapter.getChibaBean().shutdown();
591:
592: // forward submission response
593: forwardResponse(forwardMap, response);
594:
595: // remove forward response and terminate
596: this.servletAdapter.forward(null);
597: return;
598: */
599: }
600:
601: //Set content type
602: //response.setContentType("text/html");
603:
604: //Render result to output
605: //this.chiba.runChiba(out);
606: this .servletAdapter.buildUI(response.getWriter());
607: response.getWriter().close();
608:
609: } catch (Exception e) {
610: //Error
611: e.printStackTrace();
612: }
613: }
614:
615: /**
616: * this method is responsible for passing all context information needed by the Adapter and Processor from
617: * ServletRequest to ChibaContext.
618: *
619: * @param servletAdapter the ChibaAdapter to use
620: * @param request the ServletRequest
621: * @param session the ServletSession
622: */
623: protected void updateContextPost(HttpServletRequest request,
624: HttpSession session) {
625: this .servletAdapter.setContextProperty(
626: ServletAdapter.USERAGENT, request
627: .getHeader("User-Agent"));
628: this .servletAdapter.setContextProperty(
629: ServletAdapter.HTTP_SERVLET_REQUEST, request);
630: this .servletAdapter.setContextProperty(
631: ServletAdapter.HTTP_SESSION_OBJECT, session);
632: }
633:
634: /**
635: * creates and configures the ServletAdapter which does the actual request processing.
636: *
637: * @param actionURL - the URL to submit to
638: * @param session - the Servlet session
639: * @param formPath - the relative location where forms are stored
640: * @param xslFile - the xsl file to use for transform
641: * @param cssFile - the CSS file to use for styling the output
642: * @return ServletAdapter
643: */
644: private ServletAdapter setupServletAdapter(String actionURL,
645: String hostUrl, HttpSession session, Document formDocument,
646: String baseURI, String xslFile, String cssFile)
647: throws XFormsException, URISyntaxException {
648: //setup and configure the adapter
649: ServletAdapter aAdapter = new ServletAdapter();
650: aAdapter.setContextRoot(contextRoot);
651: if ((configPath != null) && !(configPath.equals(""))) {
652: aAdapter.setConfigPath(configPath);
653: }
654:
655: //call getDocumentFromString to get a valid Chiba Document
656: try {
657: formDocument = getDocumentFromString(toString(formDocument));
658: } catch (Exception e) {
659: e.printStackTrace();
660: }
661:
662: //aAdapter.setFormURI(new URI(this.contextRoot));
663: aAdapter.setXFormsURI(this .contextRoot);
664: //aAdapter.setFormDocument(formDocument);
665: aAdapter.setXForms(formDocument);
666: aAdapter.setStylesheetPath(stylesPath);
667: aAdapter.setActionUrl(actionURL);
668: aAdapter.setUploadDir(uploadDir);
669: aAdapter.setHostUrl(hostUrl);
670:
671: if (xslFile != null) {
672: aAdapter.setStylesheet(xslFile);
673: if (cat.isDebugEnabled()) {
674: cat.debug("using xsl stylesheet: " + xslFile);
675: }
676: }
677: if (cssFile != null) {
678: aAdapter.setCSS(cssFile);
679: if (cat.isDebugEnabled()) {
680: cat.debug("using css stylesheet: " + cssFile);
681: }
682: }
683:
684: Map servletMap = new HashMap();
685: servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
686: aAdapter.setContextProperty(ChibaAdapter.SUBMISSION_RESPONSE,
687: servletMap);
688:
689: return aAdapter;
690: }
691:
692: private void storeContextParams(HttpServletRequest request) {
693: Enumeration params = request.getParameterNames();
694: String s;
695: while (params.hasMoreElements()) {
696: s = (String) params.nextElement();
697: //store all request-params we don't use in the context map of ChibaBean
698: if (!(s.equals(XSL_PARAM_NAME) || s.equals(CSS_PARAM_NAME) || s
699: .equals(ACTIONURL_PARAM_NAME))) {
700: String value = request.getParameter(s);
701: this .servletAdapter.setContextProperty(s, value);
702: if (cat.isDebugEnabled()) {
703: cat.debug("added request param '" + s
704: + "' added to context");
705: }
706: }
707: }
708: }
709:
710: /**
711: * Return the action URL with jsession
712: * @param request : The request from user
713: * @param response : The response to its request
714: * @return a String object that represents the action URL
715: */
716: private String getActionURL(HttpServletRequest request,
717: HttpServletResponse response) {
718: String defaultActionURL = request.getScheme() + "://"
719: + request.getServerName() + ":"
720: + request.getServerPort() + request.getContextPath()
721: + request.getServletPath();
722: String encodedDefaultActionURL = response
723: .encodeURL(defaultActionURL);
724: int sessIdx = encodedDefaultActionURL.indexOf(";jsession");
725: String sessionId = null;
726: if (sessIdx > -1) {
727: sessionId = encodedDefaultActionURL.substring(sessIdx);
728: }
729: String actionURL = request.getParameter(ACTIONURL_PARAM_NAME);
730: if (null == actionURL) {
731: actionURL = encodedDefaultActionURL;
732: } else if (null != sessionId) {
733: actionURL += sessionId;
734: }
735:
736: //cat.info("actionURL: " + actionURL);
737: // encode the URL to allow for session id rewriting
738: actionURL = response.encodeURL(actionURL);
739: return actionURL;
740: }
741:
742: private Document getDocument(String path) {
743:
744: //DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
745: DocumentBuilderFactory factory = DocumentBuilderFactory
746: .newInstance();
747: factory.setNamespaceAware(true);
748: factory.setValidating(false);
749: factory
750: .setAttribute(
751: "http://apache.org/xml/properties/dom/document-class-name",
752: "org.chiba.xml.xforms.XFormsDocument");
753:
754: Document document = null;
755: try {
756: //get file and parse it to xmlDocument
757: File xmlFile = new File(path);
758: DocumentBuilder documentBuilder = factory
759: .newDocumentBuilder();
760: document = documentBuilder.parse(xmlFile);
761: } catch (SAXException e) {
762: e.printStackTrace();
763: } catch (IOException e) {
764: e.printStackTrace();
765: } catch (ParserConfigurationException e) {
766: e.printStackTrace();
767: }
768: return document;
769: }
770:
771: private Document getDocumentFromString(String theString) {
772:
773: //DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
774: DocumentBuilderFactory factory = DocumentBuilderFactory
775: .newInstance();
776: factory.setNamespaceAware(true);
777: factory.setValidating(false);
778: factory
779: .setAttribute(
780: "http://apache.org/xml/properties/dom/document-class-name",
781: "org.chiba.xml.xforms.XFormsDocument");
782:
783: Document document = null;
784: try {
785: //get file and parse it to xmlDocument
786: DocumentBuilder documentBuilder = factory
787: .newDocumentBuilder();
788: document = documentBuilder.parse(new ByteArrayInputStream(
789: theString.getBytes()));
790: } catch (SAXException e) {
791: e.printStackTrace();
792: } catch (IOException e) {
793: e.printStackTrace();
794: } catch (ParserConfigurationException e) {
795: e.printStackTrace();
796: }
797: return document;
798: }
799:
800: private String getUserLanguage(String languages, String languagePath) {
801:
802: //Use a tokenizer to separate acceptable languages
803: StringTokenizer tokenizer = new StringTokenizer(languages, ",");
804: String lang = null;
805: boolean fileFound = false;
806: while (tokenizer.hasMoreTokens() && !fileFound) {
807: lang = tokenizer.nextToken();
808: int semi, dash;
809: //Cut off any q-value that might come after a semi-colon
810: if ((semi = lang.indexOf(';')) != -1) {
811: lang = lang.substring(0, semi);
812: }
813: //Trim any whitespace
814: lang = lang.trim();
815: //A dash may separate the
816: //language from the country.
817: if ((dash = lang.indexOf('-')) != -1) {
818: lang = lang.substring(0, dash);
819: }
820: //try to find lang file
821: File tmp = new File(languagePath + lang + ".xml");
822: if (tmp.exists()) {
823: fileFound = true;
824: }
825: }
826: if (!fileFound) {
827: lang = "en";
828: }
829:
830: return lang;
831: }
832:
833: private void forwardResponse(Map forwardMap,
834: HttpServletResponse response) throws IOException {
835: // fetch response stream
836: InputStream responseStream = (InputStream) forwardMap
837: .remove(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);
838:
839: // copy header information
840: Iterator iterator = forwardMap.keySet().iterator();
841: while (iterator.hasNext()) {
842: String name = iterator.next().toString();
843: String value = forwardMap.get(name).toString();
844: response.setHeader(name, value);
845: }
846:
847: // copy stream content
848: OutputStream outputStream = new BufferedOutputStream(response
849: .getOutputStream());
850: for (int b = responseStream.read(); b > -1; b = responseStream
851: .read()) {
852: outputStream.write(b);
853: }
854:
855: // close streams
856: responseStream.close();
857: outputStream.close();
858: }
859:
860: // Retourne un Document en String
861: private static String toString(Document doc) throws Exception {
862:
863: ByteArrayOutputStream os = new ByteArrayOutputStream();
864: OutputFormat outputFormat = new OutputFormat(doc);
865: outputFormat.setPreserveSpace(true);
866: outputFormat.setIndenting(true);
867: //outputFormat.setLineWidth(0);
868: XMLSerializer serializer = new XMLSerializer(os, outputFormat);
869: serializer.serialize(doc);
870:
871: return new String(os.toByteArray());
872: }
873:
874: }
|