Generates HTML code

@exception Exception XML exception
346465
@Override
    public Sequences generate() {
        Sequences seq = new Sequences();

        seq.addVar(new Var("output", this.getProperty("output").value));
        try {
            new ProgramBehaviorGenerator(browser).generateFSMProgramBehaviorClasses(seq);
            new AgentsGenerator(browser).generateAgents(seq);
            new TaskGenerator(getBrowser(), seq).generateAllSeqTasks();
            new ActivityGenerator(getBrowser()).generateTimeIntervals(seq);
            new SymptomEvolutionGenerator(browser).generateFSMSymptomEvolutionClasses(seq);
            new SimulationGenerator(browser).generateSimulations(seq);
            GraphEntity[] entities = browser.getAllEntities();
            Vector<String> errors = new Vector<String>();
            for (GraphEntity norm : entities) {
                Repeat ruleRep = null;
                if (norm.getType().equals("ConsecutiveActions")) {
                    if (norm.getAttributeByName("Deontic") != null
                            && norm.getAttributeByName("Deontic").getSimpleValue().toLowerCase().contains("must not")) {
                        ruleRep = new Repeat("normsmustnot");
                    } else {
                        if (norm.getAttributeByName("Deontic") != null
                                && norm.getAttributeByName("Deontic").getSimpleValue().toLowerCase().contains("must")) {
                            ruleRep = new Repeat("normsmust");
                        } else {
                            ruleRep = new Repeat("normsmay");
                        }
                    }
                    seq.addRepeat(ruleRep);
                    ruleRep.add(new Var("normname", Utils.replaceBadChars(norm.getID())));
                    GraphEntity[] actionconditions = Utils.getRelatedElements(norm, "ActionHappeningAfterwards", "ActionHappeningAfterwardstarget");
                    if (actionconditions.length > 1) {
                        errors.add("There should be only one instance of ActionsHappeningAfterwards connected to " + norm);
                    }

                    if (actionconditions.length == 0) {
                        errors.add("There should one instance of ActionsHappeningAfterwards connected to " + norm);
                    }
                    if (errors.isEmpty()) {
                        GraphEntity[] roleCondition = Utils.getRelatedElements(actionconditions[0], "ActionResponsible", "ActionResponsibletarget");

                        ruleRep.add(new Var("normtimewindow", Utils.replaceBadChars(actionconditions[0].getAttributeByName("WithinTheTimeWindow").getSimpleValue())));
                        ;
                        if (roleCondition.length == 0) {
                            errors.add("There should one instance of Human connected to " + actionconditions[0]);
                        }
                        if (roleCondition.length > 1) {
                            errors.add("There should only one instance of Human connected to " + actionconditions[0]);
                        }
                        if (errors.isEmpty()) {
                            ruleRep.add(new Var("normrolecondition", Utils.replaceBadChars(roleCondition[0].getID())));
                        }

                        GraphEntity[] actionCondition = Utils.getRelatedElements(actionconditions[0], "AffectedAction", "AffectedActiontarget");
                        if (actionCondition.length == 0) {
                            errors.add("There should one instance of Task connected to " + actionconditions[0]);
                        }
                        if (errors.isEmpty()) {
                            for (GraphEntity action : actionCondition) {
                                Repeat normactioncondition = new Repeat("normscondition");
                                ruleRep.add(normactioncondition);
                                normactioncondition.add(new Var("normactioncondition", Utils.replaceBadChars(action.getType())));
                            }
                        }

                        GraphEntity[] deonticAction = Utils.getRelatedElements(norm, "DeonticAssignement", "DeonticAssignementtarget");
                        if (deonticAction.length == 0) {
                            errors.add("There should one instance of Task connected to " + norm);
                        }
                        if (deonticAction.length > 1) {
                            errors.add("There should only one instance of Task connected to " + norm);
                        }
                        if (errors.isEmpty()) {
                            ruleRep.add(new Var("normdeonticaction", Utils.replaceBadChars(deonticAction[0].getType())));
                        }

                        GraphEntity[] normroles = Utils.getRelatedElements(norm, "Role", "Roletarget");
                        if (deonticAction.length == 0) {
                            errors.add("There should one instance of Human connected to " + norm);
                        }
                        if (deonticAction.length > 1) {
                            errors.add("There should only one instance of Human connected to " + norm);
                        }
                        if (errors.isEmpty()) {
                            ruleRep.add(new Var("normrole", Utils.replaceBadChars(normroles[0].getID())));
                        }

                    }
                }
                if (!errors.isEmpty()) {
                    this.fatalError();
                    for (String error : errors) {
                        Log.getInstance().logERROR(error);
                    }
                }
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        return seq;
    }
992551
@Override
    public String execute(EditXmlInputs inputs) throws Exception {
        Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
        NamespaceContext ctx = XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath());
        NodeList nodeListToMove = XmlUtils.readNode(doc, inputs.getXpath1(), ctx);
        NodeList nodeListWhereToMove = XmlUtils.readNode(doc, inputs.getXpath2(), ctx);
        Node nodeToMove;
        Node nodeWhereToMove;

        if (!inputs.getXpath2().contains(inputs.getXpath1())) {
            // remove nodes
            for (int i = 0; i < nodeListToMove.getLength(); i++) {
                nodeToMove = nodeListToMove.item(i);
                if (nodeToMove != doc.getDocumentElement()) {
                    nodeToMove.getParentNode().removeChild(nodeToMove);
                }
            }
            //add nodes to designated location
            for (int i = 0; i < nodeListWhereToMove.getLength(); i++) {
                nodeWhereToMove = nodeListWhereToMove.item(i);
                for (int j = 0; j < nodeListToMove.getLength(); j++) {
                    nodeToMove = nodeListToMove.item(j);
                    nodeToMove = doc.importNode(nodeToMove, true);
                    nodeWhereToMove.appendChild(nodeToMove);
                }
            }
        }
        return DocumentUtils.documentToString(doc);
    }
1100037
private void showRobotsTxt() throws Exception {

        CmsObject cms = getCmsObject();
        StringBuffer buffer = new StringBuffer();
        I_CmsResourceType seoFileType = OpenCms.getResourceManager().getResourceType(
            CmsXmlSeoConfiguration.SEO_FILE_TYPE);
        List<CmsResource> seoFiles = cms.readResources(
            "/",
            CmsResourceFilter.DEFAULT_FILES.addRequireVisible().addRequireType(seoFileType));
        for (CmsResource seoFile : seoFiles) {
            try {
                if (seoFile.getName().contains("test")) {
                    continue;
                }
                CmsXmlSeoConfiguration seoFileConfig = new CmsXmlSeoConfiguration();
                seoFileConfig.load(cms, seoFile);
                if (seoFileConfig.isXmlSitemapMode()) {
                    buffer.append(
                        "Sitemap: "
                            + CmsXmlSitemapGenerator.replaceServerUri(
                                OpenCms.getLinkManager().getOnlineLink(cms, cms.getSitePath(seoFile)),
                                m_configuration.getServerUrl()));
                    buffer.append("\n");
                }
            } catch (CmsException e) {
                LOG.error("Error while generating robots.txt : " + e.getLocalizedMessage(), e);
            }
        }
        buffer.append("\n");
        buffer.append(m_configuration.getRobotsTxtText());
        buffer.append("\n");
        getResponse().getWriter().print(buffer.toString());
    }
1202262
public int doEndTag() throws JspException
    {
        // report errors that may have occurred when the required attributes are being set
        if (hasErrors())
            return reportAndExit(EVAL_PAGE);

        // build the anchor into the results
        ByRef script = new ByRef();

        WriteRenderAppender writer = new WriteRenderAppender(pageContext);
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        TagRenderingBase trb = TagRenderingBase.Factory.getRendering(TagRenderingBase.AREA_TAG, request);

        if (!createAnchorBeginTag(request, script, trb, writer, REQUIRED_ATTR)) {
            if (!script.isNull())
                write(script.getRef().toString());
            return reportAndExit(EVAL_PAGE);
        }

        assert(trb != null) : "trb is null";
        trb.doEndTag(writer);

        if (!script.isNull())
            write(script.getRef().toString());

        // Render the remainder to the output stream
        localRelease();
        return EVAL_PAGE;
    }
709124
public void render(Map<String, Object> content) throws Exception {
        String docType = (String) content.get(Crawler.Attributes.TYPE);
        String outputFilename = config.getDestinationFolder().getPath() + File.separatorChar + content.get(Attributes.URI);
        if (outputFilename.lastIndexOf('.') > outputFilename.lastIndexOf(File.separatorChar)) {
            outputFilename = outputFilename.substring(0, outputFilename.lastIndexOf('.'));
        }

        // delete existing versions if they exist in case status has changed either way
        String outputExtension = config.getOutputExtensionByDocType(docType);
        File draftFile = new File(outputFilename, config.getDraftSuffix() + outputExtension);
        if (draftFile.exists()) {
            draftFile.delete();
        }

        File publishedFile = new File(outputFilename + outputExtension);
        if (publishedFile.exists()) {
            publishedFile.delete();
        }

        if (content.get(Crawler.Attributes.STATUS).equals(Crawler.Attributes.Status.DRAFT)) {
            outputFilename = outputFilename + config.getDraftSuffix();
        }

        File outputFile = new File(outputFilename + outputExtension);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("content", content);
        model.put("renderer", renderingEngine);

        try {
            try (Writer out = createWriter(outputFile)) {
                renderingEngine.renderDocument(model, findTemplateName(docType), out);
            }
            LOGGER.info("Rendering [{}]... done!", outputFile);
        } catch (Exception e) {
            LOGGER.error("Rendering [{}]... failed!", outputFile, e);
            throw new Exception("Failed to render file " + outputFile.getAbsolutePath() + ". Cause: " + e.getMessage(), e);
        }
    }
642596
@Override
    public String execute(EditXmlInputs inputs) throws Exception {
        Document doc = XmlUtils.createDocument(inputs.getXml(), inputs.getFilePath(), inputs.getParsingFeatures());
        NodeList nodeList = XmlUtils.readNode(doc, inputs.getXpath1(), XmlUtils.getNamespaceContext(inputs.getXml(), inputs.getFilePath()));
        Node childNode = null;
        Node node;
        Node parentNode;
        // create new Node to insert
        if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
            childNode = XmlUtils.stringToNode(inputs.getValue(), doc.getXmlEncoding(), inputs.getParsingFeatures());
        }

        for (int i = 0; i < nodeList.getLength(); i++) {
            node = nodeList.item(i);
            if (Constants.Inputs.TYPE_ELEM.equals(inputs.getType())) {
                //check if provided xpath doesn't contain root node
                if (node != doc.getDocumentElement()) {
                    childNode = doc.importNode(childNode, true);
                    parentNode = node.getParentNode();
                    parentNode.insertBefore(childNode, node);
                }
            } else if (Constants.Inputs.TYPE_TEXT.equals(inputs.getType())) {
                node.setTextContent(inputs.getValue() + node.getTextContent());
            } else if (Constants.Inputs.TYPE_ATTR.equals(inputs.getType())) {
                ((Element) node).setAttribute(inputs.getName(), inputs.getValue());
            }
        }
        return DocumentUtils.documentToString(doc);
    }
