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


0001:        /*
0002:         * <copyright>
0003:         *  
0004:         *  Copyright 2001-2004 BBNT Solutions, LLC
0005:         *  under sponsorship of the Defense Advanced Research Projects
0006:         *  Agency (DARPA).
0007:         * 
0008:         *  You can redistribute this software and/or modify it under the
0009:         *  terms of the Cougaar Open Source License as published on the
0010:         *  Cougaar Open Source Website (www.cougaar.org).
0011:         * 
0012:         *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0013:         *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0014:         *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0015:         *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0016:         *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0017:         *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0018:         *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0019:         *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0020:         *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0021:         *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0022:         *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0023:         *  
0024:         * </copyright>
0025:         */
0026:        package org.cougaar.lib.vishnu.client;
0027:
0028:        import com.bbn.vishnu.scheduling.SchedulingData;
0029:        import org.apache.xerces.parsers.DOMParser;
0030:        import org.cougaar.core.util.UniqueObject;
0031:        import org.cougaar.lib.callback.UTILAssetCallback;
0032:        import org.cougaar.lib.callback.UTILAssetListener;
0033:        import org.cougaar.lib.filter.UTILBufferingPluginAdapter;
0034:        import org.cougaar.planning.Constants;
0035:        import org.cougaar.planning.ldm.asset.Asset;
0036:        import org.cougaar.planning.ldm.plan.AllocationResultAggregator;
0037:        import org.cougaar.planning.ldm.plan.Expansion;
0038:        import org.cougaar.planning.ldm.plan.NewTask;
0039:        import org.cougaar.planning.ldm.plan.PrepositionalPhrase;
0040:        import org.cougaar.planning.ldm.plan.Task;
0041:        import org.cougaar.planning.ldm.plan.Verb;
0042:        import org.cougaar.planning.ldm.plan.Workflow;
0043:        import org.cougaar.util.StringKey;
0044:        import org.w3c.dom.Document;
0045:        import org.w3c.dom.Element;
0046:        import org.xml.sax.InputSource;
0047:
0048:        import java.io.FileNotFoundException;
0049:        import java.io.InputStream;
0050:        import java.util.ArrayList;
0051:        import java.util.Collection;
0052:        import java.util.Date;
0053:        import java.util.Enumeration;
0054:        import java.util.HashMap;
0055:        import java.util.HashSet;
0056:        import java.util.Iterator;
0057:        import java.util.List;
0058:        import java.util.Map;
0059:        import java.util.Set;
0060:        import java.util.Vector;
0061:
0062:        /**
0063:         * <pre>
0064:         * ALP-Vishnu bridge.
0065:         *
0066:         * Base class for interacting with the Vishnu scheduler.
0067:         *
0068:         * There are 3 main dimensions of behavior for this plugin: 
0069:         *  - SchedulerMode (External, Internal, or Direct)         
0070:         *  - Job type      (Batch or Incremental)                  
0071:         *  - Translation   (Automatic or Custom)                   
0072:         *
0073:         * Supports three main scheduler modes : External, Internal, and Direct.  These
0074:         * are classes which implement the SchedulerLifecycle interface.  They
0075:         * orchestrate the steps to use the Vishnu Scheduler.  The VishnuPlugin
0076:         * is a ModeListener and its as a mode listener that the modes communicate
0077:         * with the plugin.
0078:         *
0079:         *
0080:         * <b>External</b> mode uses the web server and expects the scheduling to be 
0081:         * done by a separate Vishnu Scheduler process.  All communication is done with 
0082:         * XML.
0083:         * <b>Internal</b> mode uses an internal Vishnu Scheduler process, but 
0084:         * communicates exclusively through XML.
0085:         * <b>Direct</b> mode extends internal mode, but directly translates between
0086:         * Cougaar objects and Vishnu scheduling objects.
0087:         *
0088:         * The results of a scheduling job are handled by a ResultHandler, which
0089:         * can be either an XMLResultHandler, or a DirectResultHandler. Each mode is a
0090:         * ResultListener and communicates with its result handler.
0091:         *
0092:         * Orthogonal to the scheduling modes, the scheduling jobs can be either 
0093:         * batch or incremental.  Batch starts from scratch every time, but 
0094:         * incremental mode maintains scheduler state from previous batches.
0095:         *
0096:         * Further, XML translation can either be automatic or custom.  Automatic
0097:         * mode uses introspection to determine the object format of the problem,
0098:         * whereas custom forces the developer to define it and participate in 
0099:         * the translation process.
0100:         *
0101:         * Abstract because it does not define :
0102:         *  - createThreadCallback
0103:         * each of which is defined in the allocator, aggregator, and expander 
0104:         * subclasses.
0105:         *
0106:         * </pre>
0107:         *
0108:         * @see org.cougaar.lib.filter.UTILBufferingPluginAdapter#createThreadCallback
0109:         * @see org.cougaar.lib.vishnu.client.VishnuAggregatorPlugin#createThreadCallback
0110:         * @see org.cougaar.lib.vishnu.client.VishnuAllocatorPlugin#createThreadCallback
0111:         * @see org.cougaar.lib.vishnu.client.VishnuExpanderPlugin#createThreadCallback
0112:         *
0113:         * <!--
0114:         * (When printed, any longer line will wrap...)
0115:         *345678901234567890123456789012345678901234567890123456789012345678901234567890
0116:         *       1         2         3         4         5         6         7         8
0117:         * -->
0118:         */
0119:        public abstract class VishnuPlugin extends UTILBufferingPluginAdapter
0120:                implements  UTILAssetListener, DirectModeListener,
0121:                ResultListener {
0122:
0123:            /**
0124:             * Here all the various runtime parameters get set.  See documentation for details.
0125:             */
0126:            public void localSetup() {
0127:                super .localSetup();
0128:
0129:                String hostName = "";
0130:
0131:                try {
0132:                    if (getMyParams().hasParam("hostName"))
0133:                        hostName = getMyParams().getStringParam("hostName");
0134:                    else
0135:                        hostName = "dante.bbn.com";
0136:
0137:                    if (getMyParams().hasParam("runInternal"))
0138:                        runInternal = getMyParams().getBooleanParam(
0139:                                "runInternal");
0140:                    else
0141:                        runInternal = false;
0142:
0143:                    if (getMyParams().hasParam("runDirectly"))
0144:                        runDirectly = getMyParams().getBooleanParam(
0145:                                "runDirectly");
0146:                    else
0147:                        runDirectly = false;
0148:
0149:                    if (!runInternal)
0150:                        runDirectly = false; // can't run directly if not running internally
0151:
0152:                    if (getMyParams().hasParam("incrementalScheduling"))
0153:                        incrementalScheduling = getMyParams().getBooleanParam(
0154:                                "incrementalScheduling");
0155:                    else
0156:                        incrementalScheduling = false;
0157:
0158:                    if (getMyParams().hasParam("showTiming"))
0159:                        showTiming = getMyParams()
0160:                                .getBooleanParam("showTiming");
0161:                    else
0162:                        showTiming = true;
0163:
0164:                    if (getMyParams().hasParam("makeSetupAndWrapupTasks"))
0165:                        makeSetupAndWrapupTasks = getMyParams()
0166:                                .getBooleanParam("makeSetupAndWrapupTasks");
0167:                    else
0168:                        makeSetupAndWrapupTasks = true;
0169:
0170:                    if (getMyParams().hasParam("useStoredFormat"))
0171:                        useStoredFormat = getMyParams().getBooleanParam(
0172:                                "useStoredFormat");
0173:                    else
0174:                        useStoredFormat = false;
0175:
0176:                    if (getMyParams().hasParam("stopOnFailure"))
0177:                        stopOnFailure = getMyParams().getBooleanParam(
0178:                                "stopOnFailure");
0179:                    else
0180:                        stopOnFailure = false;
0181:
0182:                    // how many of the input tasks to use as templates when producing the 
0183:                    // OBJECT FORMAT for tasks
0184:                    if (getMyParams().hasParam("firstTemplateTasks"))
0185:                        firstTemplateTasks = getMyParams().getIntParam(
0186:                                "firstTemplateTasks");
0187:                    else
0188:                        firstTemplateTasks = 2;
0189:
0190:                    if (getMyParams().hasParam(
0191:                            "wantMediumConfidenceOnExpansion"))
0192:                        wantMediumConfidenceOnExpansion = getMyParams()
0193:                                .getBooleanParam(
0194:                                        "wantMediumConfidenceOnExpansion");
0195:                    else
0196:                        wantMediumConfidenceOnExpansion = false;
0197:                } catch (Exception e) {
0198:                }
0199:
0200:                domUtil = createVishnuDomUtil();
0201:                comm = createVishnuComm();
0202:                xmlProcessor = createXMLProcessor();
0203:                config = createVishnuConfig();
0204:
0205:                localDidRehydrate = blackboard.didRehydrate();
0206:
0207:                // helpful for debugging connection configuration problems
0208:                if (runInternal) {
0209:                    if (runDirectly) {
0210:                        info(getName()
0211:                                + " - will run direct translation internal Vishnu Scheduler.");
0212:                        resultHandler = createDirectResultHandler();
0213:                        mode = createDirectMode();
0214:                    } else {
0215:                        info(getName()
0216:                                + " - will run internal Vishnu Scheduler.");
0217:                        resultHandler = createXMLResultHandler();
0218:                        mode = createInternalMode();
0219:                    }
0220:                    if (incrementalScheduling)
0221:                        info(" - incrementally - ");
0222:                } else {
0223:                    info(getName()
0224:                            + " - will try to connect to Vishnu Web Server : "
0225:                            + hostName + ".");
0226:                    resultHandler = createXMLResultHandler();
0227:                    mode = createExternalMode();
0228:                }
0229:                if (useStoredFormat)
0230:                    info(" Will send stored object format.");
0231:            }
0232:
0233:            protected VishnuDomUtil createVishnuDomUtil() {
0234:                return new VishnuDomUtil(getMyParams(), getName(),
0235:                        getConfigFinder(), logger);
0236:            }
0237:
0238:            protected VishnuComm createVishnuComm() {
0239:                return new VishnuComm(getMyParams(), getName(),
0240:                        getClusterName(), domUtil, runInternal, logger);
0241:            }
0242:
0243:            protected XMLProcessor createXMLProcessor() {
0244:                if (isDebugEnabled())
0245:                    debug(getName()
0246:                            + ".createXMLProcessor - creating vanilla xml processor.");
0247:                return new XMLProcessor(getMyParams(), getName(),
0248:                        getClusterName(), domUtil, comm, getConfigFinder(),
0249:                        logger, logger, logger); // later perhaps divide logger name space
0250:            }
0251:
0252:            public XMLizer getDataXMLizer() {
0253:                return xmlProcessor.getDataXMLizer();
0254:            }
0255:
0256:            protected VishnuConfig createVishnuConfig() {
0257:                String clusterName = myClusterName;
0258:                if (didSpawn())
0259:                    clusterName = getOriginalAgentID().getAddress();
0260:
0261:                return new VishnuConfig(getMyParams(), getName(), clusterName,
0262:                        logger);
0263:            }
0264:
0265:            protected SchedulerLifecycle createExternalMode() {
0266:                return new ExternalMode(this , comm, xmlProcessor, domUtil,
0267:                        config, resultHandler, getMyParams(), logger);
0268:            }
0269:
0270:            protected SchedulerLifecycle createInternalMode() {
0271:                InternalMode mode = new InternalMode(this , comm, xmlProcessor,
0272:                        domUtil, config, resultHandler, getMyParams(), logger);
0273:
0274:                return mode;
0275:            }
0276:
0277:            protected SchedulerLifecycle createDirectMode() {
0278:                DirectMode mode = new DirectMode(this , comm, xmlProcessor,
0279:                        domUtil, config, resultHandler, getMyParams(), logger);
0280:
0281:                return mode;
0282:            }
0283:
0284:            protected XMLResultHandler createXMLResultHandler() {
0285:                return new XMLResultHandler(this , comm, xmlProcessor, domUtil,
0286:                        config, getMyParams(), logger);
0287:            }
0288:
0289:            protected DirectResultHandler createDirectResultHandler() {
0290:                return new DirectResultHandler(this , comm, xmlProcessor,
0291:                        domUtil, config, getMyParams(), logger);
0292:            }
0293:
0294:            /** anything you added with register, you will be informed about here upon rehydration */
0295:            /*
0296:              protected void rehydrateState (List stuff) {
0297:              if (isInfoEnabled() || true)
0298:              debug (getName () + ".rehydrateState - stuff has " + stuff.size () + " members.");
0299:            
0300:              myTaskUIDtoObject  = (Map) stuff.get (0);
0301:              myAssetUIDtoObject = (Map) stuff.get (0);
0302:
0303:              if (stuff.size () > 0) {
0304:              ((InternalMode)mode).setScheduler ((Scheduler) stuff.get(0));
0305:              if (isInfoEnabled() || true)
0306:              debug (getName () + ".rehydrateState - set Scheduler on mode.");
0307:              }
0308:            
0309:              if (isInfoEnabled() || true)
0310:              debug (getName () + ".rehydrateState - myTaskUIDToObject is now " + myTaskUIDtoObject);
0311:              if (isInfoEnabled() || true)
0312:              debug (getName () + ".rehydrateState - myAssetUIDToObject is now " + myAssetUIDtoObject);
0313:              }
0314:             */
0315:
0316:            public boolean getRunDirectly() {
0317:                return runDirectly;
0318:            }
0319:
0320:            /****************************************************************
0321:             ** Setup Filters...
0322:             **/
0323:
0324:            /** filter for assets */
0325:            public void setupFilters() {
0326:                super .setupFilters();
0327:
0328:                if (isInfoEnabled())
0329:                    debug(getName() + " : Filtering for generic Assets...");
0330:
0331:                addFilter(myAssetCallback = createAssetCallback());
0332:            }
0333:
0334:            /**
0335:             * Is the task interesting to the plugin?  This is the inner-most part of 
0336:             * the predicate.                                                         <br>
0337:             * By default, it ignores tasks produced from this plugin                 <br>                    
0338:             * If you redefine this, it's good to call this using super.
0339:             *
0340:             * @param t - the task begin checked
0341:             * @see org.cougaar.lib.callback.UTILGenericListener#interestingTask
0342:             */
0343:            public boolean interestingTask(Task t) {
0344:                PrepositionalPhrase pp = prepHelper.getPrepNamed(t, "VISHNU");
0345:                if (pp != null
0346:                        && ((String) pp.getIndirectObject())
0347:                                .equals(getClassName(this )))
0348:                    return false;
0349:                return true;
0350:            }
0351:
0352:            /**
0353:             * Implemented for UTILTaskChecker interface.
0354:             * <p>
0355:             * DEFAULT : Don't do anything with ill-formed tasks.
0356:             *
0357:             * @see org.cougaar.lib.filter.UTILTaskChecker#handleIllFormedTask
0358:             */
0359:            public void handleIllFormedTask(Task t) {
0360:            }
0361:
0362:            /** @return UTILAssetCallback that was previously created and has this plugin as a listener */
0363:            protected UTILAssetCallback getAssetCallback() {
0364:                return myAssetCallback;
0365:            }
0366:
0367:            /**
0368:             * Create the standard Asset callback
0369:             *
0370:             * @return UTILAssetCallback that was created and has this plugin as a listener
0371:             */
0372:            protected UTILAssetCallback createAssetCallback() {
0373:                return new UTILAssetCallback(this , logger);
0374:            }
0375:
0376:            /**
0377:             * Implemented for UTILAssetListener
0378:             * <p>
0379:             * OVERRIDE to see which assets you think are interesting.
0380:             * <p>
0381:             * For instance, if you are scheduling trucks/ships/planes, 
0382:             * you'd want to check like this : 
0383:             * <code>
0384:             * return (GLMAsset).hasContainPG ();
0385:             * </code>
0386:             * @param a asset to check 
0387:             * @return boolean true if asset is interesting
0388:             */
0389:            public boolean interestingAsset(Asset a) {
0390:                return true;
0391:            }
0392:
0393:            /**
0394:             * Collect new assets into a set to eventually give to scheduler (after translation).
0395:             * @param newAssets new assets found in the container
0396:             */
0397:            public void handleNewAssets(Enumeration newAssets) {
0398:                for (; newAssets.hasMoreElements();) {
0399:                    Object asset = newAssets.nextElement();
0400:                    myNewAssets.add(asset);
0401:                }
0402:                if (isInfoEnabled())
0403:                    info(getName() + ".handleNewAssets - got "
0404:                            + myNewAssets.size());
0405:            }
0406:
0407:            /**
0408:             * Place to handle changed assets.
0409:             *
0410:             * Does nothing by default - reports changed assets when isInfoEnabled() set.
0411:             *
0412:             * @param changedAssets changed assets found in the container
0413:             */
0414:            public void handleChangedAssets(Enumeration changedAssets) {
0415:                for (; changedAssets.hasMoreElements();) {
0416:                    Object asset = changedAssets.nextElement();
0417:                    myChangedAssets.add(asset);
0418:                }
0419:                if (isInfoEnabled())
0420:                    info(getName() + ".handleChangedAssets - got "
0421:                            + myChangedAssets.size() + " changed assets.");
0422:            }
0423:
0424:            /**
0425:             * Implemented for ModeListener interface 
0426:             * <p>
0427:             * Which assets were changed since they were added as new assets?
0428:             * @return myChangedAssets set of assets on the changed list
0429:             */
0430:            public Collection getChangedAssets() {
0431:                return myChangedAssets;
0432:            }
0433:
0434:            /**
0435:             * Implemented for ModeListener interface 
0436:             * <p>
0437:             * After the scheduler is informed of the changed assets, forget about them.
0438:             */
0439:            public void clearChangedAssets() {
0440:                myChangedAssets.clear();
0441:            }
0442:
0443:            /**
0444:             * Place to handle rescinded tasks. <p>
0445:             *
0446:             * Sends XML to unfreeze the task assignment and delete it.  Asks the mode to do this.
0447:             *
0448:             * @param removedTasks changed assets found in the container
0449:             * @see org.cougaar.lib.vishnu.client.SchedulerLifecycle#handleRemovedTasks
0450:             */
0451:            protected void handleRemovedTasks(Enumeration removedTasks) {
0452:                if (incrementalScheduling) {
0453:                    mode.setupScheduler(); // needed for rescinds after rehydration
0454:
0455:                    if (useStoredFormat)
0456:                        initializeWithStoredFormat();// needed for rescinds after rehydration
0457:
0458:                    mode.handleRemovedTasks(removedTasks);
0459:                }
0460:            }
0461:
0462:            protected void unfreezeTasks(Collection tasks) {
0463:                if (incrementalScheduling) {
0464:                    mode.setupScheduler(); // needed for rescinds after rehydration
0465:
0466:                    if (useStoredFormat)
0467:                        initializeWithStoredFormat();// needed for rescinds after rehydration
0468:
0469:                    mode.unfreezeTasks(tasks);
0470:                }
0471:            }
0472:
0473:            /**
0474:             * <pre>
0475:             * Heart of the plugin.
0476:             *
0477:             * Deal with the tasks that we have accumulated.
0478:             *
0479:             * Does: 
0480:             * 1) Sets up the scheduler
0481:             * 2) Sends the problem's object format, if it hasn't already been sent.
0482:             *    - generated introspectively or from a file
0483:             *    - will keep sending the object format if running in batch mode
0484:             * 3) Prepares and sends the data (obtained from tasks and assets)
0485:             *    - ask the mode to translate the tasks and assets
0486:             * 4) Waits for a result (all in the mode)
0487:             *    - start the scheduler
0488:             *    - wait for a result
0489:             *    - call handleAssignment on each returned assignment
0490:             *    - deal with un-assigned tasks
0491:             *    - clear tasks, ready to start on a new batch
0492:             *
0493:             * </pre>
0494:             *
0495:             * @param tasks the tasks to handle
0496:             */
0497:            public void processTasks(List tasks) {
0498:                total += tasks.size();
0499:                if (isDebugEnabled())
0500:                    debug(getName() + ".processTasks - received "
0501:                            + tasks.size() + " tasks, " + total
0502:                            + " total so far.");
0503:
0504:                Date start = new Date();
0505:
0506:                mode.setupScheduler();
0507:
0508:                if (useStoredFormat) {
0509:                    // only generate format the document once
0510:                    initializeWithStoredFormat();
0511:                } else {
0512:                    if (!sentFormatAlready)
0513:                        prepareObjectFormat(tasks);
0514:                }
0515:
0516:                // send again if in batch mode
0517:                sentFormatAlready = incrementalScheduling;
0518:
0519:                // remember these tasks come assignment-time
0520:                setUIDToObjectMap(tasks, myTaskUIDtoObject);
0521:
0522:                if (isDebugEnabled())
0523:                    debug(getName() + ".processTasks - sending "
0524:                            + myTaskUIDtoObject.values().size() + " tasks.");
0525:
0526:                int numTasks = getNumTasks();
0527:                Date dataStart = new Date();
0528:
0529:                // translate
0530:                prepareData(tasks, objectFormatDoc);
0531:
0532:                if (showTiming) {
0533:                    domUtil.reportTime(
0534:                            " - Vishnu completed data XML processing in ",
0535:                            dataStart);
0536:                    domUtil.reportTime(
0537:                            " - Vishnu completed XML processing in ", start);
0538:                }
0539:
0540:                // run, get answer, make plan elements
0541:                waitForAnswer();
0542:
0543:                if (showTiming)
0544:                    domUtil.reportTime(" - Vishnu did " + numTasks
0545:                            + " tasks in ", start);
0546:            }
0547:
0548:            /**
0549:             * little helper method called by processTasks, if using a stored object format  <p>
0550:             *
0551:             * Reads object format if hasn't been yet.  Sends format if it hasn't been sent yet.
0552:             *
0553:             */
0554:            protected void initializeWithStoredFormat() {
0555:                // only generate format the document once
0556:                if (objectFormatDoc == null)
0557:                    objectFormatDoc = prepareStoredObjectFormat();
0558:                if (!sentFormatAlready) {
0559:                    comm.serializeAndPostProblem(objectFormatDoc);
0560:                    mode.initializeWithFormat();
0561:                }
0562:            }
0563:
0564:            /**
0565:             * Automatically generate object format from Cougaar input tasks (and assets). 
0566:             * <p>
0567:             * Calls VishnuConfig to get representative sample of input tasks and assets to
0568:             * use as the base for automatic translation.  Also gets the class name of the
0569:             * resource asset.
0570:             * <p>
0571:             * Sends the object format and creates a data xmlizer, if needed.
0572:             *
0573:             * @param tasks - tasks to examine
0574:             */
0575:            protected void prepareObjectFormat(List tasks) {
0576:                Date start = new Date();
0577:
0578:                // The problem format, as opposed to the data, is not cleared on the <CLEARDATABASE>
0579:                // call.  Hence, there is no need to resend the format even when not doing incremental
0580:                // scheduling.  The only time the problem format needs to be resent is when running
0581:                // internally.  
0582:                if (isInfoEnabled())
0583:                    info(getName()
0584:                            + ".prepareObjectFormat - discovering object format introspectively.");
0585:
0586:                List assetClassName = new ArrayList(); // just a way of returning a second return value from function
0587:                Collection formatTemplates = config.getAssetTemplatesForTasks(
0588:                        tasks, assetClassName, getAllAssets());
0589:                String singleAssetClassName = (String) assetClassName.get(0);
0590:
0591:                formatTemplates.addAll(config.getTemplateTasks(tasks,
0592:                        firstTemplateTasks));
0593:
0594:                if (isDebugEnabled()) {
0595:                    debug(getName() + ".processObjectFormat - "
0596:                            + formatTemplates.size() + " unique assets : ");
0597:                    for (Iterator iter = formatTemplates.iterator(); iter
0598:                            .hasNext();)
0599:                        System.out.print("\t" + iter.next().getClass());
0600:                    debug("");
0601:                }
0602:
0603:                Map myNameToDescrip = sendFormat(formatTemplates,
0604:                        singleAssetClassName);
0605:                ((ExternalMode) mode).setNameToDescrip(myNameToDescrip);
0606:                ((ExternalMode) mode)
0607:                        .setSingleAssetClassName(singleAssetClassName);
0608:
0609:                // only create data xmlizer once -- remembers references to globals throughout its lifetime
0610:                xmlProcessor.createDataXMLizer(myNameToDescrip,
0611:                        singleAssetClassName);
0612:
0613:                if (showTiming)
0614:                    domUtil.reportTime(
0615:                            " - Vishnu completed format XML processing in ",
0616:                            start);
0617:            }
0618:
0619:            /**
0620:             * Like VishnuPlugin.prepareObjectFormat                           <p>
0621:             *
0622:             * Send the file called <Cluster>.dff.xml as the default object format 
0623:             * for the problem.                                                     <br>
0624:             * Does NOT discover the object format from sampling the tasks.         <p>
0625:             *
0626:             * This file can also be indicated by setting the parameter <code>defaultFormat</code>.
0627:             *
0628:             **/
0629:            protected Document prepareStoredObjectFormat() {
0630:                Date start = new Date();
0631:
0632:                Document formatDoc = null;
0633:
0634:                try {
0635:                    xmlProcessor.createDataXMLizer(null, null);
0636:
0637:                    String defaultFormat = config.getFormatFile();
0638:
0639:                    if (isDebugEnabled())
0640:                        debug(getName()
0641:                                + ".prepareStoredObjectFormat - sending format file "
0642:                                + defaultFormat);
0643:
0644:                    DOMParser parser = new DOMParser();
0645:                    InputStream inputStream = getConfigFinder().open(
0646:                            defaultFormat);
0647:                    parser.parse(new InputSource(inputStream));
0648:                    formatDoc = parser.getDocument();
0649:                    Element formatDocRoot = formatDoc.getDocumentElement();
0650:                    formatDocRoot.setAttribute("name", comm.getProblem());
0651:
0652:                    if (isInfoEnabled()) {
0653:                        info(getName()
0654:                                + ".prepareStoredObjectFormat - problem name is "
0655:                                + comm.getProblem());
0656:                    }
0657:
0658:                    attachAssociatedFiles(formatDoc); // attach vsh.xml, ga.xml, odf.xml files
0659:
0660:                    if (showTiming)
0661:                        domUtil
0662:                                .reportTime(
0663:                                        " - Vishnu completed format XML processing in ",
0664:                                        start);
0665:                } catch (Exception e) {
0666:                    e.printStackTrace();
0667:                    debug(getName()
0668:                            + ".prepareStoredObjectFormat - ERROR with file "
0669:                            + e.getMessage() + " exception was " + e);
0670:                }
0671:
0672:                return formatDoc;
0673:            }
0674:
0675:            /**
0676:             * Tasks a list of tasks and the object format document and sends the data 
0677:             * to the scheduler.  If incremental scheduling, appends assets to the 
0678:             * list of data if they haven't been sent before.  Otherwise if not 
0679:             * in incremental mode, always sends assets.<p>
0680:             *
0681:             * @see org.cougaar.lib.vishnu.client.ExternalMode#prepareData
0682:             * @see #prepareVishnuObjects
0683:             * @see org.cougaar.lib.vishnu.client.ExternalMode#sendDataToVishnu
0684:             * @param stuffToSend - initially the list of tasks to send to scheduler
0685:             * @param objectFormatDoc - optional object format used by data xmlizers
0686:             *  to determine types for fields when running directly
0687:             */
0688:            protected void prepareData(List stuffToSend,
0689:                    Document objectFormatDoc) {
0690:                Collection allAssets = getAllAssets();
0691:                if (isDebugEnabled())
0692:                    debug(getName() + ".prepareData - sending "
0693:                            + allAssets.size() + " assets.");
0694:
0695:                stuffToSend.addAll(allAssets);
0696:
0697:                setUIDToObjectMap(allAssets, myAssetUIDtoObject);
0698:
0699:                if (logger.isDebugEnabled()) {
0700:                    for (Iterator iter = stuffToSend.iterator(); iter.hasNext();) {
0701:                        Object obj = iter.next();
0702:
0703:                        debug(getName() + ".prepareData sending stuff "
0704:                                + ((UniqueObject) obj).getUID());
0705:                    }
0706:                }
0707:
0708:                // Send problem data to vishnu
0709:                mode.prepareData(stuffToSend, objectFormatDoc);
0710:            }
0711:
0712:            /**
0713:             * Ask the mode to run, which includes handling the assignments.  <p>
0714:             * Deal with un-scheduled tasks, and then forget about them.
0715:             * Any tasks not handled = any which are left in the
0716:             * <code>myTaskUIDtoObject</code> map get sent to <code>handleImpossibleTasks</code>.
0717:             * @see SchedulerLifecycle#run
0718:             * @see ExternalMode#run
0719:             * @see InternalMode#run
0720:             * @see DirectMode#run
0721:             * @see #getTasks
0722:             * @see #handleImpossibleTasks
0723:             * @see #clearTasks
0724:             */
0725:            protected void waitForAnswer() {
0726:                mode.run();
0727:
0728:                handleImpossibleTasks(getTasks());
0729:                clearTasks();
0730:            }
0731:
0732:            /**
0733:             * Utility for setting up UID to object map.  Uses StringKeys for speed.
0734:             *
0735:             * @param objects     to add to map 
0736:             * @param UIDtoObject map to populate
0737:             */
0738:            protected void setUIDToObjectMap(Collection objects, Map UIDtoObject) {
0739:                for (Iterator iter = objects.iterator(); iter.hasNext();) {
0740:                    UniqueObject obj = (UniqueObject) iter.next();
0741:                    StringKey key = new StringKey(obj.getUID().toString());
0742:                    if (!UIDtoObject.containsKey(key)) {
0743:                        UIDtoObject.put(key, obj);
0744:                        // debug("setUIDToObjectMap: added " + key + " = " + obj + " to map");
0745:                    }
0746:                }
0747:            }
0748:
0749:            /**
0750:             * If you're not in incremental mode, send all assets. <br>
0751:             * Otherwise, only send those that have come in on the subscription add list.
0752:             *
0753:             * @return Collection of assets to send to Vishnu
0754:             */
0755:            protected Collection getAllAssets() {
0756:                if (!incrementalScheduling)
0757:                    return getAssetCallback().getSubscription().getCollection();
0758:
0759:                if (blackboard.didRehydrate() || localDidRehydrate) {
0760:                    localDidRehydrate = false;
0761:
0762:                    if (isDebugEnabled())
0763:                        debug(getName()
0764:                                + ".getAllAssets - getting all assets because of rehydration.");
0765:
0766:                    return getAssetCallback().getSubscription().getCollection();
0767:                } else {
0768:                    if (isDebugEnabled())
0769:                        debug(getName()
0770:                                + ".getAllAssets - normal mode -- NOT rehydrating.");
0771:                }
0772:
0773:                Set newAssetsCopy = new HashSet(myNewAssets);
0774:                myNewAssets.clear();
0775:                return newAssetsCopy;
0776:            }
0777:
0778:            /**
0779:             * Send the dataformat section of the problem to the postdata
0780:             * URL.
0781:             *
0782:             * This will define the structure of input tasks and resources,
0783:             * as well as the scheduling specs and the ga parameters.
0784:             *
0785:             * Each of the items in the template collection will be translated
0786:             * into an xml OBJECTFORMAT tag.
0787:             *
0788:             * Attaches associated files.
0789:             *
0790:             * </pre>
0791:             * @param templates -- a collection of all the template resources 
0792:             *                     and a template task.
0793:             * @param assetClassName - used to figure out which asset is to be the Vishnu resource
0794:             * @return map of the object types to their object descriptions
0795:             */
0796:            protected Map sendFormat(Collection templates, String assetClassName) {
0797:                if (isDebugEnabled())
0798:                    debug(getName() + ".sendFormat, resource " + assetClassName);
0799:                Map nameInfo = null;
0800:                Date start = new Date();
0801:
0802:                List returnedMap = new ArrayList();
0803:
0804:                Document problemFormatDoc = xmlProcessor
0805:                        .getFormatDocWithoutDuplicates(templates,
0806:                                assetClassName, returnedMap);
0807:                nameInfo = (Map) returnedMap.get(0);
0808:
0809:                if (showTiming)
0810:                    domUtil.reportTime(
0811:                            " - Vishnu completed format XML transform in ",
0812:                            start);
0813:
0814:                attachAssociatedFiles(problemFormatDoc);
0815:
0816:                // send to postdata URL
0817:                comm.serializeAndPostProblem(problemFormatDoc);
0818:                mode.initializeWithFormat();
0819:
0820:                return nameInfo;
0821:            }
0822:
0823:            /**
0824:             * Attaches various files to format document. <p>
0825:             *
0826:             * - attach global object format file         <br>
0827:             * - attach specs file                        <br>
0828:             * - attach ga parameters file                <br>
0829:             * @param problemFormatDoc - document to add to 
0830:             **/
0831:            protected void attachAssociatedFiles(Document problemFormatDoc) {
0832:                // append any global other data object formats 
0833:                appendGlobalDataFormat(problemFormatDoc);
0834:
0835:                // append the scheduling specs
0836:                String specsFile = config.getSpecsFile();
0837:
0838:                if (isDebugEnabled())
0839:                    debug(getName() + ".sendFormat - appending " + specsFile
0840:                            + " vishnu specs xml file");
0841:
0842:                domUtil.appendDoc(problemFormatDoc, specsFile);
0843:
0844:                // append the ga specs
0845:                specsFile = config.getGASpecsFile();
0846:
0847:                if (isDebugEnabled())
0848:                    debug(getName() + ".sendFormat - appending " + specsFile
0849:                            + " vishnu ga specs xml file");
0850:
0851:                domUtil.appendDoc(problemFormatDoc, specsFile);
0852:            }
0853:
0854:            /**
0855:             * Talks to VishnuConfig to find out if there is an other data format file. <br>
0856:             * If there is, appends it to problem format doc.  Adds it beneath DATAFORMAT tag.
0857:             * @param problemFormatDoc document to add other data format to
0858:             */
0859:            protected void appendGlobalDataFormat(Document problemFormatDoc) {
0860:                String otherDataFormat = config.getOtherDataFormat();
0861:                try {
0862:                    if (getConfigFinder().open(otherDataFormat) != null) {
0863:                        if (isDebugEnabled())
0864:                            debug(getName() + ".sendFormat -  appending "
0865:                                    + otherDataFormat
0866:                                    + " other data format file");
0867:
0868:                        Element dataFormatNode = (Element) problemFormatDoc
0869:                                .getElementsByTagName("DATAFORMAT").item(0);
0870:
0871:                        domUtil.appendDoc(problemFormatDoc, dataFormatNode,
0872:                                otherDataFormat);
0873:                    }
0874:                } catch (FileNotFoundException fnf) {
0875:                    if (isInfoEnabled())
0876:                        info(getName()
0877:                                + ".appendGlobalDataFormat - could not find optional file : "
0878:                                + otherDataFormat);
0879:                } catch (Exception ioe) {
0880:                    logger.error(getName()
0881:                            + ".appendGlobalDataFormat - Exception "
0882:                            + ioe.getMessage(), ioe);
0883:                }
0884:            }
0885:
0886:            /**
0887:             * Creates lists of Vishnu objects.
0888:             * <p>
0889:             * Complains that you need to define this method by default.
0890:             * <p>
0891:             * Implemented for DirectResultListener interface.
0892:             *
0893:             * @param tasksAndResources - Cougaar tasks and resources to translate
0894:             * @param changedAssets - list of changed Cougaar assets
0895:             * @param vishnuTasks - list to add Vishnu tasks to 
0896:             * @param vishnuResources - list to add Vishnu resources to 
0897:             * @param changedVishnuResources - list of changed Vishnu resources
0898:             */
0899:            public void prepareVishnuObjects(List tasksAndResources,
0900:                    Collection changedAssets, List vishnuTasks,
0901:                    List vishnuResources, List changedVishnuResources,
0902:                    Document objectFormat, SchedulingData schedData) {
0903:                error(getName()
0904:                        + ".prepareVishnuObjects - ERROR - don't run directly if you haven't defined this method.");
0905:            }
0906:
0907:            /** implemented for ModeListener interface */
0908:            public int getNumTasks() {
0909:                return myTaskUIDtoObject.size();
0910:            }
0911:
0912:            /** called by waitForAnswer -- we don't have to remember taskUID-to-object mappings after answer is returned */
0913:            protected void clearTasks() {
0914:                myTaskUIDtoObject.clear();
0915:            }
0916:
0917:            /**
0918:             * Used when XML assignment information is returned to find matching resource asset <p>
0919:             *
0920:             * implemented for ResultListener interface 
0921:             */
0922:            public Task getTaskForKey(StringKey key) {
0923:                Task task = (Task) myTaskUIDtoObject.get(key);
0924:                return task;
0925:            }
0926:
0927:            /** implemented for ResultListener interface */
0928:            public void removeTask(StringKey key) {
0929:                myTaskUIDtoObject.remove(key);
0930:            }
0931:
0932:            /** implemented for ModeListener interface */
0933:            public Collection getTasks() {
0934:                return myTaskUIDtoObject.values();
0935:            }
0936:
0937:            /** implemented for ModeListener interface */
0938:            public int getNumAssets() {
0939:                return myAssetUIDtoObject.size();
0940:            }
0941:
0942:            /** implemented for ModeListener interface */
0943:            public String getTaskName() {
0944:                return "Transport";
0945:            }
0946:
0947:            /**
0948:             * Used when XML assignment information is returned to find matching resource asset <p>
0949:             *
0950:             * implemented for ResultListener interface 
0951:             */
0952:            public Asset getAssetForKey(StringKey key) {
0953:                Asset asset = (Asset) myAssetUIDtoObject.get(key);
0954:
0955:                return asset;
0956:            }
0957:
0958:            /*
0959:              protected UniqueObject findUniqueObject (final StringKey uid) {
0960:              Thread.dumpStack ();
0961:            
0962:              Collection stuff = blackboard.query (new UnaryPredicate () {
0963:              public boolean execute (Object obj) {
0964:              boolean isUnique = (obj instanceof UniqueObject);
0965:              if (!isUnique) return false;
0966:
0967:              boolean match = ((UniqueObject) obj).getUID ().toString().equals (uid.toString());
0968:
0969:              debug (getName () + ".findUniqueObject - Comparing uid " +
0970:              ((UniqueObject) obj).getUID ().toString() + " with key " + uid + 
0971:              ((match) ? " MATCH! " : " no match"));
0972:
0973:              return match;
0974:              }
0975:              });
0976:
0977:              if (stuff.isEmpty ())
0978:              return null;
0979:              else
0980:              return (UniqueObject) stuff.iterator().next();
0981:              }
0982:             */
0983:
0984:            /**
0985:             * Given a collection of impossible tasks, make failed disposition for each. 
0986:             * <p>
0987:             * If <code>stopOnFailure</code> is true, exits.
0988:             * @param impossibleTasks -- tasks that the scheduler couldn't figure out 
0989:             *                           what to do with
0990:             */
0991:            protected void handleImpossibleTasks(Collection impossibleTasks) {
0992:                if (!impossibleTasks.isEmpty())
0993:                    debug(getName() + ".handleImpossibleTasks - failing "
0994:                            + impossibleTasks.size() + " tasks.");
0995:
0996:                for (Iterator iter = impossibleTasks.iterator(); iter.hasNext();) {
0997:                    Object obj = allocHelper.makeFailedDisposition(this , ldmf,
0998:                            (Task) iter.next());
0999:                    publishAddWithCheck(obj);
1000:                }
1001:
1002:                if (stopOnFailure && !impossibleTasks.isEmpty()) {
1003:                    debug(getName()
1004:                            + ".handleImpossibleTasks - stopping on failure!");
1005:                    System.exit(-1);
1006:                }
1007:            }
1008:
1009:            /**
1010:             * <pre>
1011:             * Should define in subclass -- create an allocation 
1012:             *
1013:             * The parameters are what got returned from the vishnu scheduler.
1014:             *
1015:             * implemented for ResultListener interface 
1016:             * </pre>
1017:             * @see VishnuAllocatorPlugin#handleAssignment
1018:             * @param task  task that was assigned to asset
1019:             * @param asset asset handling task
1020:             * @param start of main task
1021:             * @param end   of main task
1022:             * @param setupStart start of setup task
1023:             * @param wrapupEnd end of wrapup task
1024:             */
1025:            public void handleAssignment(
1026:                    org.cougaar.planning.ldm.plan.Task task, Asset asset,
1027:                    Date start, Date end, Date setupStart, Date wrapupEnd,
1028:                    String contribs, String taskText) {
1029:                logger
1030:                        .warn("somehow calling this function? - nothing will happen.");
1031:            }
1032:
1033:            /**
1034:             * <pre>
1035:             * Should define in subclass -- create an aggregation
1036:             *
1037:             * The parameters are what got returned from the vishnu scheduler.
1038:             *
1039:             * implemented for ResultListener interface 
1040:             * </pre>
1041:             * @see VishnuAggregatorPlugin#handleMultiAssignment
1042:             * @param tasks  tasks to be aggregated together and assigned to asset
1043:             * @param asset asset handling task
1044:             * @param start of main task
1045:             * @param end   of main task
1046:             * @param setupStart start of setup task
1047:             * @param wrapupEnd end of wrapup task
1048:             */
1049:            public void handleMultiAssignment(Vector tasks, Asset asset,
1050:                    Date start, Date end, Date setupStart, Date wrapupEnd,
1051:                    boolean assetWasUsedBefore) {
1052:            }
1053:
1054:            /**
1055:             * Must use a special allocation result aggregator that does NOT include the transit (setup, wrapup) tasks
1056:             * in it's time calculations.
1057:             */
1058:            protected AllocationResultAggregator skipTransitARA = new VishnuAllocationResultAggregator();
1059:
1060:            /**
1061:             * Make expansion of mptask that attached between one and three subtasks <p>
1062:             *
1063:             * May attach setup and wrapup tasks, if there are specs defined for them and <br>
1064:             * if the <code>makeSetupAndWrapupTasks</code> boolean parameter is set. <p>
1065:             *
1066:             * The parameters are what got returned from the vishnu scheduler.
1067:             * @param task  task that was assigned to asset
1068:             * @param asset asset handling task
1069:             * @param start of main task
1070:             * @param end   of main task
1071:             * @param setupStart start of setup task
1072:             * @param wrapupEnd end of wrapup task
1073:             * @return List of subtasks created
1074:             */
1075:            protected List makeSetupWrapupExpansion(Task task, Asset asset,
1076:                    Date start, Date end, Date setupStart, Date wrapupEnd) {
1077:                if (isDebugEnabled())
1078:                    debug(getName() + ".makeSetupWrapupExpansion : "
1079:                            + " assigning " + task.getUID() + "\nto "
1080:                            + asset.getUID() + " from " + start + " to " + end);
1081:
1082:                if (setupStart.after(start))
1083:                    error(getName()
1084:                            + ".makeSetupWrapupExpansion : ERROR, assigned setupStart - "
1085:                            + setupStart + " after start " + start
1086:                            + " for task " + task);
1087:                if (start.after(end))
1088:                    error(getName()
1089:                            + ".makeSetupWrapupExpansion : ERROR, assigned start - "
1090:                            + start + " after end " + end + " for task " + task);
1091:                if (end.after(wrapupEnd))
1092:                    error(getName()
1093:                            + ".makeSetupWrapupExpansion : ERROR, assigned end - "
1094:                            + end + " after wrapupEnd " + wrapupEnd
1095:                            + " for task " + task);
1096:
1097:                Vector subtasks = new Vector();
1098:
1099:                subtasks.add(createMainTask(task, asset, start, end,
1100:                        setupStart, wrapupEnd));
1101:
1102:                if (makeSetupAndWrapupTasks) {
1103:                    if (setupStart.getTime() < start.getTime()) {
1104:                        if (isDebugEnabled())
1105:                            debug(getName()
1106:                                    + ".makeSetupWrapupExpansion : making setup task for "
1107:                                    + task.getUID());
1108:                        subtasks.add(createSetupTask(task, asset, start, end,
1109:                                setupStart, wrapupEnd));
1110:                    }
1111:
1112:                    if (wrapupEnd.getTime() > end.getTime()) {
1113:                        if (isDebugEnabled())
1114:                            debug(getName()
1115:                                    + ".makeSetupWrapupExpansion : making wrapup task for "
1116:                                    + task.getUID());
1117:                        subtasks.add(createWrapupTask(task, asset, start, end,
1118:                                setupStart, wrapupEnd));
1119:                    }
1120:                }
1121:
1122:                publishSubtasks(wantMediumConfidenceOnExpansion, task, subtasks);
1123:
1124:                return subtasks;
1125:            }
1126:
1127:            /**
1128:             * <pre>
1129:             * create first and possibly only subtask of MPTask
1130:             *
1131:             * Time preferences have 
1132:             *  1) the start time = earliest arrival = start of main task
1133:             *  2) the best arrival time = latest arrival = end of main task
1134:             *
1135:             * Attaches WITH prep that shows which asset was used
1136:             * </pre>
1137:             **/
1138:            protected Task createMainTask(Task task, Asset asset, Date start,
1139:                    Date end, Date setupStart, Date wrapupEnd) {
1140:                NewTask mainTask = (NewTask) expandHelper.makeSubTask(ldmf,
1141:                        task, task.getDirectObject(), task.getSource());
1142:                mainTask.setPrepositionalPhrases(getPrepPhrases(task, asset)
1143:                        .elements());
1144:                synchronized (task) { // bug #2124
1145:                    mainTask.setPreferences(getPreferences(task, start, start,
1146:                            end, end).elements());
1147:                }
1148:                if (isDebugEnabled())
1149:                    debug(getName() + ".createMainTask : made main task : "
1150:                            + mainTask.getUID());
1151:                return mainTask;
1152:            }
1153:
1154:            /**
1155:             * <pre>
1156:             * create setup task that goes before main subtask
1157:             *
1158:             * Time preferences have 
1159:             *  1) the start time = earliest arrival = setup start
1160:             *  2) the best arrival time = latest arrival = start of main task
1161:             *
1162:             * Attaches WITH prep that shows which asset was used
1163:             *
1164:             * </pre>
1165:             **/
1166:            protected Task createSetupTask(Task task, Asset asset, Date start,
1167:                    Date end, Date setupStart, Date wrapupEnd) {
1168:                NewTask setupTask = (NewTask) expandHelper.makeSubTask(ldmf,
1169:                        task, task.getDirectObject(), task.getSource());
1170:                setupTask.setVerb(Verb.getVerb("Transit"));
1171:                setupTask.setPrepositionalPhrases(getPrepPhrases(task, asset)
1172:                        .elements());
1173:                setupTask.setPreferences(getPreferences(task, setupStart,
1174:                        setupStart, start, start).elements());
1175:                if (isDebugEnabled())
1176:                    debug(getName() + ".createSetupTask : made setup task : "
1177:                            + setupTask.getUID());
1178:                return setupTask;
1179:            }
1180:
1181:            /**
1182:             * <pre>
1183:             * create wrapup task that goes after main subtask
1184:             *
1185:             * Time preferences have 
1186:             *  1) the start time = earliest arrival = end of main task
1187:             *  2) the best arrival time = latest arrival = end of wrapup
1188:             *
1189:             * Attaches WITH prep that shows which asset was used
1190:             *
1191:             * </pre>
1192:             **/
1193:            protected Task createWrapupTask(Task task, Asset asset, Date start,
1194:                    Date end, Date setupStart, Date wrapupEnd) {
1195:                NewTask wrapupTask = (NewTask) expandHelper.makeSubTask(ldmf,
1196:                        task, task.getDirectObject(), task.getSource());
1197:                wrapupTask.setVerb(Verb.getVerb("Transit"));
1198:                wrapupTask.setPrepositionalPhrases(getPrepPhrases(task, asset)
1199:                        .elements());
1200:                wrapupTask.setPreferences(getPreferences(task, end, end,
1201:                        wrapupEnd, wrapupEnd).elements());
1202:                if (isDebugEnabled())
1203:                    debug(getName() + ".createWrapupTask : made wrapup task : "
1204:                            + wrapupTask.getUID());
1205:                return wrapupTask;
1206:            }
1207:
1208:            /**
1209:             * <pre>
1210:             * Adjust preferences so that the start time preference is the assigned 
1211:             * start time, and the end time preference has a best date that is the 
1212:             * assigned end time.  The early and late dates of the end time preference
1213:             * are the same as the first parent task. (This isn't very important, as the
1214:             * downstream allocator should just allocate to the start and best times.)
1215:             *
1216:             * </pre>
1217:             * @param parentTask - parent task
1218:             * @param readyAt - the date for the START_TIME preference
1219:             * @param best - the best date for the END_TIME preference
1220:             * @return Vector - list of preferences for the MPTask
1221:             */
1222:            protected Vector getPreferences(Task parentTask, Date readyAt,
1223:                    Date earliest, Date best, Date latest) {
1224:                Vector prefs = allocHelper.enumToVector(parentTask
1225:                        .getPreferences());
1226:                prefs = prefHelper.replacePreference(prefs, prefHelper
1227:                        .makeStartDatePreference(ldmf, readyAt));
1228:                prefs = prefHelper.replacePreference(prefs, prefHelper
1229:                        .makeEndDatePreference(ldmf, earliest, best, latest));
1230:                return prefs;
1231:            }
1232:
1233:            /**
1234:             * This method Expands the given Task.
1235:             *
1236:             * @param wantConfidence set the confidence to 100% on expansion
1237:             * @param t the task to be expanded.
1238:             * @param subtasks the expanded subtasks
1239:             */
1240:            public void publishSubtasks(boolean wantConfidence, Task t,
1241:                    List subtasks) {
1242:                if (isDebugEnabled()) {
1243:                    debug(getName()
1244:                            + ".handleTask: Subtask(s) created for task :"
1245:                            + t.getUID());
1246:                }
1247:
1248:                Workflow wf = expandHelper.makeWorkflow(ldmf, subtasks,
1249:                        skipTransitARA, t);
1250:
1251:                Expansion exp = null;
1252:                if (wantConfidence) {
1253:                    exp = expandHelper.makeExpansionWithConfidence(ldmf, wf);
1254:                } else {
1255:                    exp = expandHelper.makeExpansion(ldmf, wf);
1256:                }
1257:
1258:                if (isDebugEnabled()) {
1259:                    debug(getName() + ".handleTask: Expansion created. ("
1260:                            + exp.getUID() + ")");
1261:                }
1262:
1263:                for (Iterator i = subtasks.iterator(); i.hasNext();) {
1264:                    publishAddWithCheck(i.next());
1265:                }
1266:                publishAddWithCheck(exp);
1267:
1268:                if (isDebugEnabled()) {
1269:                    debug(getName()
1270:                            + ".handleTask: Expansion published. Workflow has "
1271:                            + allocHelper.enumToList(
1272:                                    exp.getWorkflow().getTasks()).size()
1273:                            + " subtasks.");
1274:                }
1275:
1276:            }
1277:
1278:            /**
1279:             * Defines how the task holds the asset for the task->asset association.
1280:             *
1281:             * Critical, because the allocator downstream will probably look for this prep and
1282:             * pluck the asset off to make the allocation or use it in some way.
1283:             *
1284:             * @param a - asset to attach to task
1285:             * @param parentTask - parent task
1286:             * @return the original set of prep phrases from the first parent task PLUS the WITH
1287:             *         prep with the asset
1288:             */
1289:            protected Vector getPrepPhrases(Task parentTask, Asset a) {
1290:                Vector preps = new Vector(allocHelper.enumToVector(parentTask
1291:                        .getPrepositionalPhrases()));
1292:                if (!prepHelper.hasPrepNamed(parentTask,
1293:                        Constants.Preposition.WITH))
1294:                    preps.addElement(prepHelper.makePrepositionalPhrase(ldmf,
1295:                            Constants.Preposition.WITH, a));
1296:
1297:                preps.addElement(prepHelper.makePrepositionalPhrase(ldmf,
1298:                        "VISHNU", getClassName(this )));
1299:                return preps;
1300:            }
1301:
1302:            protected void publishAddWithCheck(Object obj) {
1303:                publishAdd(obj);
1304:            }
1305:
1306:            // ------------- MODES ------------------------ 
1307:            /** determines whether to run in internal or external (with web server) mode */
1308:            protected boolean runInternal = true;
1309:            /** determines whether to do XML or direct translation of Cougaar objects */
1310:            protected boolean runDirectly = false;
1311:            /** incremental or batch mode */
1312:            protected boolean incrementalScheduling = false;
1313:
1314:            // ------------- TASKS -------------------------
1315:            /** how many tasks to examine to automatically determine format in automatic translation mode */
1316:            protected int firstTemplateTasks;
1317:            /** memory for which tasks are being processed in this batch -- used when assignments are returned */
1318:            protected Map myTaskUIDtoObject = new HashMap();
1319:
1320:            // ------------- ASSETS ------------------------ 
1321:            /** assets to use */
1322:            protected UTILAssetCallback myAssetCallback;
1323:            /** memory of which assets are available -- used when assignments are returned */
1324:            protected Map myAssetUIDtoObject = new HashMap();
1325:            /** recently received assets to tell the scheduler about */
1326:            protected Set myNewAssets = new HashSet();
1327:            /** changed assets to tell the scheduler about */
1328:            protected Set myChangedAssets = new HashSet();
1329:
1330:            // ------------- FLAGS ------------------------ 
1331:
1332:            /** option : create setup and wrapup tasks, in addition to assignment task */
1333:            protected boolean makeSetupAndWrapupTasks = true;
1334:            /** controls whether to use custom translation */
1335:            protected boolean useStoredFormat = false;
1336:            /** controls whether to do exit on failure, sometimes useful for debugging */
1337:            protected boolean stopOnFailure = false;
1338:            /** report debug output showing timing info */
1339:            protected boolean showTiming = true;
1340:
1341:            // ------------- STATE ---------------------------------
1342:            /** sent the format already?  Send it only once unless in batch mode */
1343:            protected boolean sentFormatAlready = false;
1344:            /** object format doc, either generated or from a file */
1345:            protected Document objectFormatDoc;
1346:
1347:            protected boolean localDidRehydrate = false;
1348:
1349:            protected boolean wantMediumConfidenceOnExpansion;
1350:
1351:            protected int total = 0;
1352:
1353:            // ------------- HELPER OBJECTS ------------------------
1354:            /** mode - manages scheduler lifecycle */
1355:            protected SchedulerLifecycle mode;
1356:            /** handles results, calls methods in plugin to create plan elements */
1357:            protected ResultHandler resultHandler;
1358:
1359:            /** manages communication with URLs or internally */
1360:            protected VishnuComm comm;
1361:            /** utility functions for manipulating DOM documents */
1362:            protected VishnuDomUtil domUtil;
1363:            /** automatic translator */
1364:            protected XMLProcessor xmlProcessor;
1365:            /** config files, gets representative tasks and assets for automatic translation */
1366:            protected VishnuConfig config;
1367:
1368:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.