Source Code Cross Referenced for ServletBonitaForm.java in  » Workflow-Engines » bonita-v3.1 » mc » formgenerator » servlets » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Workflow Engines » bonita v3.1 » mc.formgenerator.servlets 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Created on 23 avr. 2004 by the Message Center Team
0003:         *
0004:         */
0005:        package mc.formgenerator.servlets;
0006:
0007:        import mc.formgenerator.servlets.bonita.RepositoryFacade;
0008:        import mc.formgenerator.servlets.util.*;
0009:
0010:        import hero.user.ReadEnv;
0011:        import hero.util.HeroException;
0012:
0013:        import java.io.BufferedOutputStream;
0014:        import java.io.BufferedWriter;
0015:        import java.io.ByteArrayInputStream;
0016:        import java.io.ByteArrayOutputStream;
0017:        import java.io.File;
0018:        import java.io.FileNotFoundException;
0019:        import java.io.FileOutputStream;
0020:        import java.io.FileWriter;
0021:        import java.io.IOException;
0022:        import java.io.InputStream;
0023:        import java.io.OutputStream;
0024:        import java.io.PrintWriter;
0025:        import java.io.StringWriter;
0026:        import java.net.MalformedURLException;
0027:        import java.net.URISyntaxException;
0028:        import java.rmi.RemoteException;
0029:        import java.util.Collection;
0030:        import java.util.Enumeration;
0031:        import java.util.HashMap;
0032:        import java.util.Iterator;
0033:        import java.util.Map;
0034:        import java.util.StringTokenizer;
0035:        import java.util.Vector;
0036:
0037:        import javax.ejb.CreateException;
0038:        import javax.naming.NamingException;
0039:        import javax.security.auth.login.LoginException;
0040:        import javax.servlet.ServletConfig;
0041:        import javax.servlet.ServletException;
0042:        import javax.servlet.http.HttpServlet;
0043:        import javax.servlet.http.HttpServletRequest;
0044:        import javax.servlet.http.HttpServletResponse;
0045:        import javax.servlet.http.HttpSession;
0046:        import javax.xml.parsers.DocumentBuilder;
0047:        import javax.xml.parsers.DocumentBuilderFactory;
0048:        import javax.xml.parsers.ParserConfigurationException;
0049:        import javax.xml.transform.TransformerConfigurationException;
0050:        import javax.xml.transform.TransformerException;
0051:
0052:        import org.w3c.dom.DOMImplementation;
0053:        import org.w3c.dom.Document;
0054:        import org.w3c.dom.Element;
0055:        import org.w3c.dom.Node;
0056:        import org.w3c.dom.NodeList;
0057:        import org.w3c.dom.Text;
0058:        import org.xml.sax.SAXException;
0059:
0060:        import mc.formgenerator.bonita.BonitaActivityAdapter;
0061:        import mc.formgenerator.bonita.BonitaActivityExecutor;
0062:        import mc.formgenerator.bonita.BonitaProjectAdapter;
0063:        import mc.formgenerator.bonita.BonitaProjectExecutor;
0064:        import mc.formgenerator.bonita.DocumentParser;
0065:
0066:        import org.apache.log4j.Category;
0067:        import org.apache.xerces.dom.DOMImplementationImpl;
0068:        import org.apache.xml.serialize.DOMSerializer;
0069:        import org.apache.xml.serialize.OutputFormat;
0070:        import org.apache.xml.serialize.XMLSerializer;
0071:        import org.chiba.xml.xforms.Model;
0072:        import org.chiba.xml.xforms.config.Config;
0073:        import org.chiba.xml.xforms.exception.XFormsException;
0074:        import org.chiba.adapter.ChibaAdapter;
0075:
0076:        /**
0077:         * Servlet that displays forms acording to projects/activities properties
0078:         * and start/stop projects/activities execution. This servlet is a modification
0079:         * of ChibaServlet.
0080:         */
0081:        public class ServletBonitaForm extends HttpServlet {
0082:
0083:            //ServletAdapter instance
0084:            //private ServletAdapter servletAdapter = null;
0085:
0086:            //Allow us to know if we are working with an activity or a project
0087:            //private Boolean isActivity;
0088:
0089:            //Name of the project we are working with
0090:            //private String projectName = null;
0091:
0092:            //Name of the activity we are working with
0093:            //private String activityName = null;
0094:
0095:            //Application mode consumer or exploitant
0096:            //private String mode = null;
0097:
0098:            //forward URL
0099:            //private String forward = null;
0100:
0101:            //init-params
0102:            private static Category cat = Category
0103:                    .getInstance(ServletBonitaForm.class);
0104:            //private static final String FORM_PARAM_NAME = "form";
0105:            private static final String XSL_PARAM_NAME = "xslt";
0106:            private static final String CSS_PARAM_NAME = "css";
0107:            private static final String ACTIONURL_PARAM_NAME = "action_url";
0108:
0109:            /*
0110:             * It is not thread safe to modify these variables once the
0111:             * init(ServletConfig) method has been called
0112:             */
0113:            // the absolute path to the Chiba config-file
0114:            private String configPath = null;
0115:
0116:            // the rootdir of this app; forms + documents fill be searched under this root
0117:            private String contextRoot = null;
0118:
0119:            // where uploaded files are stored
0120:            private String uploadDir = null;
0121:
0122:            private String stylesPath = null;
0123:
0124:            /**
0125:             * Returns a short description of the servlet.
0126:             *
0127:             * @return - Returns a short description of the servlet.
0128:             */
0129:            public String getServletInfo() {
0130:                return "Servlet Controller for Chiba Bonita's XForms Processor";
0131:            }
0132:
0133:            /**
0134:             * Destroys the servlet.
0135:             */
0136:            public void destroy() {
0137:            }
0138:
0139:            /**
0140:             * Start the server side interpretation of the xforms document
0141:             * @param document the xforms document we have to interprete
0142:             * @param writer the servlet's writer
0143:             */
0144:            private ServletAdapter xformProcessing(Document instance,
0145:                    PrintWriter writer, HttpServletRequest request,
0146:                    HttpServletResponse response, String actionURL,
0147:                    HttpSession session, ServletAdapter servletAdapter,
0148:                    Boolean isActivity, String projectName,
0149:                    String activityName, String projectVersion)
0150:                    throws TransformerConfigurationException, XFormsException,
0151:                    FileNotFoundException, TransformerException, IOException,
0152:                    URISyntaxException, SAXException,
0153:                    ParserConfigurationException, Exception {
0154:
0155:                //hostUrl needed by ui.xsl
0156:                String hostUrl = request.getScheme() + "://"
0157:                        + request.getServerName() + ":"
0158:                        + request.getServerPort();
0159:
0160:                //xmlBase needed by Chiba
0161:                String xmlBase = request.getScheme() + "://"
0162:                        + request.getServerName() + ":"
0163:                        + request.getServerPort() + request.getContextPath()
0164:                        + "/";
0165:                Document xformDocument = null;
0166:                Document langInstance = null;
0167:
0168:                String xslFile = request.getParameter(XSL_PARAM_NAME);
0169:                String css = request.getParameter(CSS_PARAM_NAME);
0170:                if (css == null) {
0171:                    css = "web/styles/admin.css";
0172:                }
0173:
0174:                String realProjectName = projectName.replaceFirst(
0175:                        "_instance.+", "");
0176:
0177:                String formPath = null;
0178:
0179:                //instantiate RepositoryFacade to get form path (if exist)
0180:                RepositoryFacade repositoryFacade = new RepositoryFacade(
0181:                        getServletConfig().getServletContext().getRealPath("")
0182:                                + File.separator + "web" + File.separator
0183:                                + "repository.xml");
0184:
0185:                if (repositoryFacade == null) {
0186:                    //Exception
0187:                    throw new IOException(
0188:                            "Invalid session - Cannot retrieve repositoryFacade");
0189:                }
0190:
0191:                if (isActivity.booleanValue() == true) {
0192:                    formPath = repositoryFacade.getActivityFormPath(
0193:                            realProjectName, activityName, projectVersion);
0194:                } else {
0195:                    formPath = repositoryFacade.getProjectFormPath(
0196:                            realProjectName, projectVersion);
0197:                }
0198:                if (formPath != null) {
0199:                    // ****************************************************
0200:                    //xform file exist : use the xform to generate the html
0201:                    // ****************************************************
0202:
0203:                    //get file and parse it to xmlDocument
0204:                    String realFormPath = getServletConfig()
0205:                            .getServletContext().getRealPath("")
0206:                            + formPath;
0207:                    xformDocument = getDocument(realFormPath);
0208:                    //set xmlbase
0209:                    Element xformRoot = xformDocument.getDocumentElement();
0210:                    xformRoot.setAttribute("xml:base", xmlBase);
0211:
0212:                    //lookup languages and create language instance
0213:                    String languagePath = null;
0214:                    // *** Activity ***
0215:                    if (isActivity.booleanValue() == true) {
0216:                        //We are working with an activity
0217:                        languagePath = getServletConfig().getServletContext()
0218:                                .getRealPath("")
0219:                                + File.separator
0220:                                + "web"
0221:                                + File.separator
0222:                                + "xforms"
0223:                                + File.separator
0224:                                + realProjectName
0225:                                + File.separator
0226:                                + projectVersion
0227:                                + File.separator
0228:                                + activityName
0229:                                + File.separator;
0230:                        // *** Project Instance ***
0231:                    } else {
0232:                        //We are working with a project
0233:                        languagePath = getServletConfig().getServletContext()
0234:                                .getRealPath("")
0235:                                + File.separator
0236:                                + "web"
0237:                                + File.separator
0238:                                + "xforms"
0239:                                + File.separator
0240:                                + realProjectName
0241:                                + File.separator
0242:                                + projectVersion
0243:                                + File.separator;
0244:                    }
0245:
0246:                    String languages = request.getHeader("Accept-Language");
0247:                    String userLanguage = "en";
0248:                    if ((languages != null) && (!languages.equals(""))) {
0249:                        userLanguage = getUserLanguage(languages, languagePath);
0250:                    }
0251:
0252:                    langInstance = getDocument(languagePath + userLanguage
0253:                            + ".xml");
0254:
0255:                    //xformDocument = getDocument(realFormPath);
0256:
0257:                    //this.servletAdapter = setupServletAdapter(actionURL, session, formPath, xslFile, css);
0258:                    servletAdapter = setupServletAdapter(actionURL, hostUrl,
0259:                            session, xformDocument, realFormPath, xslFile, css);
0260:
0261:                } else {
0262:                    //xform file does not exist. Generate xform document
0263:                    xformDocument = createXform(instance, xmlBase, projectName,
0264:                            activityName, projectVersion);
0265:                    servletAdapter = setupServletAdapter(actionURL, hostUrl,
0266:                            session, xformDocument, null, xslFile, css);
0267:                }
0268:
0269:                //Chiba launching
0270:                //Build HTML page according to an activity or a project we are working with
0271:                try {
0272:                    //System.out.println("INSTANCE: " + toString(instance));
0273:                    //System.out.println("XFORM DOCUMENT: " + toString(xformDocument));
0274:                    //if (langInstance!=null) System.out.println("LANG INSTANCE: " + toString(langInstance));
0275:                    //create instance for XForm
0276:                    if (formPath != null) {
0277:                        servletAdapter = updateContext(request, session,
0278:                                instance, langInstance, servletAdapter);
0279:                    } else {
0280:                        servletAdapter = updateContext(request, session,
0281:                                instance, servletAdapter);
0282:                    }
0283:
0284:                    //add all request params that are not used by this servlet to the context map in ChibaBean
0285:                    servletAdapter = storeContextParams(request, servletAdapter);
0286:                    servletAdapter.init();
0287:                    //this.servletAdapter.executeHandler();
0288:                    servletAdapter.dispatch(null);
0289:                    servletAdapter.buildUI(writer);
0290:                } catch (Exception e) {
0291:                    //Error
0292:                    if (request.getParameter("forward") != null) {
0293:                        String saveTime = saveErrors(e);
0294:                        response.sendRedirect(request.getParameter("forward")
0295:                                + "&processError=saved&processName="
0296:                                + projectName + "&saveTime=" + saveTime);
0297:                    } else
0298:                        e.printStackTrace();
0299:                }
0300:                return (servletAdapter);
0301:            }
0302:
0303:            /**
0304:             * Action on doGet
0305:             * @param writer Response's writer
0306:             * @param request Request access
0307:             * @param response servlet response
0308:             * @throws TransformerConfigurationException
0309:             * @throws FileNotFoundException
0310:             * @throws XFormsException
0311:             * @throws TransformerException
0312:             * @throws IOException
0313:             */
0314:            private void writingUI(PrintWriter writer,
0315:                    HttpServletRequest request, HttpServletResponse response,
0316:                    String actionURL, HttpSession session)
0317:                    throws LoginException, TransformerConfigurationException,
0318:                    FileNotFoundException, TransformerException, IOException,
0319:                    Exception {
0320:
0321:                //ServletAdapter instance
0322:                ServletAdapter servletAdapter = null;
0323:
0324:                //Allow us to know if we are working with an activity or a project
0325:                Boolean isActivity = null;
0326:
0327:                //Name of the project we are working with
0328:                String projectName = request.getParameter("projectName");
0329:
0330:                //Name of the activity we are working with
0331:                String activityName = request.getParameter("activityName");
0332:
0333:                //The project version we are working with
0334:                String projectVersion = request.getParameter("version");
0335:
0336:                //Application mode consumer or exploitant
0337:                String mode = request.getParameter("mode");
0338:
0339:                //Document for server side interpretation
0340:                Document instance = null;
0341:
0342:                //Start or stop the activity
0343:                String action = request.getParameter("action");
0344:
0345:                //Project name parameter is present
0346:                if (projectName != null) {
0347:
0348:                    //We are working with an activity
0349:                    if (activityName != null) {
0350:
0351:                        if (action != null) {
0352:
0353:                            if (action.equals("stop")) {
0354:
0355:                                //Creation of executor
0356:                                BonitaActivityExecutor bonitaActivityExecutor = new BonitaActivityExecutor();
0357:
0358:                                //Terminate activity
0359:                                bonitaActivityExecutor.endActivity(
0360:                                        activityName, projectName);
0361:
0362:                                //Redirection to work list
0363:                                response
0364:                                        .sendRedirect("/formgenerator/ServletWorkList");
0365:
0366:                                return;
0367:                            } else {
0368:                                isActivity = new Boolean(true);
0369:
0370:                                //Creation of adapter
0371:                                BonitaActivityAdapter bonitaActivityAdapter = new BonitaActivityAdapter();
0372:
0373:                                //Getting process informations via the adapter
0374:                                instance = bonitaActivityAdapter
0375:                                        .getActivityData(projectName,
0376:                                                activityName, projectVersion);
0377:                            }
0378:                        } else {
0379:                            isActivity = new Boolean(true);
0380:
0381:                            //Creation of adapter
0382:                            BonitaActivityAdapter bonitaActivityAdapter = new BonitaActivityAdapter();
0383:
0384:                            //Getting process informations via the adapter
0385:                            instance = bonitaActivityAdapter.getActivityData(
0386:                                    projectName, activityName, projectVersion);
0387:                        }
0388:                    } else {
0389:
0390:                        //We are working with a project
0391:                        isActivity = new Boolean(false);
0392:
0393:                        //Creation of adapter
0394:                        BonitaProjectAdapter bonitaProjectAdapter = new BonitaProjectAdapter();
0395:                        //Getting process informations via the adapter
0396:                        instance = bonitaProjectAdapter.getProjectData(
0397:                                projectName, projectVersion);
0398:                    }
0399:                    DocumentParser parser = new DocumentParser();
0400:                    //If the document has properties
0401:
0402:                    if (parser.hasProperties(instance, isActivity)) {
0403:                        //Finally starting of interpretation
0404:                        servletAdapter = xformProcessing(instance, writer,
0405:                                request, response, actionURL, session,
0406:                                servletAdapter, isActivity, projectName,
0407:                                activityName, projectVersion);
0408:                    } else {
0409:                        //case there's no properties: request parameters collection is null and formsExists is false)
0410:                        String newinstance = callExecutor(instance, null,
0411:                                false, isActivity, mode, projectVersion);
0412:                        if (request.getParameter("forward") != null) {
0413:                            String forward = (String) request
0414:                                    .getParameter("forward");
0415:                            if (newinstance != null) {
0416:                                int delim = forward.indexOf("processName=");
0417:                                if (delim >= 0)
0418:                                    forward = forward.substring(0, delim + 12)
0419:                                            + newinstance;
0420:                            }
0421:                            if (projectVersion != null)
0422:                                forward = forward + "&version="
0423:                                        + projectVersion;
0424:                            response.sendRedirect(forward);
0425:                        } else {
0426:                            //Page redirection
0427:                            if (isActivity.booleanValue() == true) {
0428:                                if (mode.equals("consumer"))
0429:                                    //Redirection to todo list
0430:                                    response
0431:                                            .sendRedirect("/formgenerator/ServletActivityToDoList?projectName="
0432:                                                    + projectName);
0433:                                else
0434:                                    //Redirection to work list
0435:                                    response
0436:                                            .sendRedirect("/formgenerator/ServletWorkList");
0437:                            } else {
0438:                                if (mode.equals("consumer"))
0439:                                    //Redirection to instances projets
0440:                                    response
0441:                                            .sendRedirect("/formgenerator/ServletInstancesProjects");
0442:                                else
0443:                                    //Redirection to work list
0444:                                    response
0445:                                            .sendRedirect("/formgenerator/ServletWorkList");
0446:                            }
0447:                        }
0448:                    }
0449:                } else
0450:                    //Message to user
0451:                    (new MessageServlet())
0452:                            .writeMessage(writer,
0453:                                    "PARAMETER FOR projectName IS MISSING CANNOT PERFORM OPERATION");
0454:
0455:                //Stores the state of isActivity attribute in the session
0456:                session.setAttribute("formgenerator.isActivity", isActivity);
0457:
0458:                //Stores the servletAdapter
0459:                session.setAttribute("formgenerator.sAdapter", servletAdapter);
0460:
0461:                //Stores the projectname in the session
0462:                session.setAttribute("formgenerator.projectName", projectName);
0463:
0464:                //Stores the projectVersion in the session
0465:                session.setAttribute("formgenerator.projectVersion",
0466:                        projectVersion);
0467:
0468:                //Stores the activity name in the session
0469:                session
0470:                        .setAttribute("formgenerator.activityName",
0471:                                activityName);
0472:
0473:                //Stores the application mode in the session
0474:                session.setAttribute("formgenerator.mode", mode);
0475:            }
0476:
0477:            /**
0478:             * Call the correct executor
0479:             * @param filledDocument document that will be use by the executor
0480:             * @param mode the application mode: consumer or exploitant
0481:             */
0482:            private String callExecutor(Document filledDocument,
0483:                    Vector req_parameters, boolean formsExists,
0484:                    Boolean isActivity, String mode, String version)
0485:                    throws MalformedURLException, SAXException, IOException,
0486:                    RemoteException, NamingException, CreateException,
0487:                    HeroException, Exception {
0488:
0489:                String instance = null;
0490:                if (isActivity.booleanValue() == true) {
0491:
0492:                    //Creation of executor
0493:                    BonitaActivityExecutor bonitaActivityExecutor = new BonitaActivityExecutor();
0494:
0495:                    //Terminate the activity
0496:                    bonitaActivityExecutor.actOnActivity(filledDocument,
0497:                            req_parameters, formsExists, mode, version);
0498:                } else {
0499:
0500:                    //Creation of executor
0501:                    BonitaProjectExecutor bonitaProjectExecutor = new BonitaProjectExecutor();
0502:
0503:                    //Instanciate project
0504:                    instance = bonitaProjectExecutor.startBonitaProject(
0505:                            filledDocument, req_parameters, formsExists,
0506:                            version);
0507:                }
0508:                return instance;
0509:            }
0510:
0511:            /**
0512:             * Initializes the servlet.
0513:             *
0514:             * @param config - the ServletConfig object
0515:             * @throws javax.servlet.ServletException
0516:             */
0517:            public void init(ServletConfig config) throws ServletException {
0518:                super .init(config);
0519:
0520:                //cat.info("--------------- initing ChibaView... ---------------");
0521:                //read some params from web-inf
0522:                contextRoot = getServletConfig().getServletContext()
0523:                        .getRealPath("");
0524:                if (contextRoot == null)
0525:                    contextRoot = getServletConfig().getServletContext()
0526:                            .getRealPath(".");
0527:
0528:                //get the relative path to the chiba config-file
0529:                String path = getServletConfig().getInitParameter(
0530:                        "chiba.config");
0531:
0532:                //get the real path for the config-file
0533:                if (path != null) {
0534:                    configPath = getServletConfig().getServletContext()
0535:                            .getRealPath(path);
0536:                }
0537:
0538:                //get the path for the stylesheets
0539:                //path = getServletConfig().getServletContext().getInitParameter("chiba.xforms.stylesPath");
0540:                path = getServletConfig().getInitParameter(
0541:                        "chiba.xforms.stylesPath");
0542:
0543:                //get the real path for the stylesheets and configure a new StylesheetLoader with it
0544:                if (path != null) {
0545:                    stylesPath = getServletConfig().getServletContext()
0546:                            .getRealPath(path);
0547:                    //cat.info("stylesPath: " + stylesPath);
0548:                }
0549:
0550:                //uploadDir = contextRoot	+ "/" + getServletConfig().getServletContext().getInitParameter("chiba.upload");
0551:                //uploadDir = getServletConfig().getServletContext().getInitParameter("chiba.upload");
0552:                uploadDir = getServletConfig().getInitParameter("chiba.upload");
0553:                //Security constraint
0554:                if (uploadDir != null) {
0555:                    if (uploadDir.toUpperCase().indexOf("WEB-INF") >= 0) {
0556:                        throw new ServletException(
0557:                                "Chiba security constraint: uploadDir '"
0558:                                        + uploadDir + "' not allowed");
0559:                    }
0560:                }
0561:            }
0562:
0563:            /**
0564:             * Servlet reaction on get method:
0565:             * Display the form generated for filling a valid XML file
0566:             */
0567:            protected void doGet(HttpServletRequest request,
0568:                    HttpServletResponse response) throws IOException {
0569:                //set the content-type and character encoding for request and response
0570:                response.setContentType("text/html; charset="
0571:                        + FormGeneratorConstant.CHARACTER_ENCODING);
0572:                request
0573:                        .setCharacterEncoding(FormGeneratorConstant.CHARACTER_ENCODING);
0574:
0575:                //Creating a session
0576:                HttpSession session = request.getSession(true);
0577:
0578:                //Name of the project we are working with
0579:                String projectName = request.getParameter("projectName");
0580:
0581:                //The project version we are working with
0582:                String projectVersion = request.getParameter("version");
0583:
0584:                // get the user language
0585:                String userLanguage = request.getHeader("Accept-Language");
0586:
0587:                //write the 'forward' parameter in the session
0588:                if (request.getParameter("forward") != null)
0589:                    session.setAttribute("formgenerator.forward", request
0590:                            .getParameter("forward"));
0591:                else
0592:                    session.removeAttribute("forward");
0593:
0594:                try {
0595:
0596:                    //Getting the writer
0597:                    PrintWriter out = response.getWriter();
0598:
0599:                    // build actionURL where forms are submitted to
0600:                    String actionURL = getActionURL(request, response);
0601:
0602:                    //Build HTML page according to an activity or a project we are working with
0603:                    writingUI(out, request, response, actionURL, session);
0604:
0605:                    //Closing writer
0606:                    out.close();
0607:
0608:                } catch (Exception e) {
0609:                    //Error
0610:                    if (request.getParameter("forward") != null) {
0611:                        String saveTime = saveErrors(e);
0612:                        response.sendRedirect(request.getParameter("forward")
0613:                                + "&processError=saved&processName="
0614:                                + projectName + "&version=" + projectVersion
0615:                                + "&saveTime=" + saveTime);
0616:                    } else
0617:                        e.printStackTrace();
0618:
0619:                }
0620:            }
0621:
0622:            /**
0623:             * this method is responsible for passing all context information needed by the Adapter and Processor from
0624:             * ServletRequest to ChibaContext.
0625:             *
0626:             * @param servletAdapter the ChibaAdapter to use
0627:             * @param request        the ServletRequest
0628:             * @param session        the ServletSession
0629:             */
0630:            protected ServletAdapter updateContext(HttpServletRequest request,
0631:                    HttpSession session, Document instance,
0632:                    ServletAdapter servletAdapter) {
0633:                servletAdapter.setContextProperty(ServletAdapter.USERAGENT,
0634:                        request.getHeader("User-Agent"));
0635:                servletAdapter.setContextProperty(
0636:                        ServletAdapter.HTTP_SERVLET_REQUEST, request);
0637:                servletAdapter.setContextProperty(
0638:                        ServletAdapter.HTTP_SESSION_OBJECT, session);
0639:                servletAdapter.setContextProperty("instance", instance);
0640:                return (servletAdapter);
0641:            }
0642:
0643:            /**
0644:             * this method is responsible for passing all context information needed by the Adapter and Processor from
0645:             * ServletRequest to ChibaContext.
0646:             *
0647:             * @param servletAdapter the ChibaAdapter to use
0648:             * @param request        the ServletRequest
0649:             * @param session        the ServletSession
0650:             */
0651:            protected ServletAdapter updateContext(HttpServletRequest request,
0652:                    HttpSession session, Document formDocument,
0653:                    Document langDocument, ServletAdapter servletAdapter) {
0654:                servletAdapter.setContextProperty(ServletAdapter.USERAGENT,
0655:                        request.getHeader("User-Agent"));
0656:                servletAdapter.setContextProperty(
0657:                        ServletAdapter.HTTP_SERVLET_REQUEST, request);
0658:                servletAdapter.setContextProperty(
0659:                        ServletAdapter.HTTP_SESSION_OBJECT, session);
0660:                servletAdapter.setContextProperty("instance", formDocument);
0661:                servletAdapter.setContextProperty("lang", langDocument);
0662:                return (servletAdapter);
0663:            }
0664:
0665:            /**
0666:             * Servlet reaction on post method:
0667:             * Submit information from user
0668:             */
0669:            protected void doPost(HttpServletRequest request,
0670:                    HttpServletResponse response) throws ServletException,
0671:                    IOException {
0672:                String forward = null;
0673:                //Getting the current session
0674:                HttpSession session = request.getSession(true);
0675:
0676:                ServletAdapter servletAdapter = null;
0677:                String projectName = null;
0678:                String projectVersion = null;
0679:
0680:                try {
0681:                    response.setContentType("text/html; charset="
0682:                            + FormGeneratorConstant.CHARACTER_ENCODING);
0683:                    request
0684:                            .setCharacterEncoding(FormGeneratorConstant.CHARACTER_ENCODING);
0685:
0686:                    //Getting servletAdapter from the session
0687:                    servletAdapter = (ServletAdapter) session
0688:                            .getAttribute("formgenerator.sAdapter");
0689:
0690:                    //Getting isActivity from the session
0691:                    Boolean isActivity = (Boolean) session
0692:                            .getAttribute("formgenerator.isActivity");
0693:                    //Set isActivity in the session
0694:                    session
0695:                            .setAttribute("formgenerator.isActivity",
0696:                                    isActivity);
0697:
0698:                    //Getting projectName from the session
0699:                    projectName = (String) session
0700:                            .getAttribute("formgenerator.projectName");
0701:                    //Set the projectname in the session
0702:                    session.setAttribute("formgenerator.projectName",
0703:                            projectName);
0704:
0705:                    //			Getting projectVersion from the session
0706:                    projectVersion = (String) session
0707:                            .getAttribute("formgenerator.projectVersion");
0708:                    //Set the projectversion in the session
0709:                    session.setAttribute("formgenerator.projectVersion",
0710:                            projectVersion);
0711:
0712:                    //Getting activityName from the session
0713:                    String activityName = (String) session
0714:                            .getAttribute("formgenerator.activityName");
0715:                    //Set the activityname in the session
0716:                    session.setAttribute("formgenerator.activityName",
0717:                            activityName);
0718:
0719:                    //Getting mode from the session
0720:                    String mode = (String) session
0721:                            .getAttribute("formgenerator.mode");
0722:
0723:                    //Getting forward from the session
0724:                    forward = (String) session
0725:                            .getAttribute("formgenerator.forward");
0726:
0727:                    //Set isActivity in the session
0728:                    session.setAttribute("formgenerator.forward", forward);
0729:
0730:                    if ((servletAdapter == null) || (isActivity == null)
0731:                            || (projectName == null)) {
0732:                        //Exception
0733:                        throw new IOException(
0734:                                "Invalid session - Cannot retrieve servletAdapter or ggf or isActivity or projectName in the session");
0735:                    }
0736:
0737:                    servletAdapter = updateContextPost(request, session,
0738:                            servletAdapter);
0739:
0740:                    //this.servletAdapter.executeHandler();
0741:                    servletAdapter.dispatch(null);
0742:
0743:                    // handle setRedirect <xforms:load show='replace'/>
0744:                    // and redirect from submission as well
0745:                    // NOTE - this needs to be checked *before* the this.getForwardMap()
0746:                    // as a submission handler may force a redirect
0747:                    if (servletAdapter.getRedirectUri() != null) {
0748:                        String redirectTo = servletAdapter.getRedirectUri();
0749:                        // todo: remove from session ?
0750:                        // shutdown processor
0751:                        servletAdapter.getChibaBean().shutdown();
0752:
0753:                        // send redirect (after encoding session id if required)
0754:                        response.sendRedirect(response
0755:                                .encodeRedirectURL(redirectTo));
0756:
0757:                        // remove redirect uri and terminate
0758:                        servletAdapter.setRedirect(null);
0759:                        return;
0760:                    }
0761:
0762:                    // handle forward <xforms:submission replace='all'/>
0763:                    Map forwardMap = servletAdapter.getForwardMap();
0764:                    InputStream forwardStream = (InputStream) forwardMap
0765:                            .get(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);
0766:                    if (forwardStream != null) {
0767:                        //get instance filled
0768:                        //Document filledDocument = (Document)this.servletAdapter.getChibaBean().getContainer().getModel("model").getInstance("instance").getInstanceDocument();
0769:                        Model model = (Model) servletAdapter.getChibaBean()
0770:                                .lookup("model");
0771:                        Document filledDocument = (Document) model.getInstance(
0772:                                "instance").getInstanceDocument();
0773:                        if (filledDocument == null) {
0774:                            throw new ServletException(Config.getInstance()
0775:                                    .getErrorMessage("session-invalid"));
0776:                        }
0777:                        //------ test if xform has been generated -----
0778:                        String formPath = null;
0779:                        boolean formsExists = false;
0780:                        Vector v_req_params = null;
0781:
0782:                        //instantiate RepositoryFacade to get form path (if exist)
0783:                        RepositoryFacade repositoryFacade = new RepositoryFacade(
0784:                                getServletConfig().getServletContext()
0785:                                        .getRealPath("")
0786:                                        + File.separator
0787:                                        + "web"
0788:                                        + File.separator + "repository.xml");
0789:
0790:                        if (repositoryFacade == null) {
0791:                            //Exception
0792:                            throw new IOException(
0793:                                    "Invalid session - Cannot retrieve repositoryFacade");
0794:                        }
0795:                        String realProjectName = projectName.replaceFirst(
0796:                                "_instance.+", "");
0797:                        if (isActivity.booleanValue() == true) {
0798:                            formPath = repositoryFacade.getActivityFormPath(
0799:                                    realProjectName, activityName,
0800:                                    projectVersion);
0801:                        } else {
0802:                            formPath = repositoryFacade.getProjectFormPath(
0803:                                    realProjectName, projectVersion);
0804:                        }
0805:                        if (formPath != null) {
0806:                            //xform has been generated and some properties may have constraints: hidden, readonly
0807:                            formsExists = true;
0808:                            //Get parameters of the request (to be able latter in xxExecutor Bean
0809:                            // remove hidden, readonly properties from the filledDocument)
0810:                            Enumeration param_names = request
0811:                                    .getParameterNames();
0812:                            v_req_params = new Vector();
0813:
0814:                            for (; param_names.hasMoreElements();) {
0815:                                //Get the name of the request parameter
0816:                                String name = (String) param_names
0817:                                        .nextElement();
0818:                                //remove prefix : d_  from for ex.: d_proc_str if xform generated or for ex. : d_C2 if no xform
0819:                                name = name.substring(2);
0820:                                v_req_params.add(name);
0821:                            }
0822:                        }
0823:                        //Calling the executor
0824:                        String newinstance = this .callExecutor(filledDocument,
0825:                                v_req_params, formsExists, isActivity, mode,
0826:                                projectVersion);
0827:
0828:                        //redirect
0829:                        if ((forward != null) && !forward.equals("")) {
0830:                            //redirection to forward
0831:                            if (newinstance != null) {
0832:                                int delim = forward.indexOf("processName=");
0833:                                if (delim >= 0)
0834:                                    forward = forward.substring(0, delim + 12)
0835:                                            + newinstance;
0836:                            }
0837:                            if (projectVersion != null)
0838:                                forward = forward + "&version="
0839:                                        + projectVersion;
0840:                            response.sendRedirect(forward);
0841:                        } else {
0842:                            if (isActivity.booleanValue() == true) {
0843:
0844:                                if (mode.equals("consumer"))
0845:                                    //Redirection to todo list
0846:                                    response
0847:                                            .sendRedirect("/formgenerator/ServletActivityToDoList?projectName="
0848:                                                    + projectName);
0849:                                else
0850:                                    //Redirection to work list
0851:                                    response
0852:                                            .sendRedirect("/formgenerator/ServletWorkList");
0853:                            } else {
0854:                                if (mode != null) {
0855:                                    if (mode.equals("consumer"))
0856:                                        //Redirection to instances projets
0857:                                        response
0858:                                                .sendRedirect("/formgenerator/ServletInstancesProjects");
0859:                                    else
0860:                                        //Redirection to work list
0861:                                        response
0862:                                                .sendRedirect("/formgenerator/ServletWorkList");
0863:                                }
0864:                            }
0865:                        }
0866:                        /*
0867:                        // todo: remove from session ?
0868:                        // shutdown processor
0869:                        this.servletAdapter.getChibaBean().shutdown();
0870:
0871:                        // forward submission response
0872:                        forwardResponse(forwardMap, response);
0873:
0874:                        // remove forward response and terminate
0875:                        this.servletAdapter.forward(null);
0876:                        return;
0877:                         */
0878:                    }
0879:
0880:                    //Set content type
0881:                    //response.setContentType("text/html");
0882:
0883:                    //Render result to output
0884:                    //this.chiba.runChiba(out);
0885:                    servletAdapter.buildUI(response.getWriter());
0886:                    response.getWriter().close();
0887:
0888:                } catch (Exception e) {
0889:                    //Error
0890:                    if (forward != null) {
0891:                        String saveTime = saveErrors(e);
0892:                        response.sendRedirect(forward
0893:                                + "&processError=saved&processName="
0894:                                + projectName + "&saveTime=" + saveTime);
0895:                    } else
0896:                        e.printStackTrace();
0897:                }
0898:            }
0899:
0900:            /**
0901:             * this method is responsible for passing all context information needed by the Adapter and Processor from
0902:             * ServletRequest to ChibaContext.
0903:             *
0904:             * @param servletAdapter the ChibaAdapter to use
0905:             * @param request        the ServletRequest
0906:             * @param session        the ServletSession
0907:             */
0908:            protected ServletAdapter updateContextPost(
0909:                    HttpServletRequest request, HttpSession session,
0910:                    ServletAdapter servletAdapter) {
0911:                servletAdapter.setContextProperty(ServletAdapter.USERAGENT,
0912:                        request.getHeader("User-Agent"));
0913:                servletAdapter.setContextProperty(
0914:                        ServletAdapter.HTTP_SERVLET_REQUEST, request);
0915:                servletAdapter.setContextProperty(
0916:                        ServletAdapter.HTTP_SESSION_OBJECT, session);
0917:                return (servletAdapter);
0918:            }
0919:
0920:            /**
0921:             * creates and configures the ServletAdapter which does the actual request processing.
0922:             *
0923:             * @param actionURL - the URL to submit to
0924:             * @param session   - the Servlet session
0925:             * @param formPath  - the relative location where forms are stored
0926:             * @param xslFile   - the xsl file to use for transform
0927:             * @param cssFile   - the CSS file to use for styling the output
0928:             * @return ServletAdapter
0929:             */
0930:            private ServletAdapter setupServletAdapter(String actionURL,
0931:                    String hostUrl, HttpSession session, Document formDocument,
0932:                    String baseURI, String xslFile, String cssFile)
0933:                    throws XFormsException, URISyntaxException, Exception {
0934:                //setup and configure the adapter
0935:                ServletAdapter aAdapter = new ServletAdapter();
0936:                aAdapter.setContextRoot(contextRoot);
0937:                if ((configPath != null) && !(configPath.equals(""))) {
0938:                    aAdapter.setConfigPath(configPath);
0939:                }
0940:
0941:                //call getDocumentFromString to get a valid Chiba Document
0942:                try {
0943:                    formDocument = getDocumentFromString(toString(formDocument));
0944:                } catch (Exception e) {
0945:                    e.printStackTrace();
0946:                    throw new Exception("ServletBonitaForm.setupServletAdapter");
0947:                }
0948:
0949:                //aAdapter.setFormURI(new URI(this.contextRoot));
0950:                aAdapter.setXFormsURI(this .contextRoot);
0951:                //aAdapter.setFormDocument(formDocument);
0952:                aAdapter.setXForms(formDocument);
0953:                aAdapter.setStylesheetPath(stylesPath);
0954:                aAdapter.setActionUrl(actionURL);
0955:                aAdapter.setUploadDir(uploadDir);
0956:                aAdapter.setHostUrl(hostUrl);
0957:
0958:                if (xslFile != null) {
0959:                    aAdapter.setStylesheet(xslFile);
0960:                    if (cat.isDebugEnabled()) {
0961:                        cat.debug("using xsl stylesheet: " + xslFile);
0962:                    }
0963:                }
0964:                if (cssFile != null) {
0965:                    aAdapter.setCSS(cssFile);
0966:                    if (cat.isDebugEnabled()) {
0967:                        cat.debug("using css stylesheet: " + cssFile);
0968:                    }
0969:                }
0970:
0971:                Map servletMap = new HashMap();
0972:                servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
0973:                aAdapter.setContextProperty(ChibaAdapter.SUBMISSION_RESPONSE,
0974:                        servletMap);
0975:
0976:                return aAdapter;
0977:            }
0978:
0979:            /**
0980:             * creates and configures the ServletAdapter which does the actual request processing.
0981:             *
0982:             * @param actionURL - the URL to submit to
0983:             * @param session   - the Servlet session
0984:             * @param formPath  - the relative location where forms are stored
0985:             * @param xslFile   - the xsl file to use for transform
0986:             * @param cssFile   - the CSS file to use for styling the output
0987:             * @return ServletAdapter
0988:             */
0989:            /*
0990:            private ServletAdapter setupServletAdapter(String actionURL,
0991:                                                       HttpSession session,
0992:                                                       String formPath,
0993:                                                       String xslFile,
0994:                                                       String cssFile) throws XFormsException, URISyntaxException {
0995:                //setup and configure the adapter
0996:                ServletAdapter aAdapter = new ServletAdapter();
0997:                aAdapter.setContextRoot(contextRoot);
0998:                if ((configPath != null) && !(configPath.equals(""))) {
0999:                    aAdapter.setConfigPath(configPath);
1000:                }
1001:                aAdapter.setFormPath(formPath);
1002:            	//aAdapter.setXFormsURI(formPath);
1003:                aAdapter.setStylesheetPath(stylesPath);
1004:                aAdapter.setActionUrl(actionURL);
1005:                aAdapter.setUploadDir(uploadDir);
1006:
1007:                if (xslFile != null) {
1008:                    aAdapter.setStylesheet(xslFile);
1009:                    if (cat.isDebugEnabled()) {
1010:                        cat.debug("using xsl stylesheet: " + xslFile);
1011:                    }
1012:                }
1013:                if (cssFile != null) {
1014:                    aAdapter.setCSS(cssFile);
1015:                    if (cat.isDebugEnabled()) {
1016:                        cat.debug("using css stylesheet: " + cssFile);
1017:                    }
1018:                }
1019:
1020:                Map servletMap = new HashMap();
1021:                servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
1022:                aAdapter.setContextProperty(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);
1023:
1024:                return aAdapter;
1025:            }
1026:             */
1027:
1028:            private ServletAdapter storeContextParams(
1029:                    HttpServletRequest request, ServletAdapter servletAdapter) {
1030:                Enumeration params = request.getParameterNames();
1031:                String s;
1032:                while (params.hasMoreElements()) {
1033:                    s = (String) params.nextElement();
1034:                    //store all request-params we don't use in the context map of ChibaBean
1035:                    if (!(s.equals(XSL_PARAM_NAME) || s.equals(CSS_PARAM_NAME) || s
1036:                            .equals(ACTIONURL_PARAM_NAME))) {
1037:                        String value = request.getParameter(s);
1038:                        servletAdapter.setContextProperty(s, value);
1039:                        if (cat.isDebugEnabled()) {
1040:                            cat.debug("added request param '" + s
1041:                                    + "' added to context");
1042:                        }
1043:                    }
1044:                }
1045:                return (servletAdapter);
1046:            }
1047:
1048:            /**
1049:             * Return the action URL with jsession
1050:             * @param request : The request from user
1051:             * @param response : The response to its request
1052:             * @return a String object that represents the action URL
1053:             */
1054:            private String getActionURL(HttpServletRequest request,
1055:                    HttpServletResponse response) {
1056:                String defaultActionURL = request.getScheme() + "://"
1057:                        + request.getServerName() + ":"
1058:                        + request.getServerPort() + request.getContextPath()
1059:                        + request.getServletPath();
1060:                String encodedDefaultActionURL = response
1061:                        .encodeURL(defaultActionURL);
1062:                int sessIdx = encodedDefaultActionURL.indexOf(";jsession");
1063:                String sessionId = null;
1064:                if (sessIdx > -1) {
1065:                    sessionId = encodedDefaultActionURL.substring(sessIdx);
1066:                }
1067:                String actionURL = request.getParameter(ACTIONURL_PARAM_NAME);
1068:                if (null == actionURL) {
1069:                    actionURL = encodedDefaultActionURL;
1070:                } else if (null != sessionId) {
1071:                    actionURL += sessionId;
1072:                }
1073:
1074:                //cat.info("actionURL: " + actionURL);
1075:                // encode the URL to allow for session id rewriting
1076:                actionURL = response.encodeURL(actionURL);
1077:                return actionURL;
1078:            }
1079:
1080:            private void writeFile(String formPath, Document formDocument)
1081:                    throws FileNotFoundException, IOException {
1082:                FileOutputStream output = null;
1083:                OutputFormat of = new OutputFormat("XML",
1084:                        FormGeneratorConstant.CHARACTER_ENCODING, true);
1085:                of.setIndent(1);
1086:                of.setIndenting(true);
1087:                XMLSerializer serializer = null;
1088:                try {
1089:                    output = new FileOutputStream(formPath);
1090:                    serializer = new XMLSerializer(output, of);
1091:                    serializer.asDOMSerializer();
1092:                    serializer.serialize(formDocument.getDocumentElement());
1093:                    output.close();
1094:                } catch (FileNotFoundException e) {
1095:                    e.printStackTrace();
1096:                    throw new FileNotFoundException(
1097:                            "ServletBonitaForm.writeFile");
1098:                } catch (IOException e) {
1099:                    e.printStackTrace();
1100:                    throw new IOException("ServletBonitaForm.writeFile");
1101:                }
1102:            }
1103:
1104:            private void deleteFile(String filename) {
1105:                // Create a File object to represent the filename
1106:                File f = new File(filename);
1107:                // Make sure the file or directory exists and isn't write protected
1108:                if (!f.exists())
1109:                    System.out
1110:                            .println("ERROR: ServletBonitaForm ==> deleteFile: no such file or directory: "
1111:                                    + filename);
1112:                if (!f.canWrite())
1113:                    System.out
1114:                            .println("ERROR: ServletBonitaForm ==> deleteFile: write protected: "
1115:                                    + filename);
1116:                // If we passed all the tests, then attempt to delete it
1117:                boolean success = f.delete();
1118:                if (!success)
1119:                    System.out
1120:                            .println("ERROR: ServletBonitaForm ==> deleteFile: deletion failed");
1121:            }
1122:
1123:            private Document getDocument(String path) throws SAXException,
1124:                    IOException, ParserConfigurationException {
1125:
1126:                //DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
1127:                DocumentBuilderFactory factory = DocumentBuilderFactory
1128:                        .newInstance();
1129:                factory.setNamespaceAware(true);
1130:                factory.setValidating(false);
1131:                factory
1132:                        .setAttribute(
1133:                                "http://apache.org/xml/properties/dom/document-class-name",
1134:                                "org.chiba.xml.xforms.XFormsDocument");
1135:
1136:                Document document = null;
1137:                try {
1138:                    //get file and parse it to xmlDocument
1139:                    File xmlFile = new File(path);
1140:                    DocumentBuilder documentBuilder = factory
1141:                            .newDocumentBuilder();
1142:                    document = documentBuilder.parse(xmlFile);
1143:                } catch (SAXException e) {
1144:                    e.printStackTrace();
1145:                    throw new SAXException("ServletBonitaForm.getDocument");
1146:                } catch (IOException e) {
1147:                    e.printStackTrace();
1148:                    throw new IOException("ServletBonitaForm.getDocument");
1149:                } catch (ParserConfigurationException e) {
1150:                    e.printStackTrace();
1151:                    throw new ParserConfigurationException(
1152:                            "ServletBonitaForm.getDocument");
1153:                }
1154:                return document;
1155:            }
1156:
1157:            private Document getDocumentFromString(String theString)
1158:                    throws SAXException, IOException,
1159:                    ParserConfigurationException {
1160:
1161:                //DocumentBuilderFactory factory = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
1162:                DocumentBuilderFactory factory = DocumentBuilderFactory
1163:                        .newInstance();
1164:                factory.setNamespaceAware(true);
1165:                factory.setValidating(false);
1166:                factory
1167:                        .setAttribute(
1168:                                "http://apache.org/xml/properties/dom/document-class-name",
1169:                                "org.chiba.xml.xforms.XFormsDocument");
1170:
1171:                Document document = null;
1172:                try {
1173:                    //get file and parse it to xmlDocument
1174:                    DocumentBuilder documentBuilder = factory
1175:                            .newDocumentBuilder();
1176:                    document = documentBuilder.parse(new ByteArrayInputStream(
1177:                            theString.getBytes()));
1178:                } catch (SAXException e) {
1179:                    e.printStackTrace();
1180:                    throw new SAXException(
1181:                            "ServletBonitaForm.getDocumentFromString");
1182:                } catch (IOException e) {
1183:                    e.printStackTrace();
1184:                    throw new IOException(
1185:                            "ServletBonitaForm.getDocumentFromString");
1186:                } catch (ParserConfigurationException e) {
1187:                    e.printStackTrace();
1188:                    throw new ParserConfigurationException(
1189:                            "ServletBonitaForm.getDocumentFromString");
1190:                }
1191:                return document;
1192:            }
1193:
1194:            private String getUserLanguage(String languages, String languagePath) {
1195:
1196:                //Use a tokenizer to separate acceptable languages
1197:                StringTokenizer tokenizer = new StringTokenizer(languages, ",");
1198:                String lang = null;
1199:                boolean fileFound = false;
1200:                while (tokenizer.hasMoreTokens() && !fileFound) {
1201:                    lang = tokenizer.nextToken();
1202:                    int semi, dash;
1203:                    //Cut off any q-value that might come after a semi-colon
1204:                    if ((semi = lang.indexOf(';')) != -1) {
1205:                        lang = lang.substring(0, semi);
1206:                    }
1207:                    //Trim any whitespace
1208:                    lang = lang.trim();
1209:                    //A dash may separate the
1210:                    //language from the country.
1211:                    if ((dash = lang.indexOf('-')) != -1) {
1212:                        lang = lang.substring(0, dash);
1213:                    }
1214:                    //try to find lang file
1215:                    File tmp = new File(languagePath + lang + ".xml");
1216:                    if (tmp.exists()) {
1217:                        fileFound = true;
1218:                    }
1219:                }
1220:                if (!fileFound) {
1221:                    lang = "en";
1222:                }
1223:
1224:                return lang;
1225:            }
1226:
1227:            private void forwardResponse(Map forwardMap,
1228:                    HttpServletResponse response) throws IOException {
1229:                // fetch response stream
1230:                InputStream responseStream = (InputStream) forwardMap
1231:                        .remove(ChibaAdapter.SUBMISSION_RESPONSE_STREAM);
1232:
1233:                // copy header information
1234:                Iterator iterator = forwardMap.keySet().iterator();
1235:                while (iterator.hasNext()) {
1236:                    String name = iterator.next().toString();
1237:                    String value = forwardMap.get(name).toString();
1238:                    response.setHeader(name, value);
1239:                }
1240:
1241:                // copy stream content
1242:                OutputStream outputStream = new BufferedOutputStream(response
1243:                        .getOutputStream());
1244:                for (int b = responseStream.read(); b > -1; b = responseStream
1245:                        .read()) {
1246:                    outputStream.write(b);
1247:                }
1248:
1249:                // close streams
1250:                responseStream.close();
1251:                outputStream.close();
1252:            }
1253:
1254:            // Retourne un Document en String
1255:            private static String toString(Document doc) throws Exception {
1256:
1257:                ByteArrayOutputStream os = new ByteArrayOutputStream();
1258:                OutputFormat outputFormat = new OutputFormat(doc);
1259:                outputFormat.setPreserveSpace(true);
1260:                outputFormat.setIndenting(true);
1261:                //outputFormat.setLineWidth(0);
1262:                XMLSerializer serializer = new XMLSerializer(os, outputFormat);
1263:                serializer.serialize(doc);
1264:
1265:                return new String(os.toByteArray());
1266:            }
1267:
1268:            /**  13-05-2005
1269:             *   This method transform xmlInput to XForm instance.
1270:             *   <p/>
1271:             *
1272:             *   @param xmlInput XML Input to transform.
1273:             * @throws SAXException
1274:             * @throws IOException
1275:             */
1276:            /*
1277:            public Document getInstance(Document xmlInput){
1278:
1279:            	//get xmlInput root
1280:            	Element root = xmlInput.getDocumentElement();
1281:            	NodeList rootChilds = root.getChildNodes();
1282:
1283:            	//Instance Document creation with the root element called process
1284:            	DOMImplementation domImpl = new DOMImplementationImpl();
1285:            	Document instanceDocument = domImpl.createDocument(null, "process" , null);
1286:            	Element instanceRoot = instanceDocument.getDocumentElement();
1287:
1288:            	//project properties element creation
1289:            	Element projectProperties = instanceDocument.createElement("projectProperties");
1290:            	instanceRoot.appendChild(projectProperties);
1291:
1292:            	//activity properties element creation
1293:            	Element activityProperties = instanceDocument.createElement("activityProperties");
1294:            	instanceRoot.appendChild(activityProperties);
1295:
1296:            	//get xmlInput project and activity propeties nodes
1297:            	Node inputProjectProperties = rootChilds.item(0);
1298:            	NodeList propertiesChilds = inputProjectProperties.getChildNodes();
1299:
1300:            	Node inputActivityProperties = null;
1301:            	NodeList activityPropertiesChilds = null;
1302:            	if(this.activityName != null){
1303:            		inputActivityProperties = rootChilds.item(1);
1304:            		activityPropertiesChilds = activityProperties.getChildNodes();
1305:            	}
1306:
1307:            	int i; //i will be used also to create activity binds and properties if they exist
1308:
1309:            	//project properties
1310:            	for(i=0;i<propertiesChilds.getLength();i++){
1311:            			Node property = propertiesChilds.item(i);
1312:            			NodeList propertyChilds = property.getChildNodes();
1313:
1314:            			//get property name
1315:            			Element propertyNameElement = (Element)propertyChilds.item(0); //property name will be allways in the same position
1316:            			Text propertyNameText = (Text)propertyNameElement.getFirstChild();
1317:            			String propertyName = propertyNameText.getNodeValue();
1318:
1319:            			//get property value
1320:            			Element propertyValueElement = (Element)propertyChilds.item(1); //property value will be allways in the same position
1321:            			Text propertyValueText = (Text)propertyValueElement.getFirstChild();
1322:            			String propertyValue = propertyValueText.getNodeValue();
1323:
1324:            			//set property node in instance file
1325:            			Element propertyElement = instanceDocument.createElement(propertyName);
1326:            			Text propertyText = instanceDocument.createTextNode(propertyValue);
1327:            			propertyElement.appendChild(propertyText);
1328:            			projectProperties.appendChild(propertyElement);
1329:            	}
1330:
1331:            	//activity properties
1332:            	if(this.activityName!=null){
1333:            		for(int j=i,k=0;k<activityPropertiesChilds.getLength();j++,k++){
1334:            			Node property = activityPropertiesChilds.item(k);
1335:            			NodeList propertyChilds = property.getChildNodes();
1336:
1337:            			//get property name
1338:            			Element propertyNameElement = (Element)propertyChilds.item(0); //property name will be allways in the same position
1339:            			Text propertyNameText = (Text)propertyNameElement.getFirstChild();
1340:            			String propertyName = propertyNameText.getNodeValue();
1341:
1342:            			//get property value
1343:            			Element propertyValueElement = (Element)propertyChilds.item(2); //property type will be allways in the same position
1344:            			Text propertyValueText = (Text)propertyValueElement.getFirstChild();
1345:            			String propertyValue = propertyValueText.getNodeValue();
1346:
1347:            			//set property node in instance file
1348:            			Element propertyElement = instanceDocument.createElement(propertyName);
1349:            			Text propertyText = instanceDocument.createTextNode(propertyValue);
1350:            			propertyElement.appendChild(propertyText);
1351:            			activityProperties.appendChild(propertyElement);
1352:            		}
1353:            	}
1354:            	return instanceDocument;
1355:
1356:            }
1357:             */
1358:
1359:            /**  13-05-2005
1360:             *   This method creates xform and language documents.
1361:             *   <p/>
1362:             *
1363:             *   @param xmlInput xml input Document.
1364:             * @throws SAXException
1365:             * @throws IOException
1366:             */
1367:            public Document createXform(Document xmlInput, String xmlBase,
1368:                    String projectName, String activityName,
1369:                    String projectVersion) throws Exception {
1370:                //get xmlInput root
1371:                Element root = xmlInput.getDocumentElement();
1372:                NodeList rootChilds = root.getChildNodes();
1373:
1374:                //XForm Document creation with the root element called html
1375:                DOMImplementation domImpl = new DOMImplementationImpl();
1376:                Document xformDocument = domImpl.createDocument(null, "html",
1377:                        null);
1378:                Element xformRoot = xformDocument.getDocumentElement();
1379:
1380:                //Set xmlns...
1381:                xformRoot.setAttribute("xml:base", xmlBase);
1382:                xformRoot.setAttribute("xmlns",
1383:                        "http://www.w3.org/2002/06/xhtml2");
1384:                xformRoot.setAttribute("xmlns:xf",
1385:                        "http://www.w3.org/2002/xforms");
1386:                xformRoot.setAttribute("xmlns:xsd",
1387:                        "http://www.w3.org/2001/XMLSchema");
1388:                xformRoot.setAttribute("xmlns:xsi",
1389:                        "http://www.w3.org/2001/XMLSchema-instance");
1390:
1391:                //head
1392:                Element head = xformDocument.createElement("head");
1393:                xformRoot.appendChild(head);
1394:
1395:                //tittle
1396:                Element tittle = xformDocument.createElement("tittle");
1397:                Text tittleText = xformDocument.createTextNode(projectName
1398:                        + "XForm");
1399:                tittle.appendChild(tittleText);
1400:                head.appendChild(tittle);
1401:
1402:                //model
1403:                Element model = xformDocument.createElement("xf:model");
1404:                //model.setPrefix("");
1405:                model.setAttribute("id", "model");
1406:                head.appendChild(model);
1407:
1408:                //instances
1409:                Element instance = xformDocument.createElement("xf:instance");
1410:                instance.setAttribute("id", "instance");
1411:                instance.setAttribute("src", "contextobject:$instance");
1412:                model.appendChild(instance);
1413:
1414:                //submission
1415:                Element submission = xformDocument
1416:                        .createElement("xf:submission");
1417:                submission.setAttribute("id", "bValider");
1418:                submission.setAttribute("action", "");
1419:                submission.setAttribute("method", "post");
1420:                submission.setAttribute("replace", "all");
1421:                model.appendChild(submission);
1422:
1423:                //binds
1424:                //bind element to clone and create new binds
1425:                Element nameBind = xformDocument.createElement("xf:bind");
1426:                nameBind.setAttribute("id", "");
1427:                nameBind.setAttribute("nodeset", "");
1428:                nameBind.setAttribute("readonly", "");
1429:                nameBind.setAttribute("required", "");
1430:                nameBind.setAttribute("type", "");
1431:                nameBind.setAttribute("relevant", "");
1432:                //nameBind.setAttribute("int:extattr","");
1433:
1434:                //select choice binds
1435:                //select choice bind element to clone and create new binds
1436:                Element selectChoiceBind = xformDocument
1437:                        .createElement("xf:bind");
1438:                selectChoiceBind.setAttribute("id", "");
1439:                selectChoiceBind.setAttribute("nodeset", "");
1440:
1441:                //project properties node will be always rootChilds.item(1)
1442:                Node properties = rootChilds.item(1);
1443:                NodeList propertiesChilds = properties.getChildNodes();
1444:
1445:                //activity properties node will be always rootChilds.item(3)
1446:                Node activityProperties = null;
1447:                NodeList activityPropertiesChilds = null;
1448:                if (activityName != null) {
1449:                    activityProperties = rootChilds.item(3);
1450:                    activityPropertiesChilds = activityProperties
1451:                            .getChildNodes();
1452:                }
1453:
1454:                //end head
1455:
1456:                //body
1457:                Element body = xformDocument.createElement("body");
1458:                xformRoot.appendChild(body);
1459:
1460:                //group
1461:                Element group = xformDocument.createElement("xf:group");
1462:                group.setAttribute("appearance", "maximal");
1463:                body.appendChild(group);
1464:
1465:                //xform elements
1466:
1467:                //label element to clone and create new labels
1468:                Element defaultLabel = xformDocument.createElement("xf:label");
1469:
1470:                //input element to clone and create new inputs
1471:                Element defaultInput = xformDocument.createElement("xf:input");
1472:                defaultInput.setAttribute("bind", "");
1473:                //defaultInput.setAttribute("ref","");
1474:                defaultInput.setAttribute("extattr", "");
1475:                defaultInput.setAttribute("content", "no");
1476:                Element defaultInputLabel = xformDocument
1477:                        .createElement("xf:label");
1478:                defaultInput.appendChild(defaultInputLabel);
1479:                Element defaultInputAlert = xformDocument
1480:                        .createElement("xf:alert");
1481:                Text defaultInputAlertText = xformDocument.createTextNode("");
1482:                defaultInputAlertText.setNodeValue("Error!");
1483:                defaultInputAlert.appendChild(defaultInputAlertText);
1484:                defaultInput.appendChild(defaultInputAlert);
1485:
1486:                //textarea element to clone and create new textareas
1487:                Element defaultTextArea = xformDocument
1488:                        .createElement("xf:textarea");
1489:                defaultTextArea.setAttribute("bind", "");
1490:                //defaultTextArea.setAttribute("ref","");
1491:                defaultTextArea.setAttribute("extattr", "");
1492:                defaultTextArea.setAttribute("content", "no");
1493:                Element defaultTextAreaLabel = xformDocument
1494:                        .createElement("xf:label");
1495:                defaultTextArea.appendChild(defaultTextAreaLabel);
1496:                Element defaultTextAreaAlert = xformDocument
1497:                        .createElement("xf:alert");
1498:                Text defaultTextAreaAlertText = xformDocument
1499:                        .createTextNode("");
1500:                defaultTextAreaAlertText.setNodeValue("Error!");
1501:                defaultTextAreaAlert.appendChild(defaultTextAreaAlertText);
1502:                defaultTextArea.appendChild(defaultTextAreaAlert);
1503:
1504:                //select element to clone and create new selects
1505:                Element defaultSelect = xformDocument
1506:                        .createElement("xf:select1");
1507:                defaultSelect.setAttribute("bind", "");
1508:                //defaultSelect.setAttribute("ref","");
1509:                defaultSelect.setAttribute("extattr", "");
1510:                defaultSelect.setAttribute("content", "no");
1511:                Element defaultSelectLabel = xformDocument
1512:                        .createElement("xf:label");
1513:                defaultSelect.appendChild(defaultSelectLabel);
1514:                Element defaultSelectAlert = xformDocument
1515:                        .createElement("xf:alert");
1516:                Text defaultSelectAlertText = xformDocument.createTextNode("");
1517:                defaultSelectAlertText.setNodeValue("Error!");
1518:                defaultSelectAlert.appendChild(defaultSelectAlertText);
1519:                defaultSelect.appendChild(defaultSelectAlert);
1520:                Element defaultSelectChoices = xformDocument
1521:                        .createElement("xf:choices");
1522:                defaultSelect.appendChild(defaultSelectChoices);
1523:
1524:                //select item element to clone and create new select items
1525:                Element defaultSelectItem = xformDocument
1526:                        .createElement("xf:item");
1527:                Element defaultSelectItemLabel = xformDocument
1528:                        .createElement("xf:label");
1529:                defaultSelectItem.appendChild(defaultSelectItemLabel);
1530:                Element defaultSelectItemValue = xformDocument
1531:                        .createElement("xf:value");
1532:                defaultSelectItem.appendChild(defaultSelectItemValue);
1533:                Text defaultSelectItemLabelText = xformDocument
1534:                        .createTextNode("");
1535:                defaultSelectItemLabel.appendChild(defaultSelectItemLabelText);
1536:                Text defaultSelectItemLabelValue = xformDocument
1537:                        .createTextNode("");
1538:                defaultSelectItemValue.appendChild(defaultSelectItemLabelValue);
1539:
1540:                //submit element to clone and create new inputs
1541:                Element defaultSubmit = xformDocument
1542:                        .createElement("xf:submit");
1543:                defaultSubmit.setAttribute("submission", "");
1544:                Element defaultSubmitLabel = xformDocument
1545:                        .createElement("xf:label");
1546:                defaultSubmit.appendChild(defaultSubmitLabel);
1547:
1548:                //project(or activity) name input will be allways the same
1549:                Element projectNameLabel = (Element) defaultLabel
1550:                        .cloneNode(true);
1551:                String realProjectName = projectName.replaceFirst(
1552:                        "_instance.+", "");
1553:                projectNameLabel.setAttribute("id", "projectname");
1554:                Text projectNameLabelText = xformDocument
1555:                        .createTextNode(realProjectName);
1556:                projectNameLabel.appendChild(projectNameLabelText);
1557:                group.appendChild(projectNameLabel);
1558:
1559:                //project version label
1560:                Element projectVersionLabel = (Element) defaultLabel
1561:                        .cloneNode(true);
1562:                projectVersionLabel.setAttribute("id", "projectversion");
1563:                Text projectVersionLabelText = xformDocument
1564:                        .createTextNode(projectVersion);
1565:                projectVersionLabel.appendChild(projectVersionLabelText);
1566:                group.appendChild(projectVersionLabel);
1567:
1568:                //activity name label
1569:                if (activityName != null) {
1570:                    Element activityNameLabel = (Element) defaultLabel
1571:                            .cloneNode(true);
1572:                    activityNameLabel.setAttribute("id", "activityname");
1573:                    Text activityNameLabelText = xformDocument
1574:                            .createTextNode(activityName);
1575:                    activityNameLabel.appendChild(activityNameLabelText);
1576:                    group.appendChild(activityNameLabel);
1577:                }
1578:
1579:                int i; //i will be used also to create activity binds and properties if they exist
1580:
1581:                //project properties
1582:                for (i = 0; i < propertiesChilds.getLength(); i++) {
1583:                    Element property = (Element) propertiesChilds.item(i);
1584:                    NodeList propertyChilds = property.getChildNodes();
1585:                    //get property name
1586:                    //Element propertyNameElement = (Element)propertyChilds.item(0); //property name will be allways in the same position
1587:                    //Text propertyNameText = (Text)propertyNameElement.getFirstChild();
1588:                    //String propertyName = propertyNameText.getNodeValue();
1589:                    String propertyName = property.getAttribute("id");
1590:
1591:                    //get element type
1592:                    Element propertyTypeElement = (Element) propertyChilds
1593:                            .item(1); //property type will be allways in the same position
1594:                    Text propertyTypeText = (Text) propertyTypeElement
1595:                            .getFirstChild();
1596:                    String propertyType = propertyTypeText.getNodeValue();
1597:
1598:                    if (propertyType.equalsIgnoreCase("select")) {
1599:                        //build select node
1600:                        Element tmpSelect = (Element) defaultSelect
1601:                                .cloneNode(true);
1602:                        tmpSelect.setAttribute("extattr", "project");
1603:                        tmpSelect.setAttribute("bind", "b " + propertyName);
1604:                        //tmpSelect.setAttribute("ref","/*[1]/*[2]/*[" + (i+1) + "]/*[2]");
1605:                        //tmpSelect.setAttribute("ref",properties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1606:
1607:                        //set label text
1608:                        Element tmpSelectLabel = (Element) tmpSelect
1609:                                .getFirstChild();
1610:                        Text tmpSelectLabelText = xformDocument
1611:                                .createTextNode(propertyName);
1612:                        tmpSelectLabel.appendChild(tmpSelectLabelText);
1613:
1614:                        //set items labels
1615:                        Element tmpSelectChoices = (Element) tmpSelect
1616:                                .getLastChild();
1617:                        Node propertyPossibleValues = propertyChilds.item(2); //possible values will be allways in the same position
1618:                        NodeList possibleValues = propertyPossibleValues
1619:                                .getChildNodes();
1620:
1621:                        for (int l = 1; l <= possibleValues.getLength(); l++) {
1622:                            Element tmpItem = (Element) defaultSelectItem
1623:                                    .cloneNode(true);
1624:                            //set item label
1625:                            Element tmpSelectItemLabel = (Element) tmpItem
1626:                                    .getFirstChild();
1627:                            //tmpSelectItemLabel.setAttribute("ref","/*[1]/*[2]/*[" + (i+1) + "]/*[4]/*[" + l + "]");
1628:                            //tmpSelectItemLabel.setAttribute("ref",properties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyPossibleValues.getNodeName() + "/possible[" + l + "]");
1629:                            tmpSelectItemLabel.setAttribute("bind", "b "
1630:                                    + propertyName + " choice" + l);
1631:                            //set item value
1632:                            Element tmpSelectItemValue = (Element) tmpItem
1633:                                    .getLastChild();
1634:                            //tmpSelectItemValue.setAttribute("ref","/*[1]/*[2]/*[" + (i+1) + "]/*[4]/*[" + l + "]");
1635:                            //tmpSelectItemValue.setAttribute("ref",properties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyPossibleValues.getNodeName() + "/possible[" + l + "]");
1636:                            tmpSelectItemValue.setAttribute("bind", "b "
1637:                                    + propertyName + " choice" + l);
1638:                            tmpSelectChoices.appendChild(tmpItem);
1639:
1640:                            //add element bind
1641:                            Element tmpBind = (Element) selectChoiceBind
1642:                                    .cloneNode(true);
1643:                            tmpBind.setAttribute("id", "b " + propertyName
1644:                                    + " choice" + l);
1645:                            //tmpBind.setAttribute("nodeset","/*[1]/*[2]/*[" + i + "]/*[2]");
1646:                            tmpBind.setAttribute("nodeset", properties
1647:                                    .getNodeName()
1648:                                    + "/"
1649:                                    + property.getNodeName()
1650:                                    + "[@id='"
1651:                                    + propertyName
1652:                                    + "']/"
1653:                                    + propertyPossibleValues.getNodeName()
1654:                                    + "/"
1655:                                    + possibleValues.item(l - 1).getNodeName()
1656:                                    + "[" + l + "]");
1657:                            model.appendChild(tmpBind);
1658:                        }
1659:                        group.appendChild(tmpSelect);
1660:
1661:                    } else if (propertyType.equalsIgnoreCase("textarea")) {
1662:                        //build textarea node
1663:                        Element tmpTextarea = (Element) defaultTextArea
1664:                                .cloneNode(true);
1665:                        tmpTextarea.setAttribute("extattr", "project");
1666:                        tmpTextarea.setAttribute("bind", "b " + propertyName);
1667:                        //tmpTextarea.setAttribute("ref","/*[1]/*[2]/*[" + (i+1) + "]/*[2]");
1668:                        //tmpTextarea.setAttribute("ref",properties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1669:
1670:                        //set label attributes
1671:                        Element tmpTextareaLabel = (Element) tmpTextarea
1672:                                .getFirstChild();
1673:                        Text tmpTextareaLabelText = xformDocument
1674:                                .createTextNode(propertyName);
1675:                        tmpTextareaLabel.appendChild(tmpTextareaLabelText);
1676:
1677:                        group.appendChild(tmpTextarea);
1678:
1679:                    } else {
1680:                        //build input node
1681:                        Element tmpInput = (Element) defaultInput
1682:                                .cloneNode(true);
1683:                        tmpInput.setAttribute("extattr", "project");
1684:                        tmpInput.setAttribute("bind", "b " + propertyName);
1685:                        //tmpInput.setAttribute("ref","/*[1]/*[2]/*[" + (i+1) + "]/*[2]");
1686:                        //tmpInput.setAttribute("ref",properties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1687:
1688:                        //set label attributes
1689:                        Element tmpInputLabel = (Element) tmpInput
1690:                                .getFirstChild();
1691:                        Text tmpInputLabelText = xformDocument
1692:                                .createTextNode(propertyName);
1693:                        tmpInputLabel.appendChild(tmpInputLabelText);
1694:
1695:                        group.appendChild(tmpInput);
1696:                    }
1697:                    //add element bind
1698:                    Element tmpBind = (Element) nameBind.cloneNode(true);
1699:                    tmpBind.setAttribute("id", "b " + propertyName);
1700:                    //tmpBind.setAttribute("nodeset","/*[1]/*[2]/*[" + i + "]/*[2]");
1701:                    tmpBind.setAttribute("nodeset", properties.getNodeName()
1702:                            + "/" + property.getNodeName() + "[@id='"
1703:                            + propertyName + "']/"
1704:                            + propertyChilds.item(0).getNodeName());
1705:                    tmpBind.setAttribute("readonly", "false()");
1706:                    tmpBind.setAttribute("required", "false()");
1707:                    tmpBind.setAttribute("type", "string");
1708:                    tmpBind.setAttribute("relevant", "true()");
1709:                    model.appendChild(tmpBind);
1710:                    //}
1711:                }
1712:
1713:                //activity properties
1714:                if (activityName != null) {
1715:                    for (int j = i, k = 0; k < activityPropertiesChilds
1716:                            .getLength(); j++, k++) {
1717:                        Element property = (Element) activityPropertiesChilds
1718:                                .item(k);
1719:                        NodeList propertyChilds = property.getChildNodes();
1720:
1721:                        //get property name
1722:                        //Element propertyNameElement = (Element)propertyChilds.item(0); //property name will be allways in the same position
1723:                        //Text propertyNameText = (Text)propertyNameElement.getFirstChild();
1724:                        //String propertyName = propertyNameText.getNodeValue();
1725:                        String propertyName = property.getAttribute("id");
1726:
1727:                        //get element type
1728:                        Element propertyTypeElement = (Element) propertyChilds
1729:                                .item(1); //property type will be allways in the same position
1730:                        Text propertyTypeText = (Text) propertyTypeElement
1731:                                .getFirstChild();
1732:                        String propertyType = propertyTypeText.getNodeValue();
1733:
1734:                        if (propertyType.equalsIgnoreCase("select")) {
1735:                            //build select node
1736:                            Element tmpSelect = (Element) defaultSelect
1737:                                    .cloneNode(true);
1738:                            tmpSelect.setAttribute("extattr", "activity");
1739:                            tmpSelect.setAttribute("bind", "b " + propertyName);
1740:                            //tmpSelect.setAttribute("ref","/*[1]/*[4]/*[" + (k+1) + "]/*[2]");
1741:                            //tmpSelect.setAttribute("ref",activityProperties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1742:
1743:                            //set label attributes
1744:                            Element tmpSelectLabel = (Element) tmpSelect
1745:                                    .getFirstChild();
1746:                            Text tmpSelectLabelText = xformDocument
1747:                                    .createTextNode(propertyName);
1748:                            tmpSelectLabel.appendChild(tmpSelectLabelText);
1749:
1750:                            //set items labels
1751:                            Element tmpSelectChoices = (Element) tmpSelect
1752:                                    .getLastChild();
1753:                            Node propertyPossibleValues = propertyChilds
1754:                                    .item(2); //possible values will be allways in the same position
1755:                            NodeList possibleValues = propertyPossibleValues
1756:                                    .getChildNodes();
1757:
1758:                            for (int l = 1; l <= possibleValues.getLength(); l++) {
1759:                                Element tmpItem = (Element) defaultSelectItem
1760:                                        .cloneNode(true);
1761:                                //set item label
1762:                                Element tmpSelectItemLabel = (Element) tmpItem
1763:                                        .getFirstChild();
1764:                                //tmpSelectItemLabel.setAttribute("ref","/*[1]/*[4]/*[" + (k+1) + "]/*[4]/*[" + l + "]");
1765:                                //tmpSelectItemLabel.setAttribute("ref",activityProperties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyPossibleValues.getNodeName() + "/possible[" + l + "]");
1766:                                tmpSelectItemLabel.setAttribute("bind", "b "
1767:                                        + propertyName + " choice" + l);
1768:                                //set item value
1769:                                Element tmpSelectItemValue = (Element) tmpItem
1770:                                        .getLastChild();
1771:                                //tmpSelectItemValue.setAttribute("ref","/*[1]/*[4]/*[" + (k+1) + "]/*[4]/*[" + l + "]");
1772:                                //tmpSelectItemValue.setAttribute("ref",activityProperties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyPossibleValues.getNodeName() + "/possible[" + l + "]");
1773:                                tmpSelectItemValue.setAttribute("bind", "b "
1774:                                        + propertyName + " choice" + l);
1775:                                tmpSelectChoices.appendChild(tmpItem);
1776:
1777:                                //add element bind
1778:                                Element tmpBind = (Element) selectChoiceBind
1779:                                        .cloneNode(true);
1780:                                tmpBind.setAttribute("id", "b " + propertyName
1781:                                        + " choice" + l);
1782:                                //tmpBind.setAttribute("nodeset","/*[1]/*[2]/*[" + i + "]/*[2]");
1783:                                tmpBind.setAttribute("nodeset",
1784:                                        activityProperties.getNodeName()
1785:                                                + "/"
1786:                                                + property.getNodeName()
1787:                                                + "[@id='"
1788:                                                + propertyName
1789:                                                + "']/"
1790:                                                + propertyPossibleValues
1791:                                                        .getNodeName()
1792:                                                + "/"
1793:                                                + possibleValues.item(l - 1)
1794:                                                        .getNodeName() + "["
1795:                                                + l + "]");
1796:                                model.appendChild(tmpBind);
1797:                            }
1798:                            group.appendChild(tmpSelect);
1799:
1800:                        } else if (propertyType.equalsIgnoreCase("textarea")) {
1801:                            //build textarea node
1802:                            Element tmpTextarea = (Element) defaultTextArea
1803:                                    .cloneNode(true);
1804:                            tmpTextarea.setAttribute("extattr", "activity");
1805:                            tmpTextarea.setAttribute("bind", "b "
1806:                                    + propertyName);
1807:                            //tmpTextarea.setAttribute("ref","/*[1]/*[4]/*[" + (k+1) + "]/*[2]");
1808:                            //tmpTextarea.setAttribute("ref",activityProperties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1809:
1810:                            //set label attributes
1811:                            Element tmpTextareaLabel = (Element) tmpTextarea
1812:                                    .getFirstChild();
1813:                            Text tmpTextareaLabelText = xformDocument
1814:                                    .createTextNode(propertyName);
1815:                            tmpTextareaLabel.appendChild(tmpTextareaLabelText);
1816:
1817:                            group.appendChild(tmpTextarea);
1818:
1819:                        } else {
1820:                            //build input node
1821:                            Element tmpInput = (Element) defaultInput
1822:                                    .cloneNode(true);
1823:                            tmpInput.setAttribute("extattr", "activity");
1824:                            tmpInput.setAttribute("bind", "b " + propertyName);
1825:                            //tmpInput.setAttribute("ref","/*[1]/*[4]/*[" + (k+1) + "]/*[2]");
1826:                            //tmpInput.setAttribute("ref",activityProperties.getNodeName() + "/" + property.getNodeName() + "[@id='" + propertyName + "']/" + propertyChilds.item(0).getNodeName());
1827:
1828:                            //set label attributes
1829:                            Element tmpInputLabel = (Element) tmpInput
1830:                                    .getFirstChild();
1831:                            Text tmpInputLabelText = xformDocument
1832:                                    .createTextNode(propertyName);
1833:                            tmpInputLabel.appendChild(tmpInputLabelText);
1834:
1835:                            group.appendChild(tmpInput);
1836:                        }
1837:                        //add element bind
1838:                        Element tmpBind = (Element) nameBind.cloneNode(true);
1839:                        tmpBind.setAttribute("id", "b " + propertyName);
1840:                        //tmpBind.setAttribute("nodeset","/*[1]/*[4]/*[" + k + "]/*[2]");
1841:                        tmpBind.setAttribute("nodeset", activityProperties
1842:                                .getNodeName()
1843:                                + "/"
1844:                                + property.getNodeName()
1845:                                + "[@id='"
1846:                                + propertyName
1847:                                + "']/"
1848:                                + propertyChilds.item(0).getNodeName());
1849:                        tmpBind.setAttribute("readonly", "false()");
1850:                        tmpBind.setAttribute("required", "false()");
1851:                        tmpBind.setAttribute("type", "string");
1852:                        tmpBind.setAttribute("relevant", "true()");
1853:                        model.appendChild(tmpBind);
1854:                    }
1855:                }
1856:
1857:                //project(or activity) submit will be allways the same
1858:                Element submit = (Element) defaultSubmit.cloneNode(true);
1859:                submit.setAttribute("submission", "bValider");
1860:                //set label value
1861:                Element submitLabel = (Element) submit.getFirstChild();
1862:                Text submitLabelText = xformDocument.createTextNode("Submit");
1863:                submitLabel.appendChild(submitLabelText);
1864:                group.appendChild(submit);
1865:
1866:                //end xform elements
1867:                //end group
1868:
1869:                //call getDocumentFromString to build a valid Chiba's document
1870:                try {
1871:                    String theString = toString(xformDocument);
1872:                    xformDocument = getDocumentFromString(theString);
1873:                } catch (Exception e) {
1874:                    e.printStackTrace();
1875:                    throw new Exception("ServletBonitaForm.createXform");
1876:                }
1877:
1878:                return (xformDocument);
1879:            }
1880:
1881:            protected String getErrors(Throwable t) {
1882:                String mes = "";
1883:                if (t != null) {
1884:                    if (t.getCause() != null)
1885:                        mes = mes + "\n\nCause:\n\n" + t.getCause();
1886:                    StackTraceElement[] aStacks = t.getStackTrace();
1887:                    if (0 < aStacks.length) {
1888:                        mes = mes + "\n\nDetail:\n\n";
1889:                        for (int i = 0; i < aStacks.length; i++) {
1890:                            mes = mes + aStacks[i].toString() + "\n";
1891:                        }
1892:                    }
1893:                }
1894:                return (mes);
1895:            }
1896:
1897:            // saveErrors:
1898:            // since a trace stack may be too large to successfully transmit back to
1899:            // a calling external application via a request object, we write the
1900:            // stack and any other relevant error message information to a file
1901:            // with specific delimiters. Currently, the delimiter is the 'Detail:'
1902:            // string which represents the break between the error message and the
1903:            // trace stack report. By saving the error data in a file, the calling
1904:            // application can read the file in order to subsequently display the
1905:            // error (if the 'processError' request attribute is set to 'saved'.
1906:            protected String saveErrors(Throwable t) {
1907:                String mes = "";
1908:                long curTime = 0;
1909:                String saveTime = "";
1910:                if (t != null) {
1911:                    if (t.getMessage() != null)
1912:                        mes = mes + t.getMessage();
1913:                    StackTraceElement[] aStacks = t.getStackTrace();
1914:                    if (0 < aStacks.length) {
1915:                        mes = mes + "\n\nDetail:\n\n";
1916:                        for (int i = 0; i < aStacks.length; i++) {
1917:                            mes = mes + aStacks[i].toString() + "\n";
1918:                        }
1919:                    }
1920:                    //save the error so that a calling application can read it - if need be!
1921:                    try {
1922:                        java.util.Date curDate = new java.util.Date();
1923:                        curTime = curDate.getTime();
1924:                        saveTime = Long.toString(curTime);
1925:                        ReadEnv re = new ReadEnv();
1926:                        String saveErrorPath = re.getVariable("BONITA_HOME")
1927:                                + File.separator + ".formerr-" + saveTime;
1928:                        java.io.BufferedWriter bw = new BufferedWriter(
1929:                                new FileWriter(saveErrorPath));
1930:                        bw.write(mes);
1931:                        bw.close();
1932:                    } catch (IOException io) {
1933:                        io.printStackTrace();
1934:                    } catch (Exception e) {
1935:                        e.printStackTrace();
1936:                    }
1937:                }
1938:                return (saveTime);
1939:            }
1940:
1941:            private static String toXmlString(Document document) {
1942:                try {
1943:                    OutputFormat outputFormat = new OutputFormat(document,
1944:                            FormGeneratorConstant.DEBUG_OUTPUT_FORMAT_ENCODING,
1945:                            true);
1946:                    outputFormat.setIndenting(true);
1947:                    outputFormat.setIndent(1);
1948:                    outputFormat.setPreserveSpace(true);
1949:                    StringWriter writer = new StringWriter();
1950:                    DOMSerializer serializer = new XMLSerializer(writer,
1951:                            outputFormat);
1952:                    serializer.serialize(document);
1953:                    writer.close();
1954:                    return writer.toString();
1955:                } catch (Exception ex) {
1956:                    ex.printStackTrace();
1957:                }
1958:                return null;
1959:            }
1960:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.