1365791
public static function getHtmlForException(\Throwable $exception)
    {
        //global $sys_error_reporting_mail;
        //global $sys_error_messages;
        $msg = '';

        $msg = '<table>';

        $display_errors = ini_get('display_errors');
        $color = '#FF0000';
        $type = 'Uncaught '.get_class($exception);
        if ($exception->getCode() != null) {
            $type .= ' with error code '.$exception->getCode();
        }

        $msg .= "<tr><td colspan='3' style='background-color:$color; color:white; text-align:center'><b>$type</b></td></tr>";

        $msg .= "<tr><td style='background-color:#AAAAAA; color:white; text-align:center'>Context/Message</td>";
        $msg .= "<td style='background-color:#AAAAAA; color:white; text-align:center'>File</td>";
        $msg .= "<td style='background-color:#AAAAAA; color:white; text-align:center'>Line</td></tr>";

        $msg .= "<tr><td style='background-color:#EEEEEE; color:black'><b>".nl2br($exception->getMessage()).'</b></td>';
        $msg .= "<td style='background-color:#EEEEEE; color:black'>".self::displayFile($exception->getFile()).'</td>';
        $msg .= "<td style='background-color:#EEEEEE; color:black'>".$exception->getLine().'</td></tr>';
        $msg .= self::getHTMLBackTrace($exception->getTrace());
        $msg .= '</table>';

        return $msg;
    }
92760
@Override
    public void doRender(Invocation inv) throws Exception {
        if (StringUtils.isEmpty(text)) {
            return;
        }
        
        if (logger.isDebugEnabled()) {
        	logger.debug("trying to render text:" + text);
        }
        
        HttpServletResponse response = inv.getResponse();
        String oldEncoding = response.getCharacterEncoding();
        if (StringUtils.isBlank(oldEncoding) || oldEncoding.startsWith("ISO-")) {
            String encoding = inv.getRequest().getCharacterEncoding();
            Assert.isTrue(encoding != null);
            response.setCharacterEncoding(encoding);
            if (logger.isDebugEnabled()) {
                logger.debug("set response.characterEncoding by default:"
                        + response.getCharacterEncoding());
            }
        }
        
        if (response.getContentType() == null) {
            response.setContentType("text/html");
            if (logger.isDebugEnabled()) {
                logger.debug("set response content-type by default: "
                        + response.getContentType());
            }
        }
        sendResponse(response, text);
    }
288428
private void createHtmlDoc() throws PrompterException {
        HtmlDocConfiguration configuration = new HtmlDocConfiguration();

        String heading = prompter.prompt("Enter overview title:", configuration.getHeading());
        String columns = prompter.prompt("Enter number of columns in overview:", configuration.getColumns());
        String pageTitle = prompter.prompt("Enter page title:", configuration.getPageTitle());
        String outputFile = prompter.prompt("Enter output file name:", configuration.getOutputFile());
        String logo = prompter.prompt("Enter file path to logo:", configuration.getLogo());

        String confirm = prompter.prompt("Confirm HTML documentation: outputFile='target/" + outputFile + (outputFile.endsWith(".html") ? "" : ".html") + "'\n",
                Arrays.asList("y", "n"), "y");

        if (confirm.equalsIgnoreCase("n")) {
            return;
        }

        HtmlTestDocsGenerator generator = getHtmlTestDocsGenerator();

        generator.withOutputFile(outputFile + (outputFile.endsWith(".html") ? "" : ".html"))
                .withPageTitle(pageTitle)
                .withOverviewTitle(heading)
                .withColumns(columns)
                .useSrcDirectory(getTestSrcDirectory())
                .withLogo(logo);

        generator.generateDoc();

        getLog().info("Successfully created HTML documentation: outputFile='target/" + outputFile + (outputFile.endsWith(".html") ? "" : ".html") + "'");
    }
