Source Code Cross Referenced for CompletionServlet.java in  » Science » Cougaar12_4 » org » cougaar » planning » servlet » 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 » Science » Cougaar12_4 » org.cougaar.planning.servlet 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         *
0003:         * <copyright>
0004:         *  
0005:         *  Copyright 1997-2004 BBNT Solutions, LLC
0006:         *  under sponsorship of the Defense Advanced Research Projects
0007:         *  Agency (DARPA).
0008:         * 
0009:         *  You can redistribute this software and/or modify it under the
0010:         *  terms of the Cougaar Open Source License as published on the
0011:         *  Cougaar Open Source Website (www.cougaar.org).
0012:         * 
0013:         *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0014:         *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0015:         *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0016:         *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0017:         *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0018:         *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0019:         *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0020:         *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0021:         *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0022:         *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0023:         *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0024:         *  
0025:         * </copyright>
0026:         */
0027:
0028:        package org.cougaar.planning.servlet;
0029:
0030:        import java.io.IOException;
0031:        import java.io.ObjectOutputStream;
0032:        import java.io.OutputStream;
0033:        import java.io.OutputStreamWriter;
0034:        import java.io.PrintWriter;
0035:        import java.net.URLEncoder;
0036:        import java.util.ArrayList;
0037:        import java.util.Arrays;
0038:        import java.util.Collection;
0039:        import java.util.Collections;
0040:        import java.util.Date;
0041:        import java.util.Iterator;
0042:        import java.util.List;
0043:        import java.util.Set;
0044:        import java.util.SortedSet;
0045:        import java.util.TreeSet;
0046:
0047:        import javax.servlet.Servlet;
0048:        import javax.servlet.ServletException;
0049:        import javax.servlet.http.HttpServlet;
0050:        import javax.servlet.http.HttpServletRequest;
0051:        import javax.servlet.http.HttpServletResponse;
0052:
0053:        import org.cougaar.core.mts.MessageAddress;
0054:        import org.cougaar.core.service.AgentIdentificationService;
0055:        import org.cougaar.core.service.BlackboardQueryService;
0056:        import org.cougaar.core.service.LoggingService;
0057:        import org.cougaar.core.service.wp.WhitePagesService;
0058:        import org.cougaar.core.servlet.BaseServletComponent;
0059:        import org.cougaar.core.util.UID;
0060:        import org.cougaar.core.wp.ListAllAgents;
0061:
0062:        import org.cougaar.planning.ldm.plan.Task;
0063:        import org.cougaar.planning.ldm.plan.Verb;
0064:        import org.cougaar.planning.ldm.plan.Workflow;
0065:        import org.cougaar.planning.ldm.plan.AllocationResult;
0066:        import org.cougaar.planning.ldm.plan.PlanElement;
0067:        import org.cougaar.planning.ldm.plan.AssetTransfer;
0068:        import org.cougaar.planning.ldm.plan.Disposition;
0069:        import org.cougaar.planning.ldm.plan.Aggregation;
0070:        import org.cougaar.planning.ldm.plan.Expansion;
0071:        import org.cougaar.planning.ldm.plan.Allocation;
0072:        import org.cougaar.planning.plugin.completion.CompletionCalculator;
0073:        import org.cougaar.planning.servlet.data.completion.AbstractTask;
0074:        import org.cougaar.planning.servlet.data.completion.CompletionData;
0075:        import org.cougaar.planning.servlet.data.completion.FailedTask;
0076:        import org.cougaar.planning.servlet.data.completion.FullCompletionData;
0077:        import org.cougaar.planning.servlet.data.completion.SimpleCompletionData;
0078:        import org.cougaar.planning.servlet.data.completion.UnconfidentTask;
0079:        import org.cougaar.planning.servlet.data.completion.UnestimatedTask;
0080:        import org.cougaar.planning.servlet.data.completion.UnplannedTask;
0081:        import org.cougaar.planning.servlet.data.xml.XMLWriter;
0082:
0083:        import org.cougaar.util.UnaryPredicate;
0084:        import org.cougaar.util.Filters;
0085:
0086:        /**
0087:         * A <code>Servlet</code>, loaded by the 
0088:         * <code>SimpleServletComponent</code>, that generates 
0089:         * HTML, XML, and serialized-Object views of Task completion
0090:         * information.
0091:         */
0092:        public class CompletionServlet extends BaseServletComponent {
0093:            protected static final UnaryPredicate TASK_PRED = new TaskPredicate();
0094:
0095:            private static final class TaskPredicate implements  UnaryPredicate {
0096:                public boolean execute(Object o) {
0097:                    return (o instanceof  Task);
0098:                }
0099:            }
0100:
0101:            protected static class RootTaskPredicate implements  UnaryPredicate {
0102:                private Verb rootVerb;
0103:                private Verb parentVerb;
0104:
0105:                public RootTaskPredicate(Verb rootVerb, Verb parentVerb) {
0106:                    this .rootVerb = rootVerb;
0107:                    this .parentVerb = parentVerb;
0108:                }
0109:
0110:                public boolean execute(Object o) {
0111:                    if (o instanceof  Task) {
0112:                        Task t = (Task) o;
0113:                        Verb verb = null;
0114:                        Workflow wf = null;
0115:                        Task parentTask = null;
0116:                        if (t != null && (verb = t.getVerb()) != null
0117:                                && verb.equals(rootVerb)) {
0118:                            if ((wf = t.getWorkflow()) != null
0119:                                    && (parentTask = wf.getParentTask()) != null) {
0120:                                return parentTask.getVerb().equals(parentVerb);
0121:                            }
0122:                        }
0123:                    }
0124:                    return false;
0125:                }
0126:
0127:                public String toString() {
0128:                    return getClass().getName() + "[verb=" + rootVerb + "]";
0129:                }
0130:            }
0131:
0132:            protected static final String[] iframeBrowsers = { "mozilla/5",
0133:                    "msie 5", "msie 6" };
0134:
0135:            protected static final double DEFAULT_RED_THRESHOLD = 0.89;
0136:
0137:            protected static final double DEFAULT_YELLOW_THRESHOLD = 0.99;
0138:
0139:            protected static final int MAX_AGENT_FRAMES = 18;
0140:
0141:            protected String path;
0142:
0143:            protected MessageAddress localAgent;
0144:
0145:            protected String encLocalAgent;
0146:
0147:            protected AgentIdentificationService agentIdService;
0148:            protected BlackboardQueryService blackboardQueryService;
0149:            protected WhitePagesService whitePagesService;
0150:
0151:            protected CompletionCalculator calc;
0152:            protected final Object lock = new Object();
0153:            protected LoggingService logger;
0154:
0155:            protected static UnaryPredicate projectSupplyRootTaskPred = new RootTaskPredicate(
0156:                    Verb.get("ProjectSupply"), Verb.get("GenerateProjections"));
0157:            protected static UnaryPredicate supplyRootTaskPred = new RootTaskPredicate(
0158:                    Verb.get("Supply"), Verb.get("GenerateProjections"));
0159:            protected static UnaryPredicate transportRootTaskPred = new RootTaskPredicate(
0160:                    Verb.get("Transport"), Verb.get("DetermineRequirements"));
0161:
0162:            public CompletionServlet() {
0163:                super ();
0164:                path = getDefaultPath();
0165:            }
0166:
0167:            public void setParameter(Object o) {
0168:                if (o instanceof  String) {
0169:                    path = (String) o;
0170:                } else if (o instanceof  Collection) {
0171:                    Collection c = (Collection) o;
0172:                    if (!(c.isEmpty())) {
0173:                        path = (String) c.iterator().next();
0174:                    }
0175:                } else if (o == null) {
0176:                    // ignore
0177:                } else {
0178:                    throw new IllegalArgumentException("Invalid parameter: "
0179:                            + o);
0180:                }
0181:            }
0182:
0183:            protected String getDefaultPath() {
0184:                return "/completion";
0185:            }
0186:
0187:            protected String getPath() {
0188:                return path;
0189:            }
0190:
0191:            protected Servlet createServlet() {
0192:                return new CompletorServlet();
0193:            }
0194:
0195:            public void setAgentIdentificationService(
0196:                    AgentIdentificationService agentIdService) {
0197:                this .agentIdService = agentIdService;
0198:                if (agentIdService == null) {
0199:                    // Revocation
0200:                } else {
0201:                    this .localAgent = agentIdService.getMessageAddress();
0202:                    encLocalAgent = formURLEncode(localAgent.getAddress());
0203:                }
0204:            }
0205:
0206:            public void setBlackboardQueryService(
0207:                    BlackboardQueryService blackboardQueryService) {
0208:                this .blackboardQueryService = blackboardQueryService;
0209:            }
0210:
0211:            public void setWhitePagesService(WhitePagesService whitePagesService) {
0212:                this .whitePagesService = whitePagesService;
0213:            }
0214:
0215:            public void load() {
0216:                super .load();
0217:                logger = (LoggingService) serviceBroker.getService(this ,
0218:                        LoggingService.class, null);
0219:            }
0220:
0221:            public void unload() {
0222:                super .unload();
0223:                if (whitePagesService != null) {
0224:                    serviceBroker.releaseService(this , WhitePagesService.class,
0225:                            whitePagesService);
0226:                    whitePagesService = null;
0227:                }
0228:                if (blackboardQueryService != null) {
0229:                    serviceBroker.releaseService(this ,
0230:                            BlackboardQueryService.class,
0231:                            blackboardQueryService);
0232:                    blackboardQueryService = null;
0233:                }
0234:                if (agentIdService != null) {
0235:                    serviceBroker.releaseService(this ,
0236:                            AgentIdentificationService.class, agentIdService);
0237:                    agentIdService = null;
0238:                }
0239:            }
0240:
0241:            protected List getAllEncodedAgentNames() {
0242:                try {
0243:                    // do full WP list (deprecated!)
0244:                    Set s = ListAllAgents.listAllAgents(whitePagesService);
0245:                    // URLEncode the names and sort
0246:                    List l = ListAllAgents.encodeAndSort(s);
0247:                    return l;
0248:                } catch (Exception e) {
0249:                    throw new RuntimeException("List all agents failed", e);
0250:                }
0251:            }
0252:
0253:            protected List getAllAgentNames() {
0254:                try {
0255:                    // do full WP list (deprecated!)
0256:                    List result = new ArrayList(ListAllAgents
0257:                            .listAllAgents(whitePagesService));
0258:                    Collections.sort(result);
0259:                    return result;
0260:                } catch (Exception e) {
0261:                    throw new RuntimeException("List all agents failed", e);
0262:                }
0263:            }
0264:
0265:            protected Collection queryBlackboard(UnaryPredicate pred) {
0266:                return blackboardQueryService.query(pred);
0267:            }
0268:
0269:            protected String getEncodedAgentName() {
0270:                return encLocalAgent;
0271:            }
0272:
0273:            protected String formURLEncode(String name) {
0274:                try {
0275:                    return URLEncoder.encode(name, "UTF-8");
0276:                } catch (java.io.UnsupportedEncodingException e) {
0277:                    // should never happen
0278:                    throw new RuntimeException("Unable to encode to UTF-8?");
0279:                }
0280:            }
0281:
0282:            protected CompletionCalculator getCalculator() {
0283:                synchronized (lock) {
0284:                    if (calc == null) {
0285:                        calc = new CompletionCalculator();
0286:                    }
0287:                    return calc;
0288:                }
0289:            }
0290:
0291:            protected String getTitlePrefix() {
0292:                return ""; // must not contain special URL characters
0293:            }
0294:
0295:            /**
0296:             * Inner-class that's registered as the servlet.
0297:             */
0298:            protected class CompletorServlet extends HttpServlet {
0299:                public void doGet(HttpServletRequest request,
0300:                        HttpServletResponse response) throws IOException,
0301:                        ServletException {
0302:                    (new Completor(request, response)).execute();
0303:                }
0304:
0305:                public void doPost(HttpServletRequest request,
0306:                        HttpServletResponse response) throws IOException,
0307:                        ServletException {
0308:                    (new Completor(request, response)).execute();
0309:                }
0310:            }
0311:
0312:            /** 
0313:             * Inner-class to hold state and generate the response.
0314:             */
0315:            protected class Completor {
0316:
0317:                public static final int FORMAT_DATA = 0;
0318:                public static final int FORMAT_XML = 1;
0319:                public static final int FORMAT_HTML = 2;
0320:
0321:                private int format;
0322:                private boolean showTables;
0323:
0324:                private HttpServletRequest request;
0325:                private HttpServletResponse response;
0326:
0327:                // writer from the request for HTML output
0328:                private PrintWriter out;
0329:
0330:                // various form params
0331:                double redThreshold;
0332:                double yellowThreshold;
0333:                int refreshInterval;
0334:
0335:                public Completor(HttpServletRequest request,
0336:                        HttpServletResponse response) {
0337:                    this .request = request;
0338:                    this .response = response;
0339:                }
0340:
0341:                public void execute() throws IOException, ServletException {
0342:                    try {
0343:                        redThreshold = Double.parseDouble(request
0344:                                .getParameter("redThreshold"));
0345:                    } catch (Exception e) {
0346:                        redThreshold = DEFAULT_RED_THRESHOLD;
0347:                    }
0348:                    try {
0349:                        yellowThreshold = Double.parseDouble(request
0350:                                .getParameter("yellowThreshold"));
0351:                    } catch (Exception e) {
0352:                        yellowThreshold = DEFAULT_YELLOW_THRESHOLD;
0353:                    }
0354:                    try {
0355:                        refreshInterval = Integer.parseInt(request
0356:                                .getParameter("refreshInterval"));
0357:                    } catch (Exception e) {
0358:                        refreshInterval = 0;
0359:                    }
0360:                    String formatParam = request.getParameter("format");
0361:                    if (formatParam == null) {
0362:                        format = FORMAT_HTML; // default
0363:                    } else if ("data".equals(formatParam)) {
0364:                        format = FORMAT_DATA;
0365:                    } else if ("xml".equals(formatParam)) {
0366:                        format = FORMAT_XML;
0367:                    } else if ("html".equals(formatParam)) {
0368:                        format = FORMAT_HTML;
0369:                    } else {
0370:                        format = FORMAT_HTML; // other
0371:                    }
0372:
0373:                    String showTablesParam = request.getParameter("showTables");
0374:                    if (showTablesParam == null) {
0375:                        showTables = false; // default
0376:                    } else if ("true".equals(showTablesParam)) {
0377:                        showTables = true;
0378:                    } else {
0379:                        showTables = false; // other
0380:                    }
0381:
0382:                    String viewType = request.getParameter("viewType");
0383:                    if (viewType == null) {
0384:                        viewDefault(); // default
0385:                    } else if ("viewAgentSubmit".equals(viewType)) {
0386:                        viewAgentSubmit();
0387:                    } else if ("viewAgentBig".equals(viewType)) {
0388:                        viewAgentBig();
0389:                    } else if ("viewAllAgents".equals(viewType)) {
0390:                        viewAllAgents();
0391:                    } else if ("viewSelectedAgents".equals(viewType)) {
0392:                        viewSelectedAgents();
0393:                    } else if ("viewManyAgents".equals(viewType)) {
0394:                        viewManyAgents();
0395:                    } else if ("viewTitle".equals(viewType)) {
0396:                        viewTitle();
0397:                    } else if ("viewAgentSmall".equals(viewType)) {
0398:                        viewAgentSmall();
0399:                    } else if ("viewMoreLink".equals(viewType)) {
0400:                        viewMoreLink();
0401:                    } else {
0402:                        viewDefault(); // other
0403:                    }
0404:
0405:                    // done
0406:                }
0407:
0408:                private void viewDefault() throws IOException {
0409:                    if (format == FORMAT_HTML) {
0410:                        // generate outer frame page:
0411:                        //   top:    select "/agent"
0412:                        //   middle: "viewAgentSubmit" buttons
0413:                        //   bottom: "viewAgentBig" frame
0414:                        //
0415:                        // Note that the top and middle frames must be on 
0416:                        // the same host, due to javascript security.  Only
0417:                        // the bottom frame is updated by the submit button.
0418:                        response.setContentType("text/html");
0419:                        this .out = response.getWriter();
0420:                        out
0421:                                .print("<html><head><title>"
0422:                                        + getTitlePrefix()
0423:                                        + "Completion Viewer</title></head>"
0424:                                        + "<frameset rows=\"10%,12%,78%\">\n"
0425:                                        + "<frame src=\""
0426:                                        + "/agents?format=select&suffix="
0427:                                        + getEncodedAgentName()
0428:                                        + "\" name=\"agentFrame\">\n"
0429:                                        + "<frame src=\"/$"
0430:                                        + getEncodedAgentName()
0431:                                        + getPath()
0432:                                        + "?viewType=viewAgentSubmit\" name=\"viewAgentSubmit\">\n"
0433:                                        + "<frame src=\"/$"
0434:                                        + getEncodedAgentName()
0435:                                        + getPath()
0436:                                        + "?viewType=viewAgentBig\" name=\"viewAgentBig\">\n"
0437:                                        + "</frameset>\n"
0438:                                        + "<noframes>Please enable frame support</noframes>"
0439:                                        + "</html>\n");
0440:                        out.flush();
0441:                    } else {
0442:                        // for other formats, just get the data
0443:                        viewAgentBig();
0444:                    }
0445:                }
0446:
0447:                protected void viewAgentSubmit() throws IOException {
0448:                    response.setContentType("text/html");
0449:                    this .out = response.getWriter();
0450:                    // javascript based on PlanViewServlet
0451:                    out
0452:                            .print("<html>\n"
0453:                                    + "<script language=\"JavaScript\">\n"
0454:                                    + "<!--\n"
0455:                                    + "function mySubmit() {\n"
0456:                                    + "  var obj = top.agentFrame.document.agent.name;\n"
0457:                                    + "  var encAgent = obj.value;\n"
0458:                                    + "  if (encAgent.charAt(0) == '.') {\n"
0459:                                    + "    alert(\"Please select an agent name\")\n"
0460:                                    + "    return false;\n"
0461:                                    + "  }\n"
0462:                                    + "  document.myForm.target=\"viewAgentBig\"\n"
0463:                                    + "  document.myForm.action=\"/$\"+encAgent+\""
0464:                                    + getPath()
0465:                                    + "\"\n"
0466:                                    + "  return true\n"
0467:                                    + "}\n"
0468:                                    + "// -->\n"
0469:                                    + "</script>\n"
0470:                                    + "<head>\n"
0471:                                    + "<title>"
0472:                                    + getTitlePrefix()
0473:                                    + "Completion"
0474:                                    + "</title>"
0475:                                    + "</head>\n"
0476:                                    + "<body>"
0477:                                    + "<form name=\"myForm\" method=\"get\" "
0478:                                    + "onSubmit=\"return mySubmit()\">\n"
0479:                                    + getTitlePrefix()
0480:                                    + "Select an agent above, "
0481:                                    + "<input type=\"hidden\""
0482:                                    + " name=\"viewType\""
0483:                                    + " value=\"viewAgentBig\" "
0484:                                    + "<input type=\"checkbox\""
0485:                                    + " name=\"showTables\""
0486:                                    + " value=\"true\" ");
0487:                    if (showTables) {
0488:                        out.print("checked");
0489:                    }
0490:                    out
0491:                            .println("> show table, \n"
0492:                                    + "<input type=\"submit\""
0493:                                    + " name=\"formSubmit\""
0494:                                    + " value=\"Submit\"><br>");
0495:                    out.println("<a href=\"/$" + getEncodedAgentName()
0496:                            + getPath() + "?viewType=viewAllAgents"
0497:                            + "\" target=\"_top\">Show all agents.</a>");
0498:                    out
0499:                            .println("<a href=\"/$"
0500:                                    + getEncodedAgentName()
0501:                                    + getPath()
0502:                                    + "?viewType=viewManyAgents"
0503:                                    + "\" target=\"_top\"> Show several selected agents.</a>");
0504:                    out.println("</form>");
0505:                    out.print("</body></html>");
0506:                    out.flush();
0507:                }
0508:
0509:                private void viewAgentBig() {
0510:                    // get result
0511:                    CompletionData result = getCompletionData();
0512:
0513:                    // write data
0514:                    try {
0515:                        if (format == FORMAT_HTML) {
0516:                            // html      
0517:                            response.setContentType("text/html");
0518:                            this .out = response.getWriter();
0519:                            printCompletionDataAsHTML(result);
0520:                        } else {
0521:                            // unsupported
0522:                            if (format == FORMAT_DATA) {
0523:                                // serialize
0524:                                //response.setContentType("application/binary");
0525:                                OutputStream out = response.getOutputStream();
0526:                                ObjectOutputStream oos = new ObjectOutputStream(
0527:                                        out);
0528:                                oos.writeObject(result);
0529:                                oos.flush();
0530:                            } else {
0531:                                // xml
0532:                                response.setContentType("text/plain");
0533:                                OutputStream out = response.getOutputStream();
0534:                                out.write(("<?xml version='1.0'?>\n")
0535:                                        .getBytes());
0536:                                XMLWriter w = new XMLWriter(
0537:                                        new OutputStreamWriter(out));
0538:                                result.toXML(w);
0539:                                w.flush();
0540:                            }
0541:                        }
0542:                    } catch (IOException e) {
0543:                        e.printStackTrace();
0544:                    }
0545:                }
0546:
0547:                private void viewMoreLink() throws IOException {
0548:                    response.setContentType("text/html");
0549:                    out = response.getWriter();
0550:                    format = FORMAT_HTML; // Force html format
0551:                    out.println("<html>\n" + "<head>\n" + "<title>"
0552:                            + getTitlePrefix()
0553:                            + "Completion of More Agents</title>\n"
0554:                            + "</head>\n" + "<body>");
0555:                    String firstAgent = request.getParameter("firstAgent");
0556:                    if (firstAgent != null) {
0557:                        out.println("<A href=\"/$" + getEncodedAgentName()
0558:                                + getPath()
0559:                                + "?viewType=viewAllAgents&refreshInterval="
0560:                                + refreshInterval + "&redThreshold="
0561:                                + redThreshold + "&yellowThreshold="
0562:                                + yellowThreshold + "&firstAgent=" + firstAgent
0563:                                + "\" + target=\"_top\">\n"
0564:                                + "<h2><center>More Agents</h2></center>\n"
0565:                                + "</A>");
0566:                    }
0567:                    out.println("</body>\n</html>");
0568:                }
0569:
0570:                private void viewTitle() throws IOException {
0571:                    String title = request.getParameter("title");
0572:                    response.setContentType("text/html");
0573:                    if (refreshInterval > 0) {
0574:                        response.setHeader("Refresh", String
0575:                                .valueOf(refreshInterval));
0576:                    }
0577:                    List agents = getSelectedAgents();
0578:                    out = response.getWriter();
0579:                    format = FORMAT_HTML; // Force html format
0580:                    out.println("<html>\n" + "<head>\n" + "<title>" + title
0581:                            + "</title>\n" + "</head>\n" + "<body>\n"
0582:                            + "<h2><center>" + title + "</h2></center>\n");
0583:                    int totalAgents = agents.size();
0584:                    int nPages = (totalAgents + MAX_AGENT_FRAMES - 1)
0585:                            / MAX_AGENT_FRAMES;
0586:                    String[] menu = null;
0587:                    if (nPages > 1) {
0588:                        menu = new String[nPages];
0589:                        for (int page = 0; page < nPages; page++) {
0590:                            int nagents;
0591:                            int agent0;
0592:                            agent0 = (page * totalAgents + nPages - 1) / nPages;
0593:                            nagents = (((page + 1) * totalAgents + nPages - 1) / nPages)
0594:                                    - agent0;
0595:                            String item = "Agents "
0596:                                    + ((String) agents.get(agent0))
0597:                                    + " Through "
0598:                                    + ((String) agents
0599:                                            .get(agent0 + nagents - 1));
0600:                            menu[page] = item;
0601:                        }
0602:                    }
0603:                    String this Page = request.getParameter("thisPage");
0604:                    printThresholdAndRefreshForm(out, agents, menu, this Page);
0605:                    out.println("</body>\n" + "</html>");
0606:                }
0607:
0608:                private void printThresholdAndRefreshForm(PrintWriter out,
0609:                        List selectedAgents, String[] menu, String this Page) {
0610:                    out.println("<form name=\"viewTitle\" action=\"/$"
0611:                            + getEncodedAgentName() + getPath()
0612:                            + "\"method=\"post\" target=\"_top\">");
0613:                    out.println("<table>");
0614:                    out.print("<tr><td>");
0615:                    out.print("Red Threshold");
0616:                    out.print("</td><td>");
0617:                    out
0618:                            .print("<input name=\"redThreshold\" type=\"text\" value=\""
0619:                                    + redThreshold + "\">");
0620:                    out.print("</td><td>");
0621:                    out.print("Yellow Threshold");
0622:                    out.print("</td><td>");
0623:                    out
0624:                            .print("<input name=\"yellowThreshold\" type=\"text\" value=\""
0625:                                    + yellowThreshold + "\">");
0626:                    out.println("</td><td rowspan=3>");
0627:                    if (menu != null) {
0628:                        out
0629:                                .println("<select name=\"page\" size=3 onclick=\"document.viewTitle.submit()\">");
0630:                        for (int page = 0; page < menu.length; page++) {
0631:                            out
0632:                                    .println("<option value=\""
0633:                                            + page
0634:                                            + "\" onclick=\"document.viewTitle.submit()\">");
0635:                            out.println(menu[page]);
0636:                            out.println("</option>");
0637:                        }
0638:                        out.println("</select>");
0639:                    }
0640:                    out.println("</td></tr>");
0641:                    out.print("<tr><td>");
0642:                    out.print("Refresh Interval");
0643:                    out.print("</td><td>");
0644:                    out
0645:                            .print("<input name=\"refreshInterval\" type=\"text\" value=\""
0646:                                    + refreshInterval + "\">");
0647:                    out.print("</td><td>");
0648:                    out
0649:                            .print("<input type=\"submit\" name=\"submit\" value=\"Refresh\">");
0650:                    out.println("</td>");
0651:                    out.println("</tr>");
0652:                    out.println("</table>");
0653:                    out
0654:                            .println("<input type=\"hidden\" name=\"viewType\" value=\"viewSelectedAgents\">");
0655:                    for (int i = 0, n = selectedAgents.size(); i < n; i++) {
0656:                        String agentName = (String) selectedAgents.get(i);
0657:                        out
0658:                                .println("<input type=\"hidden\" name=\"selectedAgents\" value=\""
0659:                                        + agentName + "\">");
0660:                    }
0661:                    out
0662:                            .println("<input type=\"hidden\" name=\"currentPage\" value=\""
0663:                                    + this Page + "\">");
0664:                    out.println("</form>");
0665:                }
0666:
0667:                // Output a page showing summary info for all agents
0668:                private void viewAllAgents() throws IOException {
0669:                    viewSelectedAgents(getAllAgentNames(), "All");
0670:                }
0671:
0672:                private void viewSelectedAgents() throws IOException {
0673:                    viewSelectedAgents(getSelectedAgents(), "Selected");
0674:                }
0675:
0676:                private void viewSelectedAgents(List agents,
0677:                        String titleModifier) throws IOException {
0678:                    response.setContentType("text/html");
0679:                    if (refreshInterval > 0) {
0680:                        response.setHeader("Refresh", String
0681:                                .valueOf(refreshInterval));
0682:                    }
0683:                    out = response.getWriter();
0684:                    format = FORMAT_HTML; // Force html format
0685:                    String title = getTitlePrefix() + "Completion of "
0686:                            + titleModifier + " Agents";
0687:                    out.println("<html>\n" + "<head>\n" + "<title>" + title
0688:                            + "</title>\n" + "</head>");
0689:                    boolean use_iframes = false;
0690:                    String browser = request.getHeader("user-agent")
0691:                            .toLowerCase();
0692:                    if (browser != null) {
0693:                        for (int i = 0; i < iframeBrowsers.length; i++) {
0694:                            if (browser.indexOf(iframeBrowsers[i]) >= 0) {
0695:                                use_iframes = true;
0696:                                break;
0697:                            }
0698:                        }
0699:                    }
0700:                    if (use_iframes) {
0701:                        out.println("<body>\n" + "<h2><center>" + title
0702:                                + "</h2></center>");
0703:                        printThresholdAndRefreshForm(out, agents, null, null);
0704:                        for (int i = 0, n = agents.size(); i < n; i++) {
0705:                            String agentName = (String) agents.get(i);
0706:                            out
0707:                                    .println("<iframe src=\"/$"
0708:                                            + formURLEncode(agentName)
0709:                                            + getPath()
0710:                                            + "?viewType=viewAgentSmall&redThreshold="
0711:                                            + redThreshold
0712:                                            + "&yellowThreshold="
0713:                                            + yellowThreshold
0714:                                            + "\" scrolling=\"no\" width=300 height=151>"
0715:                                            + agentName + "</iframe>");
0716:                        }
0717:                        out.println("</body>");
0718:                    } else {
0719:                        int totalAgents = agents.size();
0720:                        int nPages = (totalAgents + MAX_AGENT_FRAMES - 1)
0721:                                / MAX_AGENT_FRAMES;
0722:                        int nagents;
0723:                        int agent0;
0724:                        int page;
0725:                        if (nPages > 1) {
0726:                            try {
0727:                                page = Integer.parseInt(request
0728:                                        .getParameter("page"));
0729:                            } catch (Exception e) {
0730:                                try {
0731:                                    page = Integer.parseInt(request
0732:                                            .getParameter("currentPage"));
0733:                                } catch (Exception e1) {
0734:                                    page = 0;
0735:                                }
0736:                            }
0737:                            agent0 = (page * totalAgents + nPages - 1) / nPages;
0738:                            nagents = (((page + 1) * totalAgents + nPages - 1) / nPages)
0739:                                    - agent0;
0740:                            title = titleModifier
0741:                                    + " Agents "
0742:                                    + ((String) agents.get(agent0))
0743:                                    + " Through "
0744:                                    + ((String) agents
0745:                                            .get(agent0 + nagents - 1));
0746:                        } else {
0747:                            agent0 = 0;
0748:                            nagents = totalAgents;
0749:                            title = "All Agents";
0750:                            page = 0;
0751:                        }
0752:                        int nrows = (nagents + 2) / 3;
0753:                        out.print("<frameset rows=\"100");
0754:                        for (int row = 0; row < nrows; row++) {
0755:                            out.print(",100");
0756:                        }
0757:                        out.print("\">\n" + "  <frame src=\"/$"
0758:                                + getEncodedAgentName() + getPath()
0759:                                + "?viewType=viewTitle&title="
0760:                                + getTitlePrefix() + "Completion+of+"
0761:                                + formURLEncode(title) + "&refreshInterval="
0762:                                + refreshInterval + "&redThreshold="
0763:                                + redThreshold + "&yellowThreshold="
0764:                                + yellowThreshold + "&thisPage=" + page
0765:                                + "&nextPage=" + ((page + 1) % nPages));
0766:                        for (int i = 0; i < totalAgents; i++) {
0767:                            String agentName = (String) agents.get(i);
0768:                            out.print("&selectedAgents="
0769:                                    + formURLEncode(agentName));
0770:                        }
0771:                        out.println("\" scrolling=\"no\">");
0772:                        for (int row = 0; row < nrows; row++) {
0773:                            out.println("  <frameset cols=\"300,300,300\">");
0774:                            for (int col = 0; col < 3; col++) {
0775:                                int agentn = agent0 + row * 3 + col;
0776:                                if (agentn < agent0 + nagents) {
0777:                                    String agentName = (String) agents
0778:                                            .get(agentn);
0779:                                    out
0780:                                            .println("    <frame src=\""
0781:                                                    + "/$"
0782:                                                    + formURLEncode(agentName)
0783:                                                    + getPath()
0784:                                                    + "?viewType=viewAgentSmall&redThreshold="
0785:                                                    + redThreshold
0786:                                                    + "&yellowThreshold="
0787:                                                    + yellowThreshold
0788:                                                    + "\" scrolling=\"no\">");
0789:                                } else if (agentn == agent0 + nagents) {
0790:                                }
0791:                            }
0792:                            out.println("  </frameset>");
0793:                        }
0794:                        out.println("</frameset>");
0795:                    }
0796:                    out.println("<html>");
0797:                }
0798:
0799:                private List getSelectedAgents() {
0800:                    String[] selectedAgents = request
0801:                            .getParameterValues("selectedAgents");
0802:                    if (selectedAgents != null) {
0803:                        List ret = new ArrayList(Arrays.asList(selectedAgents));
0804:                        Collections.sort(ret);
0805:                        return ret;
0806:                    } else {
0807:                        return Collections.EMPTY_LIST;
0808:                    }
0809:                }
0810:
0811:                // Output a checkbox form allowing selection of multiple agents
0812:                private void viewManyAgents() throws IOException {
0813:                    response.setContentType("text/html");
0814:                    out = response.getWriter();
0815:                    format = FORMAT_HTML; // Force html format
0816:                    SortedSet selectedAgents = new TreeSet(getSelectedAgents());
0817:                    boolean selectAll = false;
0818:                    boolean selectNone = false;
0819:                    String submit = request.getParameter("submit");
0820:                    if ("Show".equals(submit)) {
0821:                        viewSelectedAgents(new ArrayList(selectedAgents),
0822:                                "Selected");
0823:                        return;
0824:                    }
0825:                    if ("Select All".equals(submit)) {
0826:                        selectAll = true;
0827:                    } else if ("Select None".equals(submit)) {
0828:                        selectNone = true;
0829:                    }
0830:                    List l = getAllAgentNames();
0831:                    Collections.sort(l);
0832:                    String title = "Select Agents for Completion Display";
0833:                    out.println("<html>\n" + "<head>\n" + "<title>"
0834:                            + getTitlePrefix() + title + "</title>\n"
0835:                            + "</head>");
0836:                    out.println("<body>\n" + "<h2><center>" + title
0837:                            + "</h2></center>");
0838:                    out.println("<form method=\"post\" action=\"/$"
0839:                            + getEncodedAgentName() + getPath()
0840:                            + "\" target=\"_top\">");
0841:                    out
0842:                            .println("<input type=\"submit\" name=\"submit\" value=\"Select All\">");
0843:                    out
0844:                            .println("<input type=\"submit\" name=\"submit\" value=\"Select None\">");
0845:                    out
0846:                            .println("<input type=\"submit\" name=\"submit\" value=\"Show\">");
0847:                    out
0848:                            .println("<input type=\"hidden\" name=\"viewType\" value=\"viewManyAgents\">");
0849:                    out.println("<table><tr>");
0850:                    int nagents = l.size();
0851:                    int agent0 = 0;
0852:                    int NCOL = 4;
0853:                    for (int col = 0; col < NCOL; col++) {
0854:                        out.println("<td valign=\"top\">");
0855:                        int agent1 = ((col + 1) * nagents + NCOL - 1) / NCOL;
0856:                        for (; agent0 < agent1; agent0++) {
0857:                            String agentName = (String) l.get(agent0);
0858:                            String selected;
0859:                            if (selectAll
0860:                                    || (!selectNone && selectedAgents
0861:                                            .contains(agentName))) {
0862:                                selected = " checked=\"true\"";
0863:                            } else {
0864:                                selected = "";
0865:                            }
0866:                            out
0867:                                    .println("<input type=\"checkbox\" name=\"selectedAgents\" value=\""
0868:                                            + agentName
0869:                                            + "\""
0870:                                            + selected
0871:                                            + ">"
0872:                                            + agentName + "</input><br>");
0873:                        }
0874:                        out.println("</td>");
0875:                        agent0 = agent1;
0876:                    }
0877:                    out.println("</tr></table>");
0878:                    out.println("</form>");
0879:                    out.println("</body>");
0880:                    out.println("</html>");
0881:                }
0882:
0883:                // Output a small page showing summary info for one agent
0884:                private void viewAgentSmall() throws IOException {
0885:                    response.setContentType("text/html");
0886:                    out = response.getWriter();
0887:                    format = FORMAT_HTML; // Force html format
0888:                    String agent = getEncodedAgentName();
0889:                    CompletionData result = getCompletionData();
0890:                    double ratio = result.getRatio();
0891:                    int nTasks = result.getNumberOfTasks();
0892:                    int nUnplannedTasks = result.getNumberOfUnplannedTasks();
0893:                    int nPlannedTasks = (nTasks - nUnplannedTasks);
0894:                    int nRootProjectSupplyTasks = result
0895:                            .getNumberOfRootProjectSupplyTasks();
0896:                    int nRootSupplyTasks = result.getNumberOfRootSupplyTasks();
0897:                    int nRootTransportTasks = result
0898:                            .getNumberOfRootTransportTasks();
0899:
0900:                    double percentPlannedTasks = ((nTasks > 0) ? (1.0 * nPlannedTasks)
0901:                            / nTasks
0902:                            : 0.0);
0903:                    int nUnestimatedTasks = result
0904:                            .getNumberOfUnestimatedTasks();
0905:                    int nEstimatedTasks = (nPlannedTasks - nUnestimatedTasks);
0906:                    //      double percentEstimatedTasks =
0907:                    //        ((nPlannedTasks > 0) ? 
0908:                    //         (1.0 * nEstimatedTasks) / nPlannedTasks :
0909:                    //         0.0);
0910:                    int nFailedTasks = result.getNumberOfFailedTasks();
0911:                    int nSuccessfulTasks = (nEstimatedTasks - nFailedTasks);
0912:                    double percentSuccessfulTasks = ((nEstimatedTasks > 0) ? (1.0 * nSuccessfulTasks)
0913:                            / nEstimatedTasks
0914:                            : 0.0);
0915:                    int nUnconfidentTasks = result
0916:                            .getNumberOfUnconfidentTasks();
0917:                    int nFullConfidenceTasks = (nSuccessfulTasks - nUnconfidentTasks);
0918:                    double percentFullConfidenceTasks = ((nSuccessfulTasks > 0) ? (1.0 * nFullConfidenceTasks)
0919:                            / nSuccessfulTasks
0920:                            : 0.0);
0921:                    String bgcolor, fgcolor, lncolor;
0922:                    if (ratio < redThreshold) {
0923:                        bgcolor = "#aa0000";
0924:                        fgcolor = "#ffffff";
0925:                        lncolor = "#ffff00";
0926:                    } else if (ratio < yellowThreshold) {
0927:                        bgcolor = "#ffff00";
0928:                        fgcolor = "#000000";
0929:                        lncolor = "#0000ff";
0930:                    } else {
0931:                        bgcolor = "#d0ffd0";
0932:                        fgcolor = "#000000";
0933:                        lncolor = "#0000ff";
0934:                    }
0935:                    out.println("<html>\n" + "<head>\n" + "</head>\n" + "<body"
0936:                            + " bgcolor=\"" + bgcolor + "\" text=\"" + fgcolor
0937:                            + "\" vlink=\"" + lncolor + "\" link=\"" + lncolor
0938:                            + "\">\n" + "<pre><a href=\"" + "/$" + agent
0939:                            + getPath() + "\" target=\"_top\">" + agent
0940:                            + "</a>");
0941:                    out.println(formatLabel("Ratio:") + "  <b>"
0942:                            + formatPercent(ratio) + "</b> (" + ratio + ")");
0943:                    out.println(formatLabel("Tasks:") + formatInteger(nTasks));
0944:                    out.println(formatLabel("Planned:")
0945:                            + formatInteger(nPlannedTasks) + "("
0946:                            + formatPercent(percentPlannedTasks) + ")");
0947:                    out.println(formatLabel("Successful:")
0948:                            + formatInteger(nSuccessfulTasks) + "("
0949:                            + formatPercent(percentSuccessfulTasks) + ")");
0950:                    out.println(formatLabel("Completed:")
0951:                            + formatInteger(nFullConfidenceTasks) + "("
0952:                            + formatPercent(percentFullConfidenceTasks) + ")");
0953:                    out.println(formatLabel("Root Proj Supply Tasks:")
0954:                            + formatInteger(nRootProjectSupplyTasks));
0955:                    out.println(formatLabel("Root Supply Tasks:")
0956:                            + formatInteger(nRootSupplyTasks));
0957:                    out.println(formatLabel("Root Transport Tasks:")
0958:                            + formatInteger(nRootTransportTasks) + "</pre>");
0959:                    out.println("</body>\n</html>");
0960:                }
0961:
0962:                private String formatLabel(String lbl) {
0963:                    int nchars = lbl.length();
0964:                    if (nchars > 24)
0965:                        return lbl;
0966:                    return lbl + "                        ".substring(nchars);
0967:                }
0968:
0969:                private String formatInteger(int n) {
0970:                    return formatInteger(n, 5);
0971:                }
0972:
0973:                private final String SPACES = "                    ";
0974:                private final int NSPACES = SPACES.length();
0975:
0976:                private String formatInteger(int n, int w) {
0977:                    if (w > NSPACES)
0978:                        w = NSPACES;
0979:                    String r = String.valueOf(n);
0980:                    int needed = w - r.length();
0981:                    if (needed <= 0)
0982:                        return r;
0983:                    return SPACES.substring(0, needed) + r;
0984:                }
0985:
0986:                private String formatPercent(double percent) {
0987:                    return formatInteger((int) (percent * 100.0), 3) + "%";
0988:                }
0989:
0990:                private String formatColorBar(String color) {
0991:                    return "<table width=\"100%\" bgcolor=\"" + color
0992:                            + "\"><tr><td>&nbsp;</td></tr></table>";
0993:                }
0994:
0995:                protected Collection getAllTasks() {
0996:                    Collection col = queryBlackboard(TASK_PRED);
0997:                    if (col == null)
0998:                        col = Collections.EMPTY_LIST;
0999:                    return col;
1000:                }
1001:
1002:                protected double getRatio(Collection tasks) {
1003:                    Collection objs;
1004:                    CompletionCalculator cc = getCalculator();
1005:                    if (cc.getClass() == CompletionCalculator.class) {
1006:                        // short cut for basic task completion
1007:                        objs = tasks;
1008:                    } else {
1009:                        UnaryPredicate pred = cc.getPredicate();
1010:                        objs = queryBlackboard(pred);
1011:                    }
1012:                    return cc.calculate(objs);
1013:                }
1014:
1015:                public Collection filterTasks(Collection allTasks,
1016:                        UnaryPredicate predicate) {
1017:                    return Filters.filter(allTasks, predicate);
1018:                }
1019:
1020:                protected CompletionData getCompletionData() {
1021:                    // get tasks
1022:                    Collection tasks = getAllTasks();
1023:                    CompletionCalculator cc = getCalculator();
1024:                    long nowTime = System.currentTimeMillis();
1025:                    double ratio = getRatio(tasks);
1026:                    int nTasks = tasks.size();
1027:                    int nRootProjectSupplyTasks = filterTasks(tasks,
1028:                            projectSupplyRootTaskPred).size();
1029:                    int nRootSupplyTasks = filterTasks(tasks,
1030:                            supplyRootTaskPred).size();
1031:                    int nRootTransportTasks = filterTasks(tasks,
1032:                            transportRootTaskPred).size();
1033:
1034:                    Iterator taskIter = tasks.iterator();
1035:                    if (showTables) {
1036:                        // create and initialize our result
1037:                        FullCompletionData result = new FullCompletionData();
1038:                        result.setNumberOfTasks(nTasks);
1039:                        result.setRatio(ratio);
1040:                        result.setTimeMillis(nowTime);
1041:                        result
1042:                                .setNumberOfRootProjectSupplyTasks(nRootProjectSupplyTasks);
1043:                        result.setNumberOfRootSupplyTasks(nRootSupplyTasks);
1044:                        result
1045:                                .setNumberOfRootTransportTasks(nRootTransportTasks);
1046:
1047:                        // examine tasks
1048:                        for (int i = 0; i < nTasks; i++) {
1049:                            Task ti = (Task) taskIter.next();
1050:                            PlanElement pe = ti.getPlanElement();
1051:                            if (pe != null) {
1052:                                AllocationResult peEstResult = pe
1053:                                        .getEstimatedResult();
1054:                                if (peEstResult != null) {
1055:                                    double estConf = peEstResult
1056:                                            .getConfidenceRating();
1057:                                    if (peEstResult.isSuccess()) {
1058:                                        if (cc.isConfident(estConf)) {
1059:                                            // Confident
1060:                                        } else {
1061:                                            result
1062:                                                    .addUnconfidentTask(makeUnconfidentTask(
1063:                                                            estConf, ti));
1064:                                        }
1065:                                    } else {
1066:                                        result.addFailedTask(makeFailedTask(
1067:                                                estConf, ti));
1068:                                    }
1069:                                } else {
1070:                                    result
1071:                                            .addUnestimatedTask(makeUnestimatedTask(ti));
1072:                                }
1073:                            } else {
1074:                                result.addUnplannedTask(makeUnplannedTask(ti));
1075:                            }
1076:                        }
1077:                        return result;
1078:                    } else {
1079:                        // create and initialize our result
1080:                        SimpleCompletionData result = new SimpleCompletionData();
1081:                        result.setNumberOfTasks(nTasks);
1082:                        result.setRatio(ratio);
1083:                        result.setTimeMillis(nowTime);
1084:                        result
1085:                                .setNumberOfRootProjectSupplyTasks(nRootProjectSupplyTasks);
1086:                        result.setNumberOfRootSupplyTasks(nRootSupplyTasks);
1087:                        result
1088:                                .setNumberOfRootTransportTasks(nRootTransportTasks);
1089:                        // examine tasks
1090:                        int nUnplannedTasks = 0;
1091:                        int nUnestimatedTasks = 0;
1092:                        int nFailedTasks = 0;
1093:                        int nUnconfidentTasks = 0;
1094:                        for (int i = 0; i < nTasks; i++) {
1095:                            Task ti = (Task) taskIter.next();
1096:                            PlanElement pe = ti.getPlanElement();
1097:                            if (pe != null) {
1098:                                AllocationResult peEstResult = pe
1099:                                        .getEstimatedResult();
1100:                                if (peEstResult != null) {
1101:                                    double estConf = peEstResult
1102:                                            .getConfidenceRating();
1103:                                    if (peEstResult.isSuccess()) {
1104:                                        if (cc.isConfident(estConf)) {
1105:                                            // 100% success
1106:                                        } else {
1107:                                            nUnconfidentTasks++;
1108:                                        }
1109:                                    } else {
1110:                                        nFailedTasks++;
1111:                                    }
1112:                                } else {
1113:                                    nUnestimatedTasks++;
1114:                                }
1115:                            } else {
1116:                                nUnplannedTasks++;
1117:                            }
1118:                        }
1119:                        result.setNumberOfUnplannedTasks(nUnplannedTasks);
1120:                        result.setNumberOfUnestimatedTasks(nUnestimatedTasks);
1121:                        result.setNumberOfFailedTasks(nFailedTasks);
1122:                        result.setNumberOfUnconfidentTasks(nUnconfidentTasks);
1123:                        return result;
1124:                    }
1125:                }
1126:
1127:                /**
1128:                 * Create an <code>UnplannedTask</code> for the given <code>Task</code>.
1129:                 */
1130:                protected UnplannedTask makeUnplannedTask(Task task) {
1131:                    UnplannedTask upt = new UnplannedTask();
1132:                    fillAbstractTask(upt, task);
1133:                    // leave confidence as 0%
1134:                    return upt;
1135:                }
1136:
1137:                /**
1138:                 * Create an <code>UnestimatedTask</code> for the given <code>Task</code>.
1139:                 */
1140:                protected UnestimatedTask makeUnestimatedTask(Task task) {
1141:                    UnestimatedTask uet = new UnestimatedTask();
1142:                    fillAbstractTask(uet, task);
1143:                    // leave confidence as 0%
1144:                    return uet;
1145:                }
1146:
1147:                /**
1148:                 * Create an <code>UnconfidentTask</code> for the given <code>Task</code>.
1149:                 *
1150:                 * @param confidence a double &gt;= 0.0 and &lt; 1.0
1151:                 */
1152:                protected UnconfidentTask makeUnconfidentTask(
1153:                        double confidence, Task task) {
1154:                    UnconfidentTask uct = new UnconfidentTask();
1155:                    fillAbstractTask(uct, task);
1156:                    uct.setConfidence(confidence);
1157:                    return uct;
1158:                }
1159:
1160:                /**
1161:                 * Create a <code>FailedTask</code> for the given <code>Task</code>.
1162:                 */
1163:                protected FailedTask makeFailedTask(double confidence, Task task) {
1164:                    FailedTask ft = new FailedTask();
1165:                    fillAbstractTask(ft, task);
1166:                    ft.setConfidence(confidence);
1167:                    return ft;
1168:                }
1169:
1170:                /**
1171:                 * Fill an <code>AbstractTask</code> for the given <code>Task</code>,
1172:                 * which will grab:<pre>
1173:                 *   the UID, 
1174:                 *   TASK.PSP's URL for that UID,
1175:                 *   the ParentUID, 
1176:                 *   TASK.PSP's URL for that ParentUID,
1177:                 *   a String description of the PlanElement</pre>.
1178:                 */
1179:                protected void fillAbstractTask(AbstractTask toAbsTask,
1180:                        Task task) {
1181:
1182:                    // set task UID
1183:                    UID taskUID = ((task != null) ? task.getUID() : null);
1184:                    String sTaskUID = ((taskUID != null) ? taskUID.toString()
1185:                            : null);
1186:                    if (sTaskUID == null) {
1187:                        return;
1188:                    }
1189:                    toAbsTask.setUID(sTaskUID);
1190:                    String sourceAgentId = formURLEncode(task.getSource()
1191:                            .getAddress());
1192:                    toAbsTask.setUID_URL(getTaskUID_URL(getEncodedAgentName(),
1193:                            sTaskUID));
1194:                    // set parent task UID
1195:                    UID pTaskUID = task.getParentTaskUID();
1196:                    String spTaskUID = ((pTaskUID != null) ? pTaskUID
1197:                            .toString() : null);
1198:                    if (spTaskUID != null) {
1199:                        toAbsTask.setParentUID(spTaskUID);
1200:                        toAbsTask.setParentUID_URL(getTaskUID_URL(
1201:                                sourceAgentId, spTaskUID));
1202:                    }
1203:                    // set plan element
1204:                    toAbsTask.setPlanElement(getPlanElement(task
1205:                            .getPlanElement()));
1206:                    // set verb
1207:                    toAbsTask.setVerb(task.getVerb().toString());
1208:                }
1209:
1210:                /**
1211:                 * Get the TASKS.PSP URL for the given UID String.
1212:                 *
1213:                 * Assumes that the TASKS.PSP URL is fixed at "/tasks".
1214:                 */
1215:                protected String getTaskUID_URL(String agentId, String sTaskUID) {
1216:                    /*
1217:                      // FIXME prefix with base URL?
1218:                      
1219:                      String baseURL =   
1220:                        request.getScheme()+
1221:                        "://"+
1222:                        request.getServerName()+
1223:                        ":"+
1224:                        request.getServerPort()+
1225:                        "/";
1226:                     */
1227:                    return "/$" + agentId + "/tasks?mode=3&uid=" + sTaskUID;
1228:                }
1229:
1230:                /**
1231:                 * Get a brief description of the given <code>PlanElement</code>.
1232:                 */
1233:                protected String getPlanElement(PlanElement pe) {
1234:                    return (pe instanceof  Allocation) ? "Allocation"
1235:                            : (pe instanceof  Expansion) ? "Expansion"
1236:                                    : (pe instanceof  Aggregation) ? "Aggregation"
1237:                                            : (pe instanceof  Disposition) ? "Disposition"
1238:                                                    : (pe instanceof  AssetTransfer) ? "AssetTransfer"
1239:                                                            : (pe != null) ? pe
1240:                                                                    .getClass()
1241:                                                                    .getName()
1242:                                                                    : null;
1243:                }
1244:
1245:                /**
1246:                 * Write the given <code>CompletionData</code> as formatted HTML.
1247:                 */
1248:                protected void printCompletionDataAsHTML(CompletionData result) {
1249:                    // javascript based on PlanViewServlet
1250:                    out.print("<html><body>\n" + "<h2><center>"
1251:                            + getTitlePrefix() + "Completion at "
1252:                            + getEncodedAgentName() + "</center></h2>\n");
1253:                    printCountersAsHTML(result);
1254:                    printTablesAsHTML(result);
1255:                    out.print("</body></html>");
1256:                    out.flush();
1257:                }
1258:
1259:                protected void printCountersAsHTML(CompletionData result) {
1260:                    double ratio = result.getRatio();
1261:                    String ratioColor;
1262:                    CompletionCalculator cc = getCalculator();
1263:                    if (ratio < redThreshold) {
1264:                        ratioColor = "red";
1265:                    } else if (ratio < yellowThreshold) {
1266:                        ratioColor = "yellow";
1267:                    } else {
1268:                        ratioColor = "#00d000";
1269:                    }
1270:                    out.print(formatColorBar(ratioColor) + "<pre>\n"
1271:                            + "Time: <b>");
1272:                    long timeMillis = result.getTimeMillis();
1273:                    out.print(new Date(timeMillis));
1274:                    out.print("</b>   (");
1275:                    out.print(timeMillis);
1276:                    out.print(" MS)\n" + getTitlePrefix()
1277:                            + "Completion ratio: <b>" + formatPercent(ratio)
1278:                            + "</b>" + "\nNumber of Tasks: <b>");
1279:                    int nTasks = result.getNumberOfTasks();
1280:                    out.print(nTasks);
1281:                    out.print("\n</b>Subset of Tasks[");
1282:                    out.print(nTasks);
1283:                    out.print("] planned (non-null PlanElement): <b>");
1284:                    int nUnplannedTasks = result.getNumberOfUnplannedTasks();
1285:                    int nPlannedTasks = (nTasks - nUnplannedTasks);
1286:                    out.print(nPlannedTasks);
1287:                    out.print("</b>  (<b>");
1288:                    double percentPlannedTasks = ((nTasks > 0) ? (100.0 * (((double) nPlannedTasks) / nTasks))
1289:                            : 0.0);
1290:                    out.print(percentPlannedTasks);
1291:                    out.print(" %</b>)" + "\nSubset of planned[");
1292:                    out.print(nPlannedTasks);
1293:                    out.print("] estimated (non-null EstimatedResult): <b>");
1294:                    int nUnestimatedTasks = result
1295:                            .getNumberOfUnestimatedTasks();
1296:                    int nEstimatedTasks = (nPlannedTasks - nUnestimatedTasks);
1297:                    out.print(nEstimatedTasks);
1298:                    out.print("</b>  (<b>");
1299:                    double percentEstimatedTasks = ((nPlannedTasks > 0) ? (100.0 * (((double) nEstimatedTasks) / nPlannedTasks))
1300:                            : 0.0);
1301:                    out.print(percentEstimatedTasks);
1302:                    out.print(" %</b>)" + "\nSubset of estimated[");
1303:                    out.print(nEstimatedTasks);
1304:                    out.print("] that are estimated successful: <b>");
1305:                    int nFailedTasks = result.getNumberOfFailedTasks();
1306:                    int nSuccessfulTasks = (nEstimatedTasks - nFailedTasks);
1307:                    out.print(nSuccessfulTasks);
1308:                    out.print("</b>  (<b>");
1309:                    double percentSuccessfulTasks = ((nEstimatedTasks > 0) ? (100.0 * (((double) nSuccessfulTasks) / nEstimatedTasks))
1310:                            : 0.0);
1311:                    out.print(percentSuccessfulTasks);
1312:                    out.print(" %</b>)" + "\nSubset of estimated successful[");
1313:                    out.print(nSuccessfulTasks);
1314:                    out
1315:                            .print("] with "
1316:                                    + cc.getConfidenceThreshholdString(true)
1317:                                    + " : <b>");
1318:                    int nUnconfidentTasks = result
1319:                            .getNumberOfUnconfidentTasks();
1320:                    int nFullConfidenceTasks = (nSuccessfulTasks - nUnconfidentTasks);
1321:                    out.print(nFullConfidenceTasks);
1322:                    out.print("</b>  (<b>");
1323:                    double percentFullConfidenceTasks = ((nSuccessfulTasks > 0) ? (100.0 * (((double) nFullConfidenceTasks) / nSuccessfulTasks))
1324:                            : 0.0);
1325:                    out.print(percentFullConfidenceTasks);
1326:                    out.print(" %</b>)\n");
1327:                    out.print("</b>"
1328:                            + "\nNumber of Root ProjectSupply Tasks: <b>");
1329:                    out.print(result.getNumberOfRootProjectSupplyTasks());
1330:                    out.print("</b>" + "\nNumber of Root Supply Tasks: <b>");
1331:                    out.print(result.getNumberOfRootSupplyTasks());
1332:                    out.print("</b>" + "\nNumber of Root Transport Tasks: <b>");
1333:                    out.print(result.getNumberOfRootTransportTasks());
1334:                    out.print("</pre>\n");
1335:                }
1336:
1337:                protected void printTablesAsHTML(CompletionData result) {
1338:                    CompletionCalculator cc = getCalculator();
1339:                    if (result instanceof  FullCompletionData) {
1340:                        int nUnplannedTasks = result
1341:                                .getNumberOfUnplannedTasks();
1342:                        beginTaskHTMLTable(("Unplanned Tasks["
1343:                                + nUnplannedTasks + "]"),
1344:                                "(PlanElement == null)");
1345:                        for (int i = 0; i < nUnplannedTasks; i++) {
1346:                            printAbstractTaskAsHTML(i, result
1347:                                    .getUnplannedTaskAt(i));
1348:                        }
1349:                        endTaskHTMLTable();
1350:                        int nUnestimatedTasks = result
1351:                                .getNumberOfUnestimatedTasks();
1352:                        beginTaskHTMLTable(("Unestimated Tasks["
1353:                                + nUnestimatedTasks + "]"), "(Est. == null)");
1354:                        for (int i = 0; i < nUnestimatedTasks; i++) {
1355:                            printAbstractTaskAsHTML(i, result
1356:                                    .getUnestimatedTaskAt(i));
1357:                        }
1358:                        endTaskHTMLTable();
1359:                        int nFailedTasks = result.getNumberOfFailedTasks();
1360:                        beginTaskHTMLTable(
1361:                                ("Failed Tasks[" + nFailedTasks + "]"),
1362:                                "(Est.isSuccess() == false)");
1363:                        for (int i = 0; i < nFailedTasks; i++) {
1364:                            printAbstractTaskAsHTML(i, result
1365:                                    .getFailedTaskAt(i));
1366:                        }
1367:                        endTaskHTMLTable();
1368:                        int nUnconfidentTasks = result
1369:                                .getNumberOfUnconfidentTasks();
1370:                        beginTaskHTMLTable(
1371:                                ("Unconfident Tasks[" + nUnconfidentTasks + "]"),
1372:                                "((Est.isSuccess() == true) &amp;&amp; ("
1373:                                        + cc
1374:                                                .getConfidenceThreshholdString(false)
1375:                                        + ")");
1376:                        for (int i = 0; i < nUnconfidentTasks; i++) {
1377:                            printAbstractTaskAsHTML(i, result
1378:                                    .getUnconfidentTaskAt(i));
1379:                        }
1380:                        endTaskHTMLTable();
1381:                    } else {
1382:                        // no table data
1383:                        out.print("<p>" + "<a href=\"");
1384:                        out.print("/$");
1385:                        out.print(getEncodedAgentName());
1386:                        out.print(getPath());
1387:                        out
1388:                                .print("?showTables=true&viewType=viewAgentBig\" target=\"viewAgentBig\">"
1389:                                        + "Full Listing of Unplanned/Unestimated/Failed/Unconfident Tasks (");
1390:                        out.print((result.getNumberOfTasks() - result
1391:                                .getNumberOfFullySuccessfulTasks()));
1392:                        out.println(" lines)</a><br>");
1393:                    }
1394:                }
1395:
1396:                /**
1397:                 * Begin a table of <tt>printAbstractTaskAsHTML</tt> entries.
1398:                 */
1399:                protected void beginTaskHTMLTable(String title, String subTitle) {
1400:                    out
1401:                            .print("<table border=1 cellpadding=3 cellspacing=1 width=\"100%\">\n"
1402:                                    + "<tr bgcolor=lightgrey><th align=left colspan=6>");
1403:                    out.print(title);
1404:                    if (subTitle != null) {
1405:                        out
1406:                                .print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<tt><i>");
1407:                        out.print(subTitle);
1408:                        out.print("</i></tt>");
1409:                    }
1410:                    out.print("</th></tr>\n" + "<tr>" + "<th></th>"
1411:                            + "<th>UID</th>" + "<th>ParentUID</th>"
1412:                            + "<th>Verb</th>" + "<th>Confidence</th>"
1413:                            + "<th>PlanElement</th>" + "</tr>\n");
1414:                }
1415:
1416:                /**
1417:                 * End a table of <tt>printAbstractTaskAsHTML</tt> entries.
1418:                 */
1419:                protected void endTaskHTMLTable() {
1420:                    out.print("</table>\n" + "<p>\n");
1421:                }
1422:
1423:                /**
1424:                 * Write the given <code>AbstractTask</code> as formatted HTML.
1425:                 */
1426:                protected void printAbstractTaskAsHTML(int index,
1427:                        AbstractTask at) {
1428:                    out.print("<tr align=right><td>");
1429:                    out.print(index);
1430:                    out.print("</td><td>");
1431:                    String uidURL = at.getUID_URL();
1432:                    if (uidURL != null) {
1433:                        out.print("<a href=\"");
1434:                        out.print(uidURL);
1435:                        out.print("\" target=\"itemFrame\">");
1436:                    }
1437:                    out.print(at.getUID());
1438:                    if (uidURL != null) {
1439:                        out.print("</a>");
1440:                    }
1441:                    out.print("</td><td>");
1442:                    String pUidURL = at.getParentUID_URL();
1443:                    if (pUidURL != null) {
1444:                        out.print("<a href=\"");
1445:                        out.print(at.getParentUID_URL());
1446:                        out.print("\" target=\"itemFrame\">");
1447:                    }
1448:                    out.print(at.getParentUID());
1449:                    if (pUidURL != null) {
1450:                        out.print("</a>");
1451:                    }
1452:                    out.print("</td><td>");
1453:                    out.print(at.getVerb());
1454:                    out.print("</td><td>");
1455:                    double conf = at.getConfidence();
1456:                    out.print((conf < 0.001) ? "0.0%" : ((100.0 * conf) + "%"));
1457:                    out.print("</td><td>");
1458:                    out.print(at.getPlanElement());
1459:                    out.print("</td></tr>\n");
1460:                }
1461:            }
1462:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.