1173199
protected synchronized void generateXML(String rootLoc, String serverName, 
                               WebContainer container,
                               SessionManager smgr,
                               DynamicVirtualHostManager vhostMgr,
                               WsLocationAdmin locationService,
                               boolean utilityReq,
                               File writeDirectory) {
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "generateXML", "server = " + serverName + ", Framework is stopping = " + FrameworkState.isStopping() + ", pcd = " + pcd + ", this = " + this);
        }

        // Because this method is synchronized there can become a queue of requests waiting which then don't get started
        // for a significant time period. As a result if the servers is now shutting down skip generation.
        if (pcd == null || FrameworkState.isStopping() || container.isServerStopping()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "generateXML", ((FrameworkState.isStopping() || container.isServerStopping()) ? "Server is stopping" : "pcd is null"));
            }
            // add error message in next update
            return;
        }    
        utilityRequest = utilityReq;
        boolean writeFile = true;

        // set up server names, preserving original behavior for explicit (mbean) requests
        if (!utilityRequest) {
            appServerName = serverName;
            webServerName = serverName;
        } else {
            appServerName = locationService.getServerName();
            webServerName = pcd.webServerName;
        }

        BufferedWriter pluginCfgWriter = null;
        WsResource outFile = null;
        FileOutputStream fOutputStream = null;
        try {
            
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Generating webserver plugin cfg for server=" + appServerName);
            }

            String root = rootLoc;
            boolean userOverrideLocation = true;
            if(root == null){
                root = pcd.PluginInstallRoot;
                userOverrideLocation = false;
            }
            //String root = (null == rootLoc) ? pcd.PluginInstallRoot : rootLoc;
            Map<String,Map<String,Set<URIData>>> clusterUriGroups = new HashMap<String,Map<String,Set<URIData>>>();

            Document output = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

            SimpleDateFormat tmpDateFmt = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z");
            Comment comment = output.createComment(String.format("HTTP server plugin config file for %s generated on %s",
                                                                 appServerName,
                                                                 tmpDateFmt.format(new Date())));
            output.appendChild(comment);

            // create and insert a config root element
            Element rootElement = output.createElement("Config");
            
            // add in hardcoded properties and any extra properties from the user configuration
            if (!pcd.extraConfigProperties.isEmpty())
            {
                if(pcd.TrustedProxyEnable != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Overriding TrustedProxyEnable from extra config properties with the specified value");
                    }
                    pcd.extraConfigProperties.put("TrustedProxyEnable", pcd.TrustedProxyEnable.toString());
                }
                
                for (String key : pcd.extraConfigProperties.keySet()) {
                    String value = (String)pcd.extraConfigProperties.get(key);
                    rootElement.setAttribute(key, value);                    
                }
            }
            output.appendChild(rootElement);
            
            // add log Information
            Element elem = output.createElement("Log");
            //start 142740
            
            // If user provided install root as argument, use that to generate the log location
            String name = null;
            if(userOverrideLocation){
                name = root + addSlash(root)
                                + "logs" + File.separatorChar
                                + webServerName + File.separatorChar + pcd.LogFile;;
            }  // otherwise use configured value, with LogFileName taking precedence over LogDirLocation
            else {
                if (pcd.LogFileName != null)
                    name = pcd.LogFileName;
                else
                    name = pcd.LogDirLocation + addSlash(pcd.LogDirLocation) + pcd.LogFile;
            }
                            
            if(name.charAt(1) == ':') //check if path specified is a windows path or not and replace File.separatorChar with correct separators 
                name = name.replace('/', '\\');
            else
                name = name.replace('\\', '/');
            
            elem.setAttribute("Name", name);
            //end 142740
            elem.setAttribute("LogLevel", pcd.LogLevel);
            rootElement.appendChild(elem);

            // add esi properties
            Element esiProp1 = output.createElement("Property");
            esiProp1.setAttribute("Name", "ESIEnable");
            esiProp1.setAttribute("Value", pcd.ESIEnable.toString());
            rootElement.appendChild(esiProp1);

            Element esiProp2 = output.createElement("Property");
            esiProp2.setAttribute("Name", "ESIMaxCacheSize");
            esiProp2.setAttribute("Value", pcd.ESIMaxCacheSize.toString());
            rootElement.appendChild(esiProp2);

            Element esiProp3 = output.createElement("Property");
            esiProp3.setAttribute("Name", "ESIInvalidationMonitor");
            esiProp3.setAttribute("Value", pcd.ESIInvalidationMonitor.toString());
            rootElement.appendChild(esiProp3);

            Element esiProp4 = output.createElement("Property");
            esiProp4.setAttribute("Name", "ESIEnableToPassCookies");
            esiProp4.setAttribute("Value", pcd.ESIEnableToPassCookies.toString());
            rootElement.appendChild(esiProp4);

            Element esiProp5 = output.createElement("Property");
            esiProp5.setAttribute("Name", "PluginInstallRoot");
            esiProp5.setAttribute("Value", root);
            rootElement.appendChild(esiProp5);

            // Reference to http endpoint the plugin should use
            HttpEndpointInfo httpEndpointInfo = new HttpEndpointInfo(context, output, pcd.httpEndpointPid);

            // Map of virtual host name to the list of alias data being collected...
            Map<String, List<VHostData>> vhostAliasData = new HashMap<String, List<VHostData>>();

            // Process the virtual host configuration.. 
            Set<DynamicVirtualHost> virtualHostSet = processVirtualHosts(vhostMgr, vhostAliasData, httpEndpointInfo, rootElement);

            // Create the VirtualHostGroup and VirtualHost elements 
            for( DynamicVirtualHost vh : virtualHostSet ) {
                // Create the VirtualHostGroup in the plugin xml
                Element vhElem = output.createElement("VirtualHostGroup");
                vhElem.setAttribute("Name", vh.getName());
                rootElement.appendChild(vhElem);   
                                
                if(!vhostAliasData.containsKey(vh.getName())){
                    continue;
                }
                // Create a VirtualHost element for each alias
                for ( VHostData vh_aliasData : vhostAliasData.get(vh.getName())) {
                    Element aliasElem = output.createElement("VirtualHost");
                    // The IPv6 is already has the [] in alias
                    aliasElem.setAttribute("Name", vh_aliasData.host + ":" + vh_aliasData.port);
                    vhElem.appendChild(aliasElem);
                }
            }

            if (pcd.TrustedProxyGroup != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Adding custom property TrustedProxyGroup element and its associated proxy servers");
                }

                Element tproxyGroupElem = output.createElement("TrustedProxyGroup");
                rootElement.appendChild(tproxyGroupElem);
                for (String trustedProxy : pcd.TrustedProxyGroup) {
                    Element tproxyElem = output.createElement("TrustedProxy");
                    if (trustedProxy.indexOf(":") != -1) {
                        // IPV6
                        tproxyElem.setAttribute("Name", "[" + trustedProxy.trim() + "]" );
                    } else {
                        tproxyElem.setAttribute("Name", trustedProxy.trim() );
                    }
                    tproxyGroupElem.appendChild(tproxyElem);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Added proxy server " + trustedProxy + " TrustedProxyGroup element" );
                    }
                }
            } // end-trusted-proxy

            // define all server clusters
            // config of server clusters
            String serverID = smgr.getCloneID();
            boolean singleServerConfig = true;
            if(serverID==null) {
                serverID = "";
            }
            if(serverID.length()>0) {
                // if the clone ID is defined, assume that session affinity matters
                singleServerConfig = false;
            }
            char cloneSep = smgr.getCloneSeparator();
            Boolean cloneSeparatorChange = null;
            if(':'==cloneSep) {
                cloneSeparatorChange = Boolean.FALSE;
            } else if('+'==cloneSep) {
                cloneSeparatorChange = Boolean.TRUE;
            } else {
                throw new IllegalStateException("The session manager is configured to use '"+cloneSep+"' as the clone separator, but "+pcd.PluginConfigFileName+" only supports ':' and '+'.");
            }
            pcd.cloneSeparatorChange = cloneSeparatorChange;

            Element pServersElem = null;
            Element bServersElem = null;
            int numberOfPrimaryServers = 0;
            int numberOfBackupServers = 0;


            // ------------- SERVER CLUSTER ---------------------
            // A Liberty server can only belong to one cluster
            ServerClusterData scd = pcd.createServerCluster(appServerName + "_" + GeneratePluginConfig.DEFAULT_NODE_NAME + "_Cluster", singleServerConfig);

            // get the server cluster data
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Adding the ServerCluster " + scd.clusterName);
            }
            scd.print(tc);

            // define the server cluster element
            Element sgElem = output.createElement("ServerCluster");

            // Set cluster attributes
            // name is node_server
            sgElem.setAttribute("Name", scd.clusterName);
            sgElem.setAttribute("LoadBalance", scd.loadBalance);
            if (pcd.ignoreAffinityRequests != null) {
                sgElem.setAttribute("IgnoreAffinityRequests", pcd.ignoreAffinityRequests.toString());
            }
            sgElem.setAttribute("RetryInterval", scd.retryInterval.toString());
            sgElem.setAttribute("ServerIOTimeoutRetry", scd.serverIOTimeoutRetry.toString());
            sgElem.setAttribute("RemoveSpecialHeaders", scd.removeSpecialHeaders.toString());
            sgElem.setAttribute("CloneSeparatorChange", scd.cloneSeparatorChange.toString());
            sgElem.setAttribute("PostSizeLimit", scd.postSizeLimit.toString());
            sgElem.setAttribute("PostBufferSize", scd.postBufferSize.toString());
            // retrieve Partition Table when HA-Based Session mgt is configured
            sgElem.setAttribute("GetDWLMTable", scd.GetDWLMTable.toString());

            // define a primary server element if this is a multi server gen
            if (false == scd.singleServerConfig.booleanValue()) {
                pServersElem = output.createElement("PrimaryServers");
                bServersElem = output.createElement("BackupServers");
            }

            if ( !httpEndpointInfo.isValid() ) {
                // We couldn't find a matching endpoint -- there will be bits missing from 
                // the generated plugin config as a result
                comment = output.createComment( " The configured endpoint could not be found. httpEndpointRef=" + httpEndpointInfo.getEndpointId());
                rootElement.appendChild(comment);
            } else {
                // This is unique to liberty: we put the endpoint (http/https) in its 
                // own server. (this behavior has existed since 8.5.0.. )
                // As of 8.5.5.2, we will use only one endpoint, so that a single plugin configuration
                // will contain only one server definition (which is good because there was only one server id.. )
                
                buildServerTransportData(appServerName, serverID, httpEndpointInfo, scd.clusterServers, pcd.IPv6Preferred);

                // create a server element for each server in the cluster
                for (ServerData sd : scd.clusterServers) {
                    // get the server data
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Adding the Server definition " + sd.nodeName + "_" + sd.serverName);
                    }
                    sd.print(tc);
                    
                    // create a server element for the server
                    Element serverElem = output.createElement("Server");
                    serverElem.setAttribute("Name", sd.nodeName+"_"+sd.serverName);

                    // add weight and clone id if multi server generation
                    if (false == scd.singleServerConfig.booleanValue()) {
                        
                        serverElem.setAttribute("LoadBalanceWeight", sd.loadBalanceWeight.toString());
                        
                        if (0 < sd.serverID.length()) {
                            serverElem.setAttribute("CloneID", sd.serverID);
                        }
                    }
                    // Set server attributes
                    // Could not find the best match values in liberty now, so just use the default value of metatype
                    serverElem.setAttribute("ConnectTimeout", sd.connectTimeout.toString());
                    serverElem.setAttribute("ServerIOTimeout", sd.serverIOTimeout.toString());
                    if (sd.wsServerIOTimeout!=null)
                        serverElem.setAttribute("wsServerIOTimeout", sd.wsServerIOTimeout.toString());
                    if (sd.wsServerIdleTimeout!=null)
                        serverElem.setAttribute("wsServerIdleTimeout", sd.wsServerIdleTimeout.toString());
                    serverElem.setAttribute("WaitForContinue", sd.waitForContinue.toString());
                    serverElem.setAttribute("MaxConnections", sd.maxConnections.toString());
                    serverElem.setAttribute("ExtendedHandshake", sd.extendedHandshake.toString());

                    sgElem.appendChild(serverElem);

                    if (sd.transports != null) {
                        // define its transports
                        for (TransportData currentTransport : sd.transports) {
                            Element tElem = output.createElement("Transport");
                            String hostname = currentTransport.host;

                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "Adding the Transport definition " + hostname);
                            }
                            currentTransport.print(tc);

                            tElem.setAttribute("Hostname", hostname);
                            String transportPort = Integer.toString(currentTransport.port);
                            tElem.setAttribute("Port", transportPort);

                            if (currentTransport.isSslEnabled) {
                                tElem.setAttribute("Protocol", "https");

                                Element sslProp1 = output.createElement("Property");
                                sslProp1.setAttribute("Name", "keyring");
                                sslProp1.setAttribute("Value", pcd.KeyringLocation);
                                tElem.appendChild(sslProp1);

                                Element sslProp2 = output.createElement("Property");
                                sslProp2.setAttribute("Name", "stashfile");
                                sslProp2.setAttribute("Value", pcd.StashfileLocation);
                                tElem.appendChild(sslProp2);

                                if (pcd.CertLabel != null) {
                                    Element sslProp3 = output.createElement("Property");
                                    sslProp3.setAttribute("Name", "certLabel");
                                    sslProp3.setAttribute("Value", pcd.CertLabel);
                                    tElem.appendChild(sslProp3);
                                }
                            } else {
                                tElem.setAttribute("Protocol", "http");
                            }

                            serverElem.appendChild(tElem);
                        }
                    }

                    // append the server cluster element to the root
                    rootElement.appendChild(sgElem);


                    // add the server to the primary servers if this is a multi
                    // server gen
                    if (false == scd.singleServerConfig.booleanValue()) {
                        Element psServerElem = output.createElement("Server");
                        psServerElem.setAttribute("Name", sd.nodeName + "_" + sd.serverName);

                        // Check if the current server is primary or backup
                        if (sd.roleKind == Role.PRIMARY) {
                            pServersElem.appendChild(psServerElem);
                            numberOfPrimaryServers++;
                        } else {
                            bServersElem.appendChild(psServerElem);
                            numberOfBackupServers++;
                        }
                    }
                } // end of for processing each server
            } // end of if we had an endpoint reference

            // append the primary servers if this is a multi server gen
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Number of primary servers: "
                                + numberOfPrimaryServers
                                + " Number of backup servers: "
                                + numberOfBackupServers);
            }

            if (false == scd.singleServerConfig.booleanValue()) {
                if (numberOfPrimaryServers > 0) {
                    sgElem.appendChild(pServersElem);
                }
                if (numberOfBackupServers > 0) {
                    sgElem.appendChild(bServersElem);
                }
            }

            // process the deployed modules for each server cluster (same
            // across all servers in a cluster)
            // deployed module config
            String defaultAffinityCookie = smgr.getDefaultAffinityCookie();
            String affinityUrlIdentifier = smgr.getAffinityUrlIdentifier();

            // all virtual hosts are in the same cluster 
            for(DynamicVirtualHost vhost : virtualHostSet) {
                for(Iterator<?> apps = vhost.getWebApps(); apps.hasNext(); ) {
                    WebApp app = (WebApp) apps.next();
                    // a timing window is possible where a wepp app of "null" is in the list.
                    if (app!=null) {
                         DeployedModuleData dmd = new DeployedModuleData(app, defaultAffinityCookie, affinityUrlIdentifier);
                         scd.deployedModules.add(dmd);
                    }     
                }           
            }

            Map<String,Set<URIData>> uriGroups = new HashMap<String,Set<URIData>>();
            List<String> webGroupIDs = new LinkedList<String>();
            // Check if any applications are deployed on the cluster
            if (!scd.deployedModules.isEmpty()) {
                for (DeployedModuleData dmd : scd.deployedModules) {
                    dmd.print(tc);

                    if (dmd.moduleConfig == null) {
                        continue;
                    }

                    String contextRoot = dmd.moduleConfig.getContextRoot();
                    if (!contextRoot.startsWith("/"))
                        contextRoot = "/" + contextRoot;

                    //String lvh = dmd.moduleBindings.getVirtualHostName();
                    String lvh = dmd.moduleConfig.getVirtualHostName();

                    if (lvh == null || 0 == lvh.length()) {
                        lvh = DEFAULT_VIRTUAL_HOST;
                    }

                    if (!uriGroups.containsKey(lvh)) {
                        uriGroups.put(lvh, new LinkedHashSet<URIData>());
                    }

                    Set<URIData> uriList = uriGroups.get(lvh);
                    // form the web group index and warn if a duplicate context root is being used
                    String wgIndex = lvh + contextRoot;

                    if (webGroupIDs.contains(wgIndex)) {
                        if (utilityRequest) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "duplicate.context.root", contextRoot);
                            }
                        } else 
                        Tr.warning(tc, "duplicate.context.root", contextRoot);                       
                    }

                    // add index for future reference
                    webGroupIDs.add(wgIndex);

                    // Enable File Serving by default
                    // file serving enabled...just add the context root
                    // does not considerate file serving disable!!!
                    String newContextRoot = appendWildCardString(contextRoot);
                    uriList.add(new URIData(newContextRoot, dmd.cookieName, dmd.urlCookieName));

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Computed URIs for the module " + dmd.moduleConfig.getDisplayName());
                    }
                } // end of while processing each deployed module
            }

            // put the cluster's uri groups into the cluster uri hash table,
            // indexed by the cluster
            clusterUriGroups.put(scd.clusterName, uriGroups);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Added the ServerCluster elements");
            }

            // output the uri group and route elements for each cluster
            Set<ClusterUriGroup> cUgsSet = new HashSet<ClusterUriGroup>();

            for(Map.Entry<String, Map<String, Set<URIData>>> entry : clusterUriGroups.entrySet()) {
                String clusterName = entry.getKey();
                uriGroups = entry.getValue();

                String lvh = null;
                Set<URIData> uriList = null;
                // iterate through the uri groups
                for(Map.Entry<String , Set<URIData>> ugEntry : uriGroups.entrySet()) {
                    lvh = ugEntry.getKey();
                    uriList = ugEntry.getValue();

                    Element ugElem = output.createElement("UriGroup");
                    String uriGroupName = lvh + "_" + clusterName + "_URIs";
                    ugElem.setAttribute("Name", uriGroupName);
                    rootElement.appendChild(ugElem);

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Adding the URIGroup " + uriGroupName);
                    }

                    // Check if URIList exists
                    if (uriList != null) {
                        for (URIData ud : uriList) {
                            ud.print(tc);

                            Element uriElem = output.createElement("Uri");
                            uriElem.setAttribute("Name", ud.uriName);
                            if (ud.cookieName != null && 0 < ud.cookieName.length()) {
                                uriElem.setAttribute("AffinityCookie",
                                                     ud.cookieName);
                            }
                            uriElem.setAttribute("AffinityURLIdentifier",
                                                 ud.urlCookieName);
                            ugElem.appendChild(uriElem);
                        }
                    }
                    cUgsSet.add(new ClusterUriGroup(lvh, clusterName, uriGroupName));
                }

            } // end-cluster-urigroups

            // ------------------------------------------
            // Create Routes
            for(DynamicVirtualHost vhost : virtualHostSet) {
                for(ClusterUriGroup cug : cUgsSet) {
                    if(vhost.getName().equals(cug.vhostName)) {
                        Element routeElem = output.createElement("Route");
                        routeElem.setAttribute("VirtualHostGroup", vhost.getName());
                        routeElem.setAttribute("UriGroup", cug.uriGroupName);
                        routeElem.setAttribute("ServerCluster", cug.clusterName);
                        rootElement.appendChild(routeElem);
                    }
                }
            }

            // The <RequestMetrics> and the sub elements <filters> are not processed yet
            // bunch of PMI stuff?

            // create the plugin config output file
            // Location of plugin-cfg.xml is the server.output.dir/logs/state for implicit requests, server.output.dir for direct mbean requests
            
            Boolean fileExists=false;
            if(writeDirectory == null) {
                String outputDirectory="";
                if (utilityRequest) {       
                    // If utilityRequest is true and there was no writeDirectory then write to the server.output.dir/logs/state/ directory
                    outputDirectory ="logs"+File.separatorChar+"state"+File.separatorChar;
                } 
                fileExists = locationService.getServerOutputResource(outputDirectory+pcd.PluginConfigFileName).exists();
                outFile = locationService.getServerOutputResource(outputDirectory+pcd.TempPluginConfigFileName);
            } else {        
                // Otherwise a writeDirectory was specified
                // Add a trailing slash if one is not present
                String path = writeDirectory.getPath();
                if(path.charAt(path.length()-1) != File.separatorChar) {
                    path += File.separatorChar;
                }
                File pluginFile = new File(path + pcd.PluginConfigFileName);
                fileExists = pluginFile.exists();
                File temPluginFile = new File(path + pcd.TempPluginConfigFileName);
                // ensure any existing temp file is deleted (should never exist in non failure situations)
                if (temPluginFile.exists())
                    temPluginFile.delete();
                outFile = locationService.asResource(temPluginFile, true);               
            } 
            
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Output file already exists : " + fileExists);
            }

            // Check to see if the config has changed
            writeFile = hasConfigChanged(output);

            // Only write out to file if we have new or changed configuration information, or if this is an explicit request
            if (writeFile || !utilityRequest || !fileExists) {
                fOutputStream = ((FileOutputStream)outFile.putStream());
                pluginCfgWriter = new BufferedWriter(new OutputStreamWriter(fOutputStream, "ISO-8859-1"));
    
                // Write the plugin config file
                // Create a style sheet to indent the output
                StreamSource xsltSource = new StreamSource(new StringReader(styleSheet));
        
                // Use transform apis to do generic serialization
                TransformerFactory tfactory = getTransformerFactory();
                Transformer serializer = tfactory.newTransformer(xsltSource);
                Properties oprops = new Properties();
                oprops.put(OutputKeys.METHOD, "xml");
                oprops.put(OutputKeys.OMIT_XML_DECLARATION, "no");
                oprops.put(OutputKeys.VERSION, "1.0");
                oprops.put(OutputKeys.INDENT, "yes");
                serializer.setOutputProperties(oprops);
                serializer.transform(new DOMSource(output), new StreamResult(pluginCfgWriter));
                
            }
            else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "A new plugin configuration file was not written: the configuration did not change.");
                }
            }
        } catch (Throwable t) {
            FFDCFilter.processException(t, PluginGenerator.class.getName(), "generateXML", new Object[] { container });
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Error creating plugin config xml; " + t.getMessage());
            }
        } finally {
            // flush and close
            if(pluginCfgWriter != null) {
                try {
                    pluginCfgWriter.flush();

                    // Ensure data is physically written to disk
                    fOutputStream.getFD().sync();

                    pluginCfgWriter.close();
                    pluginCfgWriter = null;
                    
                    // Verify that the temp plugin file exists
                    String tempFullFilePath = outFile.asFile().getAbsolutePath();
                    File tempFile = new File(tempFullFilePath);
                    if (!tempFile.exists()) {
                        throw new FileNotFoundException("File " + tempFile.getAbsolutePath() +  " could not be found");
                    }
                    // Construct the actual plugin file path 
                    String pluginDirPath = tempFullFilePath.substring(0, tempFullFilePath.indexOf(pcd.TempPluginConfigFileName));
                    File pluginFile = new File(pluginDirPath + pcd.PluginConfigFileName);
                    
                    if (pluginFile.exists()) {
                        FileUtils.forceDelete(pluginFile);    
                    }
                    
                    // Rename file from ".plugin-cfg.xml" to "plugin-cfg.xml"
                    FileUtils.moveFile(tempFile, pluginFile);
                    
                    // tell the user where the file is - quietly for implicit requests
                    String fullFilePath = pluginFile.getAbsolutePath();
                    if (utilityRequest)
                        Tr.info(tc, "plugin.file.generated.info",fullFilePath);
                    else
                        Tr.audit(tc, "plugin.file.generated.audit",fullFilePath);
                } catch (Throwable t) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(tc, "Error renaming the plugin config xml; " + t.getMessage());
                    }
                }
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "generateXML");
        }
    }
98711
private static void generateCCMPoolHTML(String poolName, List<TraceEvent> events,
                                           TraceEventStatus status, FileWriter fw)
      throws Exception
   {
      writeString(fw, "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"");
      writeEOL(fw);
      writeString(fw, "                      \"http://www.w3.org/TR/html4/loose.dtd\">");
      writeEOL(fw);

      writeString(fw, "<html>");
      writeEOL(fw);

      writeString(fw, "<head>");
      writeEOL(fw);

      writeString(fw, "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
      writeEOL(fw);

      writeString(fw, "<title>CCM: " + poolName + "</title>");
      writeEOL(fw);

      writeString(fw, "</head>");
      writeEOL(fw);

      writeString(fw, "<body style=\"background: #D7D7D7;\">");
      writeEOL(fw);

      writeString(fw, "<h1>CCM: " + poolName + "</h1>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Status:</b></td><td><div style=\"color: ");

      writeString(fw, status.getColor());
      writeString(fw, ";\">");

      writeString(fw, status.getDescription());
      
      writeString(fw, "</div></td>");
      writeEOL(fw);

      writeString(fw, "</tr>");
      writeEOL(fw);

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<table>");
      writeEOL(fw);

      writeString(fw, "<tr>");
      writeEOL(fw);

      writeString(fw, "<td><b>Timestamp</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Thread</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>ManagedConnectionPool</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Event</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>ConnectionListener</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Connection</b></td>");
      writeEOL(fw);

      writeString(fw, "<td><b>Key</b></td>");
      writeEOL(fw);

      writeString(fw, "</tr>");
      writeEOL(fw);

      for (TraceEvent te : events)
      {
         writeString(fw, "<tr>");
         writeEOL(fw);

         writeString(fw, "<td>" + te.getTimestamp() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getThreadId() + "</td>");
         writeEOL(fw);
      
         if (!"NONE".equals(te.getManagedConnectionPool()))
         {
            writeString(fw, "<td>" + te.getManagedConnectionPool() + "</td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         writeString(fw, "<td>" + TraceEvent.asText(te) + "</td>");
         writeEOL(fw);
      
         if (!"NONE".equals(te.getConnectionListener()))
         {
            writeString(fw, "<td><a href=\"" + te.getConnectionListener() + "/index.html\">" +
                        te.getConnectionListener() + "</a></td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         if (!"NONE".equals(te.getPayload1()))
         {
            writeString(fw, "<td>" + te.getPayload1() + "</td>");
         }
         else
         {
            writeString(fw, "<td></td>");
         }
         writeEOL(fw);
      
         writeString(fw, "<td>" + te.getPayload2() + "</td>");
         writeEOL(fw);
      
         writeString(fw, "</tr>");
         writeEOL(fw);
      }

      writeString(fw, "</table>");
      writeEOL(fw);

      writeString(fw, "<h2>Pool</h2>");
      writeEOL(fw);

      writeString(fw, "<a href=\"index.html\">Report</a>");
      writeEOL(fw);

      writeString(fw, "<h2>Lifecycle</h2>");
      writeEOL(fw);

      writeString(fw, "<a href=\"lifecycle.html\">Report</a>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<h2>Data</h2>");
      writeEOL(fw);

      writeString(fw, "<pre>");
      writeEOL(fw);

      for (TraceEvent te : events)
      {
         writeString(fw, TraceEventHelper.prettyPrint(te));
         writeEOL(fw);
      }

      writeString(fw, "</pre>");
      writeEOL(fw);

      writeString(fw, "<p>");
      writeEOL(fw);

      writeString(fw, "<a href=\"../index.html\">Back</a>");
      writeEOL(fw);

      writeString(fw, "</body>");
      writeEOL(fw);

      writeString(fw, "</html>");
      writeEOL(fw);
   }
893835
public int doEndTag() throws JspException
    {
        ServletRequest req = pageContext.getRequest();
        String scriptId = null;

        // report errors that may have occurred
        if (hasErrors())
            return reportAndExit(EVAL_PAGE);

        // Generate the name definition or image element
        String uri = null;
        if (_state.src != null) {
            try {
                uri = PageFlowTagUtils.rewriteResourceURL(pageContext, _state.src, _params, _location);
            }
            catch (URISyntaxException e) {
                // report the error...
                String s = Bundle.getString("Tags_Image_URLException",
                        new Object[]{_state.src, e.getMessage()});
                registerTagError(s, e);
            }
        }

        if (uri != null) {
            _state.src = ((HttpServletResponse) pageContext.getResponse()).encodeURL(uri);
        }

        // we assume that tagId will over have override id if both
        // are defined.
        if (_state.id != null) {
            scriptId = renderNameAndId((HttpServletRequest) req, _state, null);
        }

        WriteRenderAppender writer = new WriteRenderAppender(pageContext);
        TagRenderingBase br = TagRenderingBase.Factory.getRendering(TagRenderingBase.IMAGE_TAG, req);
        br.doStartTag(writer, _state);
        br.doEndTag(writer);


        if (scriptId != null)
            write(scriptId);

        // Evaluate the remainder of this page
        localRelease();
        return EVAL_PAGE;
    }
1223222
public String getDiffHtml() throws Exception {

        CmsDiffViewMode mode = "all".equals(m_diffMode) ? CmsDiffViewMode.ALL : CmsDiffViewMode.DIFF_ONLY;
        String text1 = m_text1;
        String text2 = m_text2;
        if ("text".equals(m_textMode)) {
            text1 = CmsHtml2TextConverter.html2text(text1, "UTF-8");
            text2 = CmsHtml2TextConverter.html2text(text2, "UTF-8");
        }
        CmsHtmlDifferenceConfiguration conf = new CmsHtmlDifferenceConfiguration(
            mode == CmsDiffViewMode.ALL ? -1 : 2,
            A_CmsUI.get().getLocale());
        String diff = Diff.diffAsHtml(text1, text2, conf);
        String html = null;
        if (CmsStringUtil.isNotEmpty(diff)) {
            html = diff;
        } else {
            html = wrapLinesWithUnchangedStyle(
                CmsStringUtil.substitute(CmsStringUtil.escapeHtml(m_text1), "<br/>", ""));
        }
        return html;

    }
602273
public void displayDialog() throws Exception {

        initAdminTool();

        JspWriter out = getJsp().getJspContext().getOut();
        out.print(htmlStart());
        out.print(bodyStart(null));
        out.print("<form name='editor' method='post' target='_top' action='");
        out.print(getJsp().link("/system/workplace/editors/editor.jsp"));
        out.print("'>\n");
        out.print(paramsAsHidden());
        out.print("</form>\n");
        out.print("<script type='text/javascript'>\n");
        out.print("document.forms['editor'].submit();\n");
        out.print("</script>\n");
        out.print(bodyEnd());
        out.print(htmlEnd());
    }
1060610
public function Generate()
	{
		// check for all required fields
		if ( empty($_REQUEST["table_name"]) )
		{
			throw new Exception("Please select at least one table to generate");
		}

		$cstring = $this->GetConnectionString();

		// initialize the database connection
		$handler = new DBEventHandler();
		$connection = new DBConnection($cstring, $handler);
		$server = new DBServer($connection);
		$dbSchema = new DBSchema($server);

		$debug = isset($_REQUEST["debug"]) && $_REQUEST["debug"] == "1";
		$parameters = array();
		$tableNames = $_REQUEST["table_name"];
		$packageName = $_REQUEST["package"];
		$debug_output = "";
		
		$selectedTables = array();
		foreach ($tableNames as $tableName)
		{
			$selectedTables[] = $dbSchema->Tables[$tableName];
		}
		
		// see if arbitrary parameters were passed in - in which case they will be passed through to the templates
		$tmp = RequestUtil::Get('parameters');
		if ($tmp)
		{
			$pairs = explode("\n", str_replace("\r","", $tmp) );
			foreach ($pairs as $pair)
			{
				list($key,$val) = explode("=",$pair,2);
				$parameters[$key] = $val;
			}
		}
		
		// check for required parameters
		if (!array_key_exists('max_items_in_topnav', $parameters)) $parameters['max_items_in_topnav'] = self::$DEFAULT_MAX_ITEMS_IN_TOPNAV;

		$zipFile = new zipfile();

		$codeRoot = GlobalConfig::$APP_ROOT . '/code/';
		$tempRoot = GlobalConfig::$APP_ROOT . '/temp/';

		// initialize smarty
		$smarty = new Smarty();
		$smarty->template_dir = $codeRoot;
		$smarty->compile_dir = $tempRoot;
		$smarty->config_dir = $tempRoot;
		$smarty->cache_dir = $tempRoot;
		$smarty->caching = false;

		$appname = RequestUtil::Get("appname");
		$appRoot = RequestUtil::Get("appRoot");
		$includePath = RequestUtil::Get("includePath");
		$includePhar = RequestUtil::Get("includePhar");
		$enableLongPolling = RequestUtil::Get("enableLongPolling");

		$config = new AppConfig($codeRoot  . $packageName);
		
		foreach ($config->GetTemplateFiles() as $templateFile)
		{
			if ($templateFile->generate_mode == 3)
			{
				if ($includePhar == '1')
				{
					// proceed, copy the phar file
					$templateFile->generate_mode = 2;
				}
				else
				{
					// skip the phar file
					continue;
				}
			}
			
			if ($templateFile->generate_mode == 2)
			{
				// this is a template that is copied without parsing to the project (ie images, static files, etc)
				$templateFilename = str_replace(
						array('{$appname}','{$appname|lower}','{$appname|upper}'),
						array($appname,strtolower($appname),strtoupper($appname)),
						$templateFile->destination
				);

				$contents = file_get_contents($codeRoot . $templateFile->source);

				// this is a direct copy
				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. "(contents of " . $codeRoot . $templateFile->source . ")\r\n";
				}
				else
				{
					$zipFile->addFile( $contents , $templateFilename);
				}
			}
			elseif ($templateFile->generate_mode == 1)
			{
				// single template where one is generated for the entire project instead of one for each selected table
				$templateFilename = str_replace(
						array('{$appRoot}','{$appRoot|lower}','{$appRoot|upper}'),
						array($appRoot,strtolower($appRoot),strtoupper($appRoot)),
						$templateFile->destination
				);

				$smarty->clearAllAssign();

				foreach ($parameters as $key => $val)
				{
					$smarty->assign($key,$val);
				}

				$smarty->assign("tableNames",$tableNames);
				$smarty->assign("templateFilename",$templateFilename);
				$smarty->assign("schema",$dbSchema);
				$smarty->assign("tables",$dbSchema->Tables);
				$smarty->assign("connection",$cstring);
				$smarty->assign("appname",$appname);
				$smarty->assign("appRoot",$appRoot);
				$smarty->assign("includePath",$includePath);
				$smarty->assign("includePhar",$includePhar);
				$smarty->assign("enableLongPolling",$enableLongPolling);
				$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

				$tableInfos = Array();
				
				// add all tables to a tableInfos array that can be used for cross-referencing by table name
						foreach ($dbSchema->Tables as $table)
				{
					if ($table->GetPrimaryKeyName())
					{
						$tableName = $table->Name;
						$tableInfos[$tableName] = Array();
						$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
						$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
						$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
						$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
						$tableInfos[$tableName]['templateFilename'] = $templateFilename;
					}
				}
				
				$smarty->assign("tableInfos",$tableInfos);
				$smarty->assign("selectedTables",$selectedTables);

				if ($debug)
				{
					$debug_output .= "\r\n###############################################################\r\n"
					. "# $templateFilename\r\n###############################################################\r\n"
					. $smarty->fetch($templateFile->source) . "\r\n";
				}
				else
				{
					// we don't like bare linefeed characters
					$content = $body = preg_replace("/^(?=\n)|[^\r](?=\n)/", "\\0\r", $smarty->fetch($templateFile->source));

					$zipFile->addFile( $content , $templateFilename);
				}
			}
			else
			{
				// enumerate all selected tables and merge them with the selected template
				// append each to the zip file for output
				foreach ($tableNames as $tableName)
				{
					$singular = $_REQUEST[$tableName."_singular"];
					$plural = $_REQUEST[$tableName."_plural"];
					$prefix = $_REQUEST[$tableName."_prefix"];

					$templateFilename = str_replace(
							array('{$singular}','{$plural}','{$table}','{$appname}','{$singular|lower}','{$plural|lower}','{$table|lower}','{$appname|lower}','{$singular|upper}','{$plural|upper}','{$table|upper}','{$appname|upper}'),
							array($singular,$plural,$tableName,$appname,strtolower($singular),strtolower($plural),strtolower($tableName),strtolower($appname),strtoupper($singular),strtoupper($plural),strtoupper($tableName),strtoupper($appname)),
							$templateFile->destination);

					$smarty->clearAllAssign();
					$smarty->assign("appname",$appname);
					$smarty->assign("singular",$singular);
					$smarty->assign("plural",$plural);
					$smarty->assign("prefix",$prefix);
					$smarty->assign("templateFilename",$templateFilename);
					$smarty->assign("table",$dbSchema->Tables[$tableName]);
					$smarty->assign("connection",$cstring);
					$smarty->assign("appRoot",$appRoot);
					$smarty->assign("includePath",$includePath);
					$smarty->assign("includePhar",$includePhar);
					$smarty->assign("enableLongPolling",$enableLongPolling);
					$smarty->assign("PHREEZE_VERSION",Phreezer::$Version);

					$tableInfos = Array();
					
					// add all tables to a tableInfos array that can be used for cross-referencing by table name
					foreach ($dbSchema->Tables as $table)
					{
						if ($table->GetPrimaryKeyName())
						{
							$tableName = $table->Name;
							$tableInfos[$tableName] = Array();
							$tableInfos[$tableName]['table'] = $dbSchema->Tables[$tableName];
							$tableInfos[$tableName]['singular'] = $_REQUEST[$tableName."_singular"];
							$tableInfos[$tableName]['plural'] = $_REQUEST[$tableName."_plural"];
							$tableInfos[$tableName]['prefix'] = $_REQUEST[$tableName."_prefix"];
							$tableInfos[$tableName]['templateFilename'] = $templateFilename;
						}
					}
					
					$smarty->assign("tableInfos",$tableInfos);
					$smarty->assign("selectedTables",$selectedTables);
					
					foreach ($parameters as $key => $val)
					{
						$smarty->assign($key,$val);
					}

					//print "<pre>"; print_r($dbSchema->Tables[$tableName]->PrimaryKeyIsAutoIncrement()); die();
					if ($debug)
					{
						$debug_output .= "\r\n###############################################################\r\n"
						. "# $templateFilename\r\n###############################################################\r\n"
						. $smarty->fetch($templateFile->source) . "\r\n";
					}
					else
					{
						$zipFile->addFile( $smarty->fetch($templateFile->source) , $templateFilename);
					}

				}
			}

		}

		if ($debug)
		{
			header("Content-type: text/plain");
			print $debug_output;
		}
		else
		{
			// now output the zip as binary data to the browser
			header("Content-type: application/force-download");

			// laplix 2007-11-02.
			// Use the application name provided by the user in show_tables.
			//header("Content-disposition: attachment; filename=".str_replace(" ","_",$G_CONNSTR->DBName).".zip");
			header("Content-disposition: attachment; filename=".str_replace(" ","_",strtolower(str_replace("/","", $appRoot))).".zip");

			header("Content-Transfer-Encoding: Binary");
			header('Content-Type: application/zip');
			print $zipFile->file();
		}
	}
1090048
private static void generateParseOnXml(BindTypeContext context, BindEntity entity) {
		// @formatter:off
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("parseOnXml").addJavadoc("parse xml\n")
				.addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
				// .addParameter(typeName(KriptonXmlContext.class), "context")
				.addParameter(typeName(XMLParser.class), "xmlParser")
				.addParameter(typeName(Integer.TYPE), "currentEventType").returns(typeName(entity.getElement()))
				.addException(Exception.class);
		// @formatter:on

		boolean mutableObject = entity.isMutablePojo();

		if (mutableObject) {
			methodBuilder.addStatement("$T instance = new $T()", entity.getElement(), entity.getElement());
		} else {
			ImmutableUtility.generateImmutableVariableInit(entity, methodBuilder);
		}

		methodBuilder.addStatement("int eventType = currentEventType");
		methodBuilder.addStatement("boolean read=true");

		methodBuilder.addCode("\n");
		methodBuilder.beginControlFlow("if (currentEventType == 0)");
		methodBuilder.addStatement("eventType = xmlParser.next()");
		methodBuilder.nextControlFlow("else");
		methodBuilder.addStatement("eventType = xmlParser.getEventType()");
		methodBuilder.endControlFlow();
		methodBuilder.addStatement("String currentTag = xmlParser.getName().toString()");

		methodBuilder.addStatement("String elementName = currentTag");

		generateParseOnXmlAttributes(context, methodBuilder, entity);

		methodBuilder.addCode("\n");
		methodBuilder.addCode("//sub-elements\n");
		methodBuilder.beginControlFlow("while (xmlParser.hasNext() && elementName!=null)");

		methodBuilder.beginControlFlow("if (read)");
		methodBuilder.addStatement("eventType = xmlParser.next()");
		methodBuilder.nextControlFlow("else");
		methodBuilder.addStatement("eventType = xmlParser.getEventType()");
		methodBuilder.endControlFlow();
		methodBuilder.addStatement("read=true");

		methodBuilder.beginControlFlow("switch(eventType)$>");
		methodBuilder.addCode("case $T.START_TAG:\n$>", XmlPullParser.class);
		generateParserOnXmlStartElement(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("case $T.END_TAG:\n$>", XmlPullParser.class);
		generateParserOnXmlEndElement(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("case $T.CDSECT:\n", XmlPullParser.class);
		methodBuilder.addCode("case $T.TEXT:\n$>", XmlPullParser.class);
		generateParserOnXmlCharacters(context, methodBuilder, "instance", "xmlParser", entity);
		methodBuilder.addStatement("$<break");

		methodBuilder.addCode("default:\n$>");
		methodBuilder.addStatement("$<break");
		methodBuilder.addCode("$<");
		methodBuilder.endControlFlow();
		// @formatter:on

		methodBuilder.endControlFlow();

		if (!mutableObject) {
			ImmutableUtility.generateImmutableEntityCreation(entity, methodBuilder, "instance", true);
		}

		methodBuilder.addStatement("return instance");

		context.builder.addMethod(methodBuilder.build());
	}
1094844
@Override
    public void writeXML(XMLOutput xmlOutput) throws IOException {
        xmlOutput.openCloseTag(
                ELEMENT_NAME,
                new XMLAttributeList().addAttribute("sequence", String.valueOf(sequence))
                .addAttribute("timestamp", String.valueOf(timestamp)).addAttribute("release", releaseName)
                .addAttribute("codeSize", String.valueOf(codeSize))
                .addAttribute("numClasses", String.valueOf(numClasses)));
    }