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


0001:        /*
0002:         * <copyright>
0003:         *  
0004:         *  Copyright 1997-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.mlm.plugin.organization;
0027:
0028:        import java.io.BufferedReader;
0029:        import java.io.InputStreamReader;
0030:        import java.io.Reader;
0031:        import java.io.StreamTokenizer;
0032:        import java.lang.reflect.Constructor;
0033:        import java.lang.reflect.Field;
0034:        import java.lang.reflect.Method;
0035:        import java.util.ArrayList;
0036:        import java.util.Calendar;
0037:        import java.util.Collection;
0038:        import java.util.Date;
0039:        import java.util.Enumeration;
0040:        import java.util.HashMap;
0041:        import java.util.Iterator;
0042:        import java.util.List;
0043:        import java.util.StringTokenizer;
0044:        import java.util.Vector;
0045:
0046:        import org.cougaar.core.mts.MessageAddress;
0047:        import org.cougaar.glm.ldm.Constants;
0048:        import org.cougaar.glm.ldm.GLMFactory;
0049:        import org.cougaar.glm.ldm.asset.AssignedPGImpl;
0050:        import org.cougaar.glm.ldm.asset.Facility;
0051:        import org.cougaar.glm.ldm.asset.NewAssignedPG;
0052:        import org.cougaar.glm.ldm.asset.NewAssignmentPG;
0053:        import org.cougaar.glm.ldm.asset.NewPositionPG;
0054:        import org.cougaar.glm.ldm.asset.Organization;
0055:        import org.cougaar.glm.ldm.asset.OrganizationAdapter;
0056:        import org.cougaar.glm.ldm.asset.PositionPGImpl;
0057:        import org.cougaar.glm.ldm.asset.TransportationNode;
0058:        import org.cougaar.glm.ldm.plan.GLMRelationship;
0059:        import org.cougaar.glm.ldm.plan.NewGeolocLocation;
0060:        import org.cougaar.glm.ldm.plan.NewPosition;
0061:        import org.cougaar.planning.ldm.asset.LocationSchedulePG;
0062:        import org.cougaar.planning.ldm.asset.LocationSchedulePGImpl;
0063:        import org.cougaar.planning.ldm.asset.NewClusterPG;
0064:        import org.cougaar.planning.ldm.asset.NewItemIdentificationPG;
0065:        import org.cougaar.planning.ldm.asset.NewLocationSchedulePG;
0066:        import org.cougaar.planning.ldm.asset.NewPropertyGroup;
0067:        import org.cougaar.planning.ldm.asset.NewTypeIdentificationPG;
0068:        import org.cougaar.planning.ldm.asset.PropertyGroup;
0069:        import org.cougaar.planning.ldm.plan.AspectType;
0070:        import org.cougaar.planning.ldm.plan.AspectValue;
0071:        import org.cougaar.planning.ldm.plan.Location;
0072:        import org.cougaar.planning.ldm.plan.NewPrepositionalPhrase;
0073:        import org.cougaar.planning.ldm.plan.NewRoleSchedule;
0074:        import org.cougaar.planning.ldm.plan.NewSchedule;
0075:        import org.cougaar.planning.ldm.plan.NewTask;
0076:        import org.cougaar.planning.ldm.plan.Preference;
0077:        import org.cougaar.planning.ldm.plan.Relationship;
0078:        import org.cougaar.planning.ldm.plan.Role;
0079:        import org.cougaar.planning.ldm.plan.Schedule;
0080:        import org.cougaar.planning.ldm.plan.ScoringFunction;
0081:        import org.cougaar.planning.ldm.plan.TaggedLocationScheduleElement;
0082:        import org.cougaar.planning.ldm.plan.TimeAspectValue;
0083:        import org.cougaar.planning.plugin.legacy.SimplePlugin;
0084:        import org.cougaar.util.ConfigFinder;
0085:        import org.cougaar.util.EmptyEnumeration;
0086:        import org.cougaar.util.Reflect;
0087:        import org.cougaar.util.TimeSpan;
0088:
0089:        /**
0090:         * This is a modified version of the OrgRTDataPlugin. OrgTPRTDataPlugin 
0091:         * reads time-dependent superior/subordinate relationships from a 
0092:         * <agent-name>-relationships.ini file in place of the information found in the
0093:         * [Relationships] section in the <agent-name>-prototype-ini.dat file and 
0094:         * puts the times associated with the relationships
0095:         * in the RFS and RFD tasks in place of the DEFAULT_START_TIME and DEFAULT_END_TIME. 
0096:         * If the <agent-name>-relationships.ini is absent or has the wrong format, it 
0097:         * defaults to the behavior of the OrgRTDataPlugin.
0098:         *
0099:         * @deprecated Uses file format which is no longer supported. Use
0100:         * OrgDataPlugin or OrgDataParamBasedPlugin instead. Both pluging support time
0101:         * phased relationships.
0102:         *
0103:         */
0104:
0105:        public class OrgTPRTDataPlugin extends SimplePlugin {
0106:            private static TrivialTimeSpan ETERNITY = new TrivialTimeSpan(
0107:                    TimeSpan.MIN_VALUE, TimeSpan.MAX_VALUE);
0108:
0109:            private final static String UTC = "UTC/RTOrg";
0110:
0111:            private static Calendar myCalendar = Calendar.getInstance();
0112:
0113:            private static long DEFAULT_START_TIME = -1;
0114:            private static long DEFAULT_END_TIME = -1;
0115:
0116:            static {
0117:                myCalendar.set(1990, 0, 1, 0, 0, 0);
0118:                DEFAULT_START_TIME = myCalendar.getTime().getTime();
0119:
0120:                myCalendar.set(2010, 0, 1, 0, 0, 0);
0121:                DEFAULT_END_TIME = myCalendar.getTime().getTime();
0122:            }
0123:
0124:            private Vector organization_vector = new Vector();
0125:            private Organization selfOrg;
0126:            private GLMFactory aldmf;
0127:
0128:            protected void setupSubscriptions() {
0129:                aldmf = (GLMFactory) getFactory("glm");
0130:                getSubscriber().setShouldBePersisted(false);
0131:
0132:                if (!didRehydrate()) {
0133:                    processOrganizations(); // Objects should already exist after rehydration
0134:                }
0135:
0136:            }
0137:
0138:            protected void execute() {
0139:            }
0140:
0141:            /**
0142:             * Parses the prototype-ini file and in the process sets up
0143:             * the organization_vector with pairs of "relationship"/"organization"
0144:             * It then loops through the vector and for each organization
0145:             * it parses the appropriate prototype-ini file.
0146:             */
0147:            protected void processOrganizations() {
0148:                try {
0149:                    String aId = getMessageAddress().getAddress();
0150:                    ParsePrototypeFile(aId, GLMRelationship.SELF);
0151:
0152:                    String organizations[][] = null;
0153:
0154:                    // get the time phased relations from teh relationship file
0155:                    Vector relationshipsVector = parseRelationshipFile(aId,
0156:                            GLMRelationship.SELF);
0157:
0158:                    // Put the organizations for this agent into array
0159:                    if (relationshipsVector != null) {
0160:                        //System.out.println(aId+": TPRTdataPlugin parsed relationships file");
0161:                        organizations = new String[relationshipsVector.size()][5];
0162:                        relationshipsVector.copyInto(organizations);
0163:                    } else {
0164:                        organizations = new String[organization_vector.size()][5];
0165:                        organization_vector.copyInto(organizations);
0166:                    }
0167:                    // For each organization, parse appropriate prototype-ini file
0168:                    for (int j = 0; j < organizations.length; j++) {
0169:                        // 980723 EWD changed second condition to use index 1 instead of 0
0170:                        if ((organizations[j][0] != null)
0171:                                && (organizations[j][1] != null)) {
0172:                            Class r_class = GLMRelationship.class;
0173:                            Field f = r_class.getField(organizations[j][0]
0174:                                    .toUpperCase());
0175:                            if ((GLMRelationship.SUPPORTING)
0176:                                    .equals(f.get(null))) {
0177:                                cloneMe(organizations[j][1],
0178:                                        organizations[j][2],
0179:                                        organizations[j][3],
0180:                                        organizations[j][4]);
0181:                            } else if ((GLMRelationship.SUPERIOR).equals(f
0182:                                    .get(null))) {
0183:                                createSuperior(organizations[j][1],
0184:                                        organizations[j][3],
0185:                                        organizations[j][4]);
0186:                            }
0187:                        }
0188:                    }
0189:                } catch (Exception e) {
0190:                    e.printStackTrace();
0191:                }
0192:            }
0193:
0194:            protected void createSuperior(String sup, String startTimeStr,
0195:                    String endTimeStr) {
0196:                Organization super iorOrg = createOrganization(sup);
0197:
0198:                if (super iorOrg == null) {
0199:                    throw new RuntimeException(
0200:                            "OrgRTDataPlugin: Unable to create superior org asset "
0201:                                    + sup);
0202:                } else if (selfOrg == null) {
0203:                    throw new RuntimeException(
0204:                            "OrgRTDataPlugin: selfOrg is null in createSuperior");
0205:                }
0206:
0207:                NewAssignedPG super iorCapability;
0208:
0209:                if (!super iorOrg.hasAssignedPG()) {
0210:                    super iorCapability = (NewAssignedPG) getFactory()
0211:                            .createPropertyGroup(AssignedPGImpl.class);
0212:                } else {
0213:                    super iorCapability = (NewAssignedPG) super iorOrg
0214:                            .getAssignedPG().copy();
0215:                }
0216:
0217:                ArrayList roles = new ArrayList(1);
0218:                roles.add(Constants.Role.ADMINISTRATIVESUPERIOR);
0219:                super iorCapability.setRoles(roles);
0220:                super iorOrg.setAssignedPG(super iorCapability);
0221:
0222:                // clone the selfOrg
0223:                Organization clone = (Organization) getFactory().cloneInstance(
0224:                        selfOrg);
0225:                NewAssignedPG cloneCapability;
0226:
0227:                if (!clone.hasAssignedPG()) {
0228:                    cloneCapability = (NewAssignedPG) getFactory()
0229:                            .createPropertyGroup(AssignedPGImpl.class);
0230:                } else {
0231:                    cloneCapability = (NewAssignedPG) clone.getAssignedPG()
0232:                            .copy();
0233:                }
0234:                roles.clear();
0235:                roles.add(Constants.Role.ADMINISTRATIVESUBORDINATE);
0236:                cloneCapability.setRoles(roles);
0237:                clone.setAssignedPG(cloneCapability);
0238:
0239:                publish(createRFD(super iorOrg, clone, roles, startTimeStr,
0240:                        endTimeStr));
0241:            }
0242:
0243:            // creates a copy of my "self" org with special capable roles to send to a
0244:            // agent I am supporting.
0245:            // Also create a client org in this agent
0246:            protected void cloneMe(String sendto, String caproles,
0247:                    String startTimeStr, String endTimeStr) {
0248:                if (selfOrg == null) {
0249:                    System.err
0250:                            .println("OrgRTDataPlugin: selfOrg is null in cloneMe");
0251:                    return;
0252:                }
0253:
0254:                // clone the selfOrg
0255:                Organization clone = (Organization) getFactory().cloneInstance(
0256:                        selfOrg);
0257:                Organization client = createOrganization(sendto);
0258:
0259:                if (client == null) {
0260:                    System.err
0261:                            .println("OrgRTDataPlugin: Unable to create client "
0262:                                    + sendto);
0263:                    return;
0264:                }
0265:
0266:                //To assist in debugging, I've broken the assignement into chunks
0267:                NewAssignedPG cloneCapability;
0268:
0269:                if (!clone.hasAssignedPG()) {
0270:                    cloneCapability = (NewAssignedPG) getFactory()
0271:                            .createPropertyGroup(AssignedPGImpl.class);
0272:                } else {
0273:                    cloneCapability = (NewAssignedPG) clone.getAssignedPG()
0274:                            .copy();
0275:                }
0276:
0277:                //To assist in debugging, I've broken the assignement into chunks
0278:                NewAssignedPG clientCapability;
0279:
0280:                if (!client.hasAssignedPG()) {
0281:                    clientCapability = (NewAssignedPG) getFactory()
0282:                            .createPropertyGroup(AssignedPGImpl.class);
0283:                } else {
0284:                    clientCapability = (NewAssignedPG) (client.getAssignedPG()
0285:                            .copy());
0286:                }
0287:
0288:                Vector rolestrs = org.cougaar.util.StringUtility
0289:                        .parseCSV(caproles);
0290:                Collection roles = new ArrayList();
0291:
0292:                for (Iterator i = rolestrs.iterator(); i.hasNext();) {
0293:                    Role role = Role.getRole((String) i.next());
0294:                    roles.add(role);
0295:                }
0296:                cloneCapability.setRoles(roles);
0297:                clone.setAssignedPG(cloneCapability);
0298:
0299:                publish(createRFS(client, clone, roles, startTimeStr,
0300:                        endTimeStr));
0301:            }
0302:
0303:            protected Organization createOrganization(String orgStr) {
0304:                final String uic = orgStr.startsWith("UIC/") ? orgStr : "UIC/"
0305:                        .concat(orgStr);
0306:
0307:                // Use the same domain name for all org assets now
0308:                Organization org = (Organization) getFactory().createAsset(
0309:                        "Organization");
0310:                org.initRelationshipSchedule();
0311:                org.setLocal(false);
0312:
0313:                ((NewTypeIdentificationPG) org.getTypeIdentificationPG())
0314:                        .setTypeIdentification(UTC);
0315:
0316:                NewItemIdentificationPG itemIdProp = (NewItemIdentificationPG) org
0317:                        .getItemIdentificationPG();
0318:                itemIdProp.setItemIdentification(uic);
0319:                itemIdProp.setNomenclature(orgStr);
0320:                itemIdProp.setAlternateItemIdentification(orgStr);
0321:
0322:                NewClusterPG cpg = (NewClusterPG) org.getClusterPG();
0323:                cpg.setMessageAddress(MessageAddress.getMessageAddress(orgStr));
0324:
0325:                return org;
0326:            }
0327:
0328:            //create the RFD task to be sent to myself which will result in an asset transfer
0329:            // of myself being sent to the agent I am supporting.
0330:            protected NewTask createRFD(Organization sup, Organization sub,
0331:                    Collection roles, String startTimeStr, String endTimeStr) {
0332:                long[] times = parseTimeStrings(startTimeStr, endTimeStr);
0333:                //System.out.println("OrgTPRTDataPlugin: Creating RFD Task for: " + sup.getItemIdentificationPG().getItemIdentification()+ " START_TIME="+new Date(times[0]) + " END_TIME="+new Date(times[1]));
0334:                NewTask rfdTask = createReportTask(sub, sup, roles, times[0],
0335:                        times[1]);
0336:                rfdTask.setVerb(Constants.Verb.ReportForDuty);
0337:
0338:                return rfdTask;
0339:            }
0340:
0341:            //create the RFD task to be sent to myself which will result in an asset transfer
0342:            // of myself being sent to the agent I am supporting.
0343:            protected NewTask createRFS(Organization client,
0344:                    Organization reportingOrg, Collection roles,
0345:                    String startTimeStr, String endTimeStr) {
0346:                long[] times = parseTimeStrings(startTimeStr, endTimeStr);
0347:                //System.out.println("OrgTPRTDataPlugin: Creating RFS Task for: " + reportingOrg.getItemIdentificationPG().getItemIdentification()+ " START_TIME="+new Date(times[0]) + " END_TIME="+new Date(times[1]));
0348:                NewTask rfsTask = createReportTask(reportingOrg, client, roles,
0349:                        times[0], times[1]);
0350:                rfsTask.setVerb(Constants.Verb.ReportForService);
0351:
0352:                return rfsTask;
0353:            }
0354:
0355:            protected long[] parseTimeStrings(String startTimeStr,
0356:                    String endTimeStr) {
0357:                try {
0358:                    String year = "";
0359:                    String month = "";
0360:                    String day = "";
0361:
0362:                    //System.out.println("OrgTPRTDataPlugin: parseTimeStrings: startTimeStr=" + startTimeStr + " endTimeStr=" + endTimeStr);
0363:
0364:                    boolean validDate = true;
0365:
0366:                    long startTime = DEFAULT_START_TIME;
0367:                    long endTime = DEFAULT_END_TIME;
0368:
0369:                    // process only if startTimeStr and endTimeStr are of non-zero length
0370:                    if (startTimeStr != null && endTimeStr != null) {
0371:                        Calendar cal = Calendar.getInstance();
0372:                        StringTokenizer st = null;
0373:                        if (!startTimeStr.equals("")) {
0374:                            st = new StringTokenizer(startTimeStr, "/ \\");
0375:                            if (st.hasMoreTokens())
0376:                                month = st.nextToken();
0377:                            else
0378:                                validDate = false;
0379:                            if (st.hasMoreTokens())
0380:                                day = st.nextToken();
0381:                            else
0382:                                validDate = false;
0383:                            if (st.hasMoreTokens())
0384:                                year = st.nextToken();
0385:                            else
0386:                                validDate = false;
0387:                        }
0388:
0389:                        if (validDate) { // startTimeStr has all the components, now check endTimeStr
0390:                            long t1 = DEFAULT_START_TIME;
0391:                            if (!startTimeStr.equals("")) {
0392:                                cal.clear();
0393:                                cal.set(Integer.parseInt(year), Integer
0394:                                        .parseInt(month) - 1, Integer
0395:                                        .parseInt(day), 0, 0, 0);
0396:                                //System.out.println("OrgTPRTDataPlugin: parseTimeStrings t1: year=" + year + " month=" + month + " day=" + day);
0397:                                t1 = cal.getTime().getTime();
0398:                            }
0399:
0400:                            if (!endTimeStr.equals("")) {
0401:                                st = new StringTokenizer(endTimeStr, "/ \\");
0402:                                if (st.hasMoreTokens())
0403:                                    month = st.nextToken();
0404:                                else
0405:                                    validDate = false;
0406:                                if (st.hasMoreTokens())
0407:                                    day = st.nextToken();
0408:                                else
0409:                                    validDate = false;
0410:                                if (st.hasMoreTokens())
0411:                                    year = st.nextToken();
0412:                                else
0413:                                    validDate = false;
0414:                            }
0415:
0416:                            if (validDate) { // endTimeStr also has all the components, change values of startTime and endTime from their defaults
0417:                                long t2 = DEFAULT_END_TIME;
0418:                                if (!endTimeStr.equals("")) {
0419:                                    cal.clear();
0420:                                    cal.set(Integer.parseInt(year), Integer
0421:                                            .parseInt(month) - 1, Integer
0422:                                            .parseInt(day), 0, 0, 0);
0423:                                    t2 = cal.getTime().getTime();
0424:                                    //System.out.println("OrgTPRTDataPlugin: parseTimeStrings t2: year=" + year + " month=" + month + " day=" + day);
0425:                                }
0426:
0427:                                startTime = t1;
0428:                                endTime = t2;
0429:                                //System.out.println("OrgTPRTDataPlugin: parseTimeStrings startTime=" + new Date(startTime));
0430:                                //System.out.println("OrgTPRTDataPlugin: parseTimeStrings endTime=" + new Date(endTime));
0431:                            }
0432:                        }
0433:                    }
0434:
0435:                    return new long[] { startTime, endTime };
0436:                } catch (Exception e) {
0437:                    e.printStackTrace();
0438:                    // System.out.println("returning default times");
0439:                    return new long[] { DEFAULT_START_TIME, DEFAULT_END_TIME };
0440:                }
0441:            }
0442:
0443:            //create the RFS task to be sent to myself which will result in an asset transfer
0444:            // of the copyofmyself being sent to the agent I am supporting.
0445:            protected NewTask createReportTask(Organization reportingOrg,
0446:                    OrganizationAdapter sendto, Collection roles,
0447:                    long startTime, long endTime) {
0448:                NewTask reportTask = getFactory().newTask();
0449:                reportTask.setDirectObject(reportingOrg);
0450:
0451:                Vector prepPhrases = new Vector(2);
0452:                NewPrepositionalPhrase newpp = getFactory()
0453:                        .newPrepositionalPhrase();
0454:                newpp.setPreposition(Constants.Preposition.FOR);
0455:                newpp.setIndirectObject(sendto);
0456:                prepPhrases.add(newpp);
0457:
0458:                newpp = getFactory().newPrepositionalPhrase();
0459:                newpp.setPreposition(Constants.Preposition.AS);
0460:                newpp.setIndirectObject(roles);
0461:                prepPhrases.add(newpp);
0462:                reportTask.setPrepositionalPhrases(prepPhrases.elements());
0463:
0464:                reportTask.setPlan(getFactory().getRealityPlan());
0465:                reportTask.setSource(getMessageAddress());
0466:
0467:                AspectValue startTAV = TimeAspectValue.create(
0468:                        AspectType.START_TIME, startTime);
0469:                ScoringFunction startScoreFunc = ScoringFunction
0470:                        .createStrictlyAtValue(startTAV);
0471:                Preference startPreference = getFactory().newPreference(
0472:                        AspectType.START_TIME, startScoreFunc);
0473:
0474:                AspectValue endTAV = TimeAspectValue.create(
0475:                        AspectType.END_TIME, endTime);
0476:                ScoringFunction endScoreFunc = ScoringFunction
0477:                        .createStrictlyAtValue(endTAV);
0478:                Preference endPreference = getFactory().newPreference(
0479:                        AspectType.END_TIME, endScoreFunc);
0480:
0481:                Vector preferenceVector = new Vector(2);
0482:                preferenceVector.addElement(startPreference);
0483:                preferenceVector.addElement(endPreference);
0484:
0485:                reportTask.setPreferences(preferenceVector.elements());
0486:
0487:                return reportTask;
0488:            }
0489:
0490:            private void publish(Object o) {
0491:                publishAdd(o);
0492:            }
0493:
0494:            /**
0495:             * 
0496:             */
0497:            protected void ParsePrototypeFile(String agentId,
0498:                    String relationship) {
0499:
0500:                // Use the same domainname for all org assets now
0501:                String uic = "";
0502:                String className = "";
0503:                String unitName = null;
0504:                String dataItem = "";
0505:                Organization org = null;
0506:                int newVal;
0507:
0508:                String filename = agentId + "-prototype-ini.dat";
0509:                BufferedReader input = null;
0510:                Reader fileStream = null;
0511:
0512:                try {
0513:                    fileStream = new InputStreamReader(ConfigFinder
0514:                            .getInstance().open(filename));
0515:                    input = new BufferedReader(fileStream);
0516:                    StreamTokenizer tokens = new StreamTokenizer(input);
0517:                    tokens.commentChar('#');
0518:                    tokens.wordChars('[', ']');
0519:                    tokens.wordChars('_', '_');
0520:                    tokens.wordChars('<', '>');
0521:                    tokens.wordChars('/', '/');
0522:                    tokens.ordinaryChars('0', '9');
0523:                    tokens.wordChars('0', '9');
0524:
0525:                    newVal = tokens.nextToken();
0526:                    // Parse the prototype-ini file
0527:                    while (newVal != StreamTokenizer.TT_EOF) {
0528:                        if (tokens.ttype == StreamTokenizer.TT_WORD) {
0529:                            dataItem = tokens.sval;
0530:                            if (dataItem.equals("[Prototype]")) {
0531:                                tokens.nextToken();
0532:                                className = tokens.sval;
0533:                                newVal = tokens.nextToken();
0534:                            } else if (dataItem.equals("[UniqueId]")) {
0535:                                tokens.nextToken();
0536:                                // Dont use unique-id as domain name anymore, just skip it
0537:                                //utc = tokens.sval;
0538:                                newVal = tokens.nextToken();
0539:                            } else if (dataItem.equals("[UnitName]")) {
0540:                                // This field is optional 
0541:                                tokens.nextToken();
0542:                                unitName = tokens.sval;
0543:                                newVal = tokens.nextToken();
0544:                            } else if (dataItem.equals("[UIC]")) {
0545:                                if (className != null) {
0546:                                    tokens.nextToken();
0547:                                    uic = tokens.sval;
0548:
0549:                                    // This is a silly fix to a dumb bug
0550:                                    if (!uic.startsWith("UIC/")) {
0551:                                        uic = "UIC/" + uic;
0552:                                    }
0553:
0554:                                    org = (Organization) getFactory()
0555:                                            .createAsset("Organization");
0556:                                    org.initRelationshipSchedule();
0557:                                    org.setLocal(false);
0558:
0559:                                    NewTypeIdentificationPG typeIdPG = (NewTypeIdentificationPG) org
0560:                                            .getTypeIdentificationPG();
0561:                                    typeIdPG.setTypeIdentification(UTC);
0562:
0563:                                    NewItemIdentificationPG itemIdPG = (NewItemIdentificationPG) org
0564:                                            .getItemIdentificationPG();
0565:                                    itemIdPG.setItemIdentification(uic);
0566:                                    // Use unitName if it occurred, else use agentId
0567:                                    if (unitName != null) {
0568:                                        itemIdPG.setNomenclature(unitName);
0569:                                    } else {
0570:                                        itemIdPG.setNomenclature(agentId);
0571:                                    }
0572:                                    itemIdPG
0573:                                            .setAlternateItemIdentification(agentId);
0574:
0575:                                    NewClusterPG cpg = (NewClusterPG) org
0576:                                            .getClusterPG();
0577:                                    cpg.setMessageAddress(MessageAddress
0578:                                            .getMessageAddress(agentId));
0579:                                } else {
0580:                                    System.out
0581:                                            .println("OrgRTDataPlugin Error: [Prototype] value is null");
0582:                                }
0583:                                newVal = tokens.nextToken();
0584:                            } else if (dataItem.equals("[Relationship]")) {
0585:                                newVal = FillOrganizationVector(org, newVal,
0586:                                        tokens, relationship);
0587:                                // ADDED BY TOPS
0588:                            } else if (dataItem.equals("[AssignmentPG]")) {
0589:                                newVal = setAssignmentForOrganization(org,
0590:                                        dataItem, newVal, tokens);
0591:                                // END ADDED BY TOPS
0592:                            } else if (dataItem.substring(0, 1).equals("[")) {
0593:                                // We've got a property or capability
0594:                                newVal = setPropertyForOrganization(org,
0595:                                        dataItem, newVal, tokens);
0596:                            } else {
0597:                                // if The token you read is not one of the valid
0598:                                // choices from above
0599:                                System.out
0600:                                        .println("OrgRTDataPlugin Incorrect token: "
0601:                                                + dataItem);
0602:                            }
0603:                        } else {
0604:                            throw new RuntimeException("Format error in \""
0605:                                    + filename + "\".");
0606:                        }
0607:                    }
0608:
0609:                    // For each organization, the following code sets
0610:                    // CapableRoles and Relationship slots for the
0611:                    // AssignedPG property
0612:                    // It adds the property to the organization and
0613:                    // adds the organization to ccv2 collections
0614:                    NewAssignedPG assignedCap = (NewAssignedPG) getFactory()
0615:                            .createPropertyGroup(AssignedPGImpl.class);
0616:                    Collection roles = org.getOrganizationPG().getRoles();
0617:                    if (roles != null) {
0618:                        assignedCap.setRoles(new ArrayList(roles));
0619:                    }
0620:                    org.setAssignedPG(assignedCap);
0621:
0622:                    // set up this asset's available schedule
0623:                    myCalendar.set(1990, 0, 1, 0, 0, 0);
0624:                    Date start = myCalendar.getTime();
0625:                    // set the end date of the available schedule to 01/01/2010
0626:                    myCalendar.set(2010, 0, 1, 0, 0, 0);
0627:                    Date end = myCalendar.getTime();
0628:                    NewSchedule availsched = getFactory().newSimpleSchedule(
0629:                            start, end);
0630:                    // set the available schedule
0631:                    ((NewRoleSchedule) org.getRoleSchedule())
0632:                            .setAvailableSchedule(availsched);
0633:
0634:                    if (relationship.equals(GLMRelationship.SELF)) {
0635:                        Relationship selfRelationship = getFactory()
0636:                                .newRelationship(Constants.Role.SELF, org, org,
0637:                                        ETERNITY);
0638:                        org.getRelationshipSchedule().add(selfRelationship);
0639:                        org.setLocal(true);
0640:
0641:                        publish(org);
0642:                        selfOrg = org;
0643:                    }
0644:
0645:                    // Closing BufferedReader
0646:                    if (input != null)
0647:                        input.close();
0648:
0649:                    //only generates a NoSuchMethodException for AssetSkeleton because of a coding error
0650:                    //if we are successul in creating it here  it then the AssetSkeletomn will end up with two copies
0651:                    //the add/search criteria in AssetSkeleton is for a Vecotr and does not gurantee only one instance of 
0652:                    //each class.  Thus the Org allocator plugin fails to recognixe the correct set of cpabilities.
0653:
0654:                } catch (Exception e) {
0655:                    e.printStackTrace();
0656:                }
0657:            }
0658:
0659:            /**
0660:             * reads time-phased support and superior relationships from a file
0661:             */
0662:            protected Vector parseRelationshipFile(String agentId,
0663:                    String relationship) {
0664:
0665:                Vector relationshipsVector = new Vector(5, 10);
0666:                String filename = agentId + "-relationships.ini";
0667:
0668:                try {
0669:                    StreamTokenizer st = new StreamTokenizer(
0670:                            new BufferedReader(new InputStreamReader(
0671:                                    ConfigFinder.getInstance().open(filename))));
0672:                    st.eolIsSignificant(true);
0673:                    st.commentChar('#');
0674:                    int count = 1;
0675:                    st.nextToken();
0676:                    while (st.ttype != StreamTokenizer.TT_EOF) {
0677:                        String[] relationshipsArray = { "", "", "", "", "" };
0678:
0679:                        Vector tokenVector = new Vector(5);
0680:                        // read the next full line of input
0681:                        while (st.ttype != StreamTokenizer.TT_EOL) {
0682:                            tokenVector.addElement(st.sval);
0683:                            st.nextToken();
0684:                        }
0685:
0686:                        //System.out.println("OrgTPRTDataPlugin:"+ " obtained line: " + tokenVector);
0687:                        // now process the line
0688:                        if (tokenVector.size() == 0) {
0689:                            st.nextToken();
0690:                            count++;
0691:                            continue;
0692:                        }
0693:
0694:                        // element 0 is always Superior or Subordinate
0695:                        relationshipsArray[0] = (String) tokenVector
0696:                                .elementAt(0);
0697:                        // find out what type of relationship this is
0698:                        Class r_class = GLMRelationship.class;
0699:                        Field f = r_class.getField(relationshipsArray[0]
0700:                                .toUpperCase());
0701:
0702:                        if ((GLMRelationship.SUPPORTING).equals(f.get(null))) {
0703:
0704:                            if (tokenVector.size() == 5) {
0705:                                // element 1 is clientAgentName
0706:                                relationshipsArray[1] = (String) tokenVector
0707:                                        .elementAt(1);
0708:                                // element 2 is roles
0709:                                relationshipsArray[2] = (String) tokenVector
0710:                                        .elementAt(2);
0711:                                // element 3 is startDate
0712:                                relationshipsArray[3] = (String) tokenVector
0713:                                        .elementAt(3);
0714:                                // element 4 is endDate
0715:                                relationshipsArray[4] = (String) tokenVector
0716:                                        .elementAt(4);
0717:                            } else {
0718:                                System.out
0719:                                        .println("Line "
0720:                                                + count
0721:                                                + ": incomplete or extra information, using default start and end times for all relations");
0722:                                return null;
0723:                            }
0724:                        } else if ((GLMRelationship.SUPERIOR).equals(f
0725:                                .get(null))) {
0726:
0727:                            if (tokenVector.size() == 4) {
0728:                                // element 1 is subordinateAgentName
0729:                                relationshipsArray[1] = (String) tokenVector
0730:                                        .elementAt(1);
0731:                                // element 2 is startDate
0732:                                relationshipsArray[3] = (String) tokenVector
0733:                                        .elementAt(2);
0734:                                // element 3 is endDate
0735:                                relationshipsArray[4] = (String) tokenVector
0736:                                        .elementAt(3);
0737:                            } else if (tokenVector.size() == 5) {
0738:                                // element 1 is subordinateAgentName
0739:                                relationshipsArray[1] = (String) tokenVector
0740:                                        .elementAt(1);
0741:                                // element 3 is startDate
0742:                                relationshipsArray[3] = (String) tokenVector
0743:                                        .elementAt(3);
0744:                                // element 4 is endDate
0745:                                relationshipsArray[4] = (String) tokenVector
0746:                                        .elementAt(4);
0747:                            } else {
0748:                                System.out
0749:                                        .println("Line "
0750:                                                + count
0751:                                                + ": extra information, using default start and end times for all relations");
0752:                                return null;
0753:                            }
0754:                        } else {
0755:                            System.out
0756:                                    .println("Line "
0757:                                            + count
0758:                                            + ": unrecognized relationship, using default start and end times for all relations");
0759:                            return null;
0760:                        }
0761:
0762:                        // we now have all tokens necessary from a single relationship statement
0763:                        if (relationship.equals(GLMRelationship.SELF))
0764:                            relationshipsVector.addElement(relationshipsArray);
0765:                        /*
0766:                        for (int i = 0; i < relationshipsArray.length; i++)
0767:                        	System.out.println("OrgTPRTDataPlugin:"+ " obtained token: " + "*"+relationshipsArray[i]+"*");
0768:                         */
0769:
0770:                        // advance to the next line
0771:                        st.nextToken();
0772:                        count++;
0773:                    }
0774:
0775:                } catch (Exception e) {
0776:                    e.printStackTrace();
0777:                    return null;
0778:                }
0779:
0780:                return relationshipsVector;
0781:            }
0782:
0783:            private Object parseExpr(String type, String arg) {
0784:                int i;
0785:                if ((i = type.indexOf("<")) >= 0) {
0786:                    int j = type.lastIndexOf(">");
0787:                    String ctype = type.substring(0, i);
0788:                    String etype = type.substring(i + 1, j);
0789:                    Collection c = null;
0790:                    if (ctype.equals("Collection") || ctype.equals("List")) {
0791:                        c = new ArrayList();
0792:                    } else {
0793:                        throw new RuntimeException(
0794:                                "Unparsable collection type: " + type);
0795:                    }
0796:
0797:                    Vector l = org.cougaar.util.StringUtility.parseCSV(arg);
0798:                    for (Iterator it = l.iterator(); it.hasNext();) {
0799:                        c.add(parseExpr(etype, (String) it.next()));
0800:                    }
0801:                    return c;
0802:                } else if ((i = type.indexOf("/")) >= 0) {
0803:                    String m = type.substring(0, i);
0804:                    String mt = type.substring(i + 1);
0805:                    double qty = Double.valueOf(arg).doubleValue();
0806:                    return createMeasureObject(m, qty, mt);
0807:                } else {
0808:                    Class cl = findClass(type);
0809:
0810:                    try {
0811:                        if (cl.isInterface()) {
0812:                            // interface means try the COF
0813:                            return parseWithCOF(cl, arg);
0814:                        } else {
0815:                            Class ac = getArgClass(cl);
0816:                            Object[] args = { arg };
0817:                            Constructor cons = Reflect.getConstructor(ac,
0818:                                    stringArgSpec);
0819:                            if (cons != null) {
0820:                                // found a constructor - use it
0821:                                return cons.newInstance(args);
0822:                            } else {
0823:                                Method fm = Reflect.getMethod(ac, "create",
0824:                                        stringArgSpec);
0825:                                if (fm == null) {
0826:                                    String n = ac.getName();
0827:                                    // remove the package prefix
0828:                                    n = n.substring(n.lastIndexOf('.') + 1);
0829:                                    fm = Reflect.getMethod(ac, "create" + n,
0830:                                            stringArgSpec);
0831:                                    if (fm == null)
0832:                                        fm = Reflect.getMethod(ac, "get" + n,
0833:                                                stringArgSpec);
0834:                                }
0835:                                if (fm == null) {
0836:                                    throw new RuntimeException(
0837:                                            "Couldn't figure out how to construct "
0838:                                                    + type);
0839:                                }
0840:                                return fm.invoke(null, args);
0841:                            }
0842:                        }
0843:                    } catch (Exception e) {
0844:                        System.err
0845:                                .println("OrgRTDataPlugin: Exception constructing "
0846:                                        + type + " from \"" + arg + "\":");
0847:                        e.printStackTrace();
0848:                        throw new RuntimeException("Construction problem " + e);
0849:                    }
0850:                }
0851:            }
0852:
0853:            private static Class[] stringArgSpec = { String.class };
0854:
0855:            private static Class[][] argClasses = {
0856:                    { Integer.TYPE, Integer.class },
0857:                    { Double.TYPE, Double.class },
0858:                    { Boolean.TYPE, Boolean.class },
0859:                    { Float.TYPE, Float.class }, { Long.TYPE, Long.class },
0860:                    { Short.TYPE, Short.class }, { Byte.TYPE, Byte.class },
0861:                    { Character.TYPE, Character.class } };
0862:
0863:            private static Class getArgClass(Class c) {
0864:                if (!c.isPrimitive())
0865:                    return c;
0866:                for (int i = 0; i < argClasses.length; i++) {
0867:                    if (c == argClasses[i][0])
0868:                        return argClasses[i][1];
0869:                }
0870:                throw new IllegalArgumentException("Class " + c
0871:                        + " is an unknown primitive.");
0872:            }
0873:
0874:            private String getType(String type) {
0875:                int i;
0876:                if ((i = type.indexOf("<")) > -1) { // deal with collections 
0877:                    int j = type.lastIndexOf(">");
0878:                    return getType(type.substring(0, i)); // deal with measures
0879:                } else if ((i = type.indexOf("/")) > -1) {
0880:                    return getType(type.substring(0, i));
0881:                } else {
0882:                    return type;
0883:                }
0884:            }
0885:
0886:            protected Object parseWithCOF(Class cl, String val) {
0887:                String name = cl.getName();
0888:                int dot = name.lastIndexOf('.');
0889:                if (dot != -1)
0890:                    name = name.substring(dot + 1);
0891:
0892:                try {
0893:                    // lookup method on ldmf
0894:                    Object o = callFactoryMethod(name);
0895:
0896:                    Vector svs = org.cougaar.util.StringUtility.parseCSV(val);
0897:                    // svs should be a set of strings like "slot=value" or "slot=type value"
0898:                    for (Enumeration sp = svs.elements(); sp.hasMoreElements();) {
0899:                        String ss = (String) sp.nextElement();
0900:
0901:                        int eq = ss.indexOf('=');
0902:                        String slotname = ss.substring(0, eq);
0903:                        String vspec = ss.substring(eq + 1);
0904:
0905:                        int spi = vspec.indexOf(' ');
0906:                        Object v;
0907:                        if (spi == -1) {
0908:                            v = vspec;
0909:                        } else {
0910:                            String st = vspec.substring(0, spi);
0911:                            String sv = vspec.substring(spi + 1);
0912:                            v = parseExpr(st, sv);
0913:                        }
0914:                        callSetMethod(o, slotname, v);
0915:                    }
0916:                    return o;
0917:                } catch (Exception e) {
0918:                    e.printStackTrace();
0919:                    return null;
0920:                }
0921:            }
0922:
0923:            private Object callFactoryMethod(String ifcname) {
0924:                // look up a zero-arg factory method in the ldmf
0925:                String newname = "new" + ifcname;
0926:
0927:                // try the COUGAAR factory
0928:                try {
0929:                    Class ldmfc = aldmf.getClass();
0930:                    Method fm = ldmfc.getMethod(newname, nullClassList);
0931:                    return fm.invoke(aldmf, nullArgList);
0932:                } catch (Exception e) {
0933:                    e.printStackTrace();
0934:                }
0935:
0936:                // try the main factory
0937:                try {
0938:                    Class ldmfc = getFactory().getClass();
0939:                    Method fm = ldmfc.getMethod(newname, nullClassList);
0940:                    return fm.invoke(getFactory(), nullArgList);
0941:                } catch (Exception e) {
0942:                }
0943:                throw new RuntimeException(
0944:                        "Couldn't find a factory method for " + ifcname);
0945:            }
0946:
0947:            private static final Class nullClassList[] = {};
0948:            private static final Object nullArgList[] = {};
0949:
0950:            private void callSetMethod(Object o, String slotname, Object value) {
0951:                Class oc = o.getClass();
0952:                String setname = "set" + slotname;
0953:                Class vc = value.getClass();
0954:
0955:                try {
0956:                    Method ms[] = Reflect.getMethods(oc);
0957:                    for (int i = 0; i < ms.length; i++) {
0958:                        Method m = ms[i];
0959:                        if (setname.equals(m.getName())) {
0960:                            Class mps[] = m.getParameterTypes();
0961:                            if (mps.length == 1 && mps[0].isAssignableFrom(vc)) {
0962:                                Object args[] = { value };
0963:                                m.invoke(o, args);
0964:                                return;
0965:                            }
0966:                        }
0967:                    }
0968:                } catch (Exception e) {
0969:                    throw new RuntimeException("Couldn't find set" + slotname
0970:                            + " for " + o + ", value " + value);
0971:                }
0972:
0973:                throw new RuntimeException("Couldn't find set" + slotname
0974:                        + " for " + o + ", value " + value);
0975:            }
0976:
0977:            /**
0978:             * Creates the property, fills in the slots based on what's in the prototype-ini file
0979:             * and then sets it for (or adds it to) the organization
0980:             */
0981:            protected int setPropertyForOrganization(Organization org,
0982:                    String prop, int newVal, StreamTokenizer tokens) {
0983:                String propertyName = prop.substring(1, prop.length() - 1);
0984:                if (org != null) {
0985:                    NewPropertyGroup property = null;
0986:                    try {
0987:                        property = (NewPropertyGroup) getFactory()
0988:                                .createPropertyGroup(propertyName);
0989:                    } catch (Exception e) {
0990:                        System.err
0991:                                .println("OrgRTDataPlugin: Unrecognized keyword for a prototype-ini file: ["
0992:                                        + propertyName + "]");
0993:                    }
0994:                    try {
0995:                        newVal = tokens.nextToken();
0996:                        String member = tokens.sval;
0997:                        String propName = "New" + propertyName;
0998:                        // Parse through the property section of the file
0999:                        while (newVal != StreamTokenizer.TT_EOF) {
1000:                            if ((tokens.ttype == StreamTokenizer.TT_WORD)
1001:                                    && !(tokens.sval.substring(0, 1)
1002:                                            .equals("["))) {
1003:                                newVal = tokens.nextToken();
1004:                                String dataType = tokens.sval;
1005:                                newVal = tokens.nextToken();
1006:                                // Call appropriate setters for the slots of the property
1007:                                Object arg = parseExpr(dataType, tokens.sval);
1008:
1009:                                createAndCallSetter(property, propName, "set"
1010:                                        + member, getType(dataType), arg);
1011:                                newVal = tokens.nextToken();
1012:                                member = tokens.sval;
1013:                            } else {
1014:                                // Reached a left bracket "[", want to exit block
1015:                                break;
1016:                            }
1017:                        } //while
1018:
1019:                        // Add the property to the organization
1020:                        try {
1021:                            // if a setter already exists for the property (such as setTypeIdentificationPG)
1022:                            // then use it
1023:                            Class propertyClass = Organization.class;
1024:                            Class parameters[] = new Class[] { PropertyGroup.class };
1025:                            Method meth = propertyClass.getMethod("set"
1026:                                    + propertyName, parameters);
1027:                            Object arguments[] = new Object[] { property };
1028:                            meth.invoke(org, arguments);
1029:                        } catch (NoSuchMethodException nsme) {
1030:                            // else call addOtherPropertyGroup
1031:                            org.addOtherPropertyGroup(property);
1032:                        } catch (Exception e) {
1033:                            e.printStackTrace();
1034:                        }
1035:                    } catch (Exception e) {
1036:                        e.printStackTrace();
1037:                    }
1038:                } else {
1039:                    System.err.println("OrgRTDataPlugin Error: org is null");
1040:                }
1041:                return newVal;
1042:            }
1043:
1044:            /**
1045:             * Fills in the organization_vector with arrays of relationship, agentName and capableroles triples.
1046:             */
1047:            protected int FillOrganizationVector(Organization org, int newVal,
1048:                    StreamTokenizer tokens, String relationship) {
1049:                organization_vector.removeAllElements(); // Clear out the organization_vector
1050:
1051:                int x = 0;
1052:                if (org != null) {
1053:                    try {
1054:                        while (newVal != StreamTokenizer.TT_EOF) {
1055:                            String organization_array[] = new String[5]; // An array of relationship, agentName and capableroles triples
1056:                            newVal = tokens.nextToken();
1057:                            // Parse [Relationship] part of prototype-ini file
1058:                            if ((tokens.ttype == StreamTokenizer.TT_WORD)
1059:                                    && !(tokens.sval.substring(0, 1)
1060:                                            .equals("["))) {
1061:                                organization_array[0] = tokens.sval;
1062:                                newVal = tokens.nextToken();
1063:                                organization_array[1] = tokens.sval;
1064:                                newVal = tokens.nextToken();
1065:                                organization_array[2] = tokens.sval;
1066:                                // Only add to the organization_vector if
1067:                                // the relationship is SELF
1068:                                if (relationship.equals(GLMRelationship.SELF))
1069:                                    organization_vector
1070:                                            .addElement(organization_array);
1071:                            } else {
1072:                                // Reached a left bracket "[", want to exit block
1073:                                break;
1074:                            }
1075:                            x++;
1076:                        } //while
1077:                    } catch (Exception e) {
1078:                        e.printStackTrace();
1079:                    }
1080:                } else {
1081:                    System.out.println("OrgRTDataPlugin Error: org is null");
1082:                }
1083:
1084:                return newVal;
1085:            }
1086:
1087:            /**
1088:             * Returns the integer value for the appropriate
1089:             * unitOfMeasure field in the measureClass
1090:             */
1091:            protected int getMeasureUnit(String measureClass,
1092:                    String unitOfMeasure) {
1093:                try {
1094:                    String fullClassName = "org.cougaar.planning.ldm.measure."
1095:                            + measureClass;
1096:                    Field f = Class.forName(fullClassName).getField(
1097:                            unitOfMeasure);
1098:                    return f.getInt(null);
1099:                } catch (Exception e) {
1100:                    System.err
1101:                            .println("OrgRTDataPlugin Exception: for measure unit: "
1102:                                    + unitOfMeasure);
1103:                    e.printStackTrace();
1104:                }
1105:                return -1;
1106:            }
1107:
1108:            /**
1109:             * Returns a measure object which is an instance of className and has
1110:             * a quantity of unitOfMeasure
1111:             */
1112:            protected Object createMeasureObject(String className,
1113:                    double quantity, String unitOfMeasure) {
1114:                try {
1115:                    Class classObj = Class
1116:                            .forName("org.cougaar.planning.ldm.measure."
1117:                                    + className);
1118:                    String methodName = "new" + className;
1119:                    Class parameters[] = { double.class, int.class };
1120:                    Method meth = classObj.getMethod(methodName, parameters);
1121:                    Object arguments[] = {
1122:                            new Double(quantity),
1123:                            new Integer(
1124:                                    getMeasureUnit(className, unitOfMeasure)) };
1125:                    return meth.invoke(classObj, arguments); // static method call
1126:                } catch (Exception e) {
1127:                    e.printStackTrace();
1128:                }
1129:                return null;
1130:            }
1131:
1132:            private static HashMap classes;
1133:            protected static final Collection packages;
1134:
1135:            static {
1136:                // initialize packages:
1137:                packages = new ArrayList();
1138:                packages.add("org.cougaar.glm.ldm.asset");
1139:                packages.add("org.cougaar.glm.ldm.plan");
1140:                packages.add("org.cougaar.glm.ldm.oplan");
1141:                packages.add("org.cougaar.glm.ldm.policy");
1142:
1143:                packages.add("org.cougaar.planning.ldm.measure");
1144:                packages.add("org.cougaar.planning.ldm.plan");
1145:                packages.add("org.cougaar.planning.ldm.asset");
1146:                packages.add("org.cougaar.planning.ldm.oplan");
1147:
1148:                packages.add("java.lang"); // extras for fallthrough
1149:                packages.add("java.util");
1150:
1151:                // initialize the classmap with some common ones
1152:                classes = new HashMap();
1153:
1154:                classes.put("MessageAddress", MessageAddress.class);
1155:
1156:                // precache some builtins
1157:                classes.put("long", Long.TYPE);
1158:                classes.put("int", Integer.TYPE);
1159:                classes.put("integer", Integer.TYPE);
1160:                classes.put("boolean", Boolean.TYPE);
1161:                classes.put("float", Float.TYPE);
1162:                classes.put("double", Double.TYPE);
1163:                // and some java.lang
1164:                classes.put("Double", Double.class);
1165:                classes.put("String", String.class);
1166:                classes.put("Integer", Integer.class);
1167:                // and some java.util
1168:                classes.put("Collection", Collection.class);
1169:                classes.put("List", List.class);
1170:                // COUGAAR-specific stuff will be looked for
1171:            }
1172:
1173:            private Class findClass(String name) {
1174:                synchronized (classes) {
1175:                    Class c = (Class) classes.get(name);
1176:                    // try the cache
1177:                    if (c != null)
1178:                        return c;
1179:
1180:                    for (Iterator i = packages.iterator(); i.hasNext();) {
1181:                        String pkg = (String) i.next();
1182:                        try { // Oh so ugly!
1183:                            c = Class.forName(pkg + "." + name);
1184:                            if (c != null) { // silly
1185:                                classes.put(name, c);
1186:                                return c;
1187:                            }
1188:                        } catch (ClassNotFoundException e) {
1189:                        }
1190:                        ; // sigh
1191:                    }
1192:                    throw new RuntimeException("Could not find a class for '"
1193:                            + name + "'.");
1194:                }
1195:            }
1196:
1197:            /**
1198:             * Creates and calls the appropriate "setter" method for the classInstance
1199:             * which is of type className.
1200:             */
1201:            protected void createAndCallSetter(Object classInstance,
1202:                    String className, String setterName, String type,
1203:                    Object value) {
1204:                Class parameters[] = new Class[1];
1205:                Object arguments[] = new Object[] { value };
1206:
1207:                try {
1208:                    parameters[0] = findClass(type);
1209:                    Class propertyClass = findClass(className);
1210:                    //Method meth = propertyClass.getMethod(setterName, parameters);
1211:                    Method meth = findMethod(propertyClass, setterName,
1212:                            parameters);
1213:                    meth.invoke(classInstance, arguments);
1214:                } catch (Exception e) {
1215:                    System.err
1216:                            .println("OrgRTPlugin Exception: createAndCallSetter("
1217:                                    + classInstance.getClass().getName()
1218:                                    + ", "
1219:                                    + className
1220:                                    + ", "
1221:                                    + setterName
1222:                                    + ", "
1223:                                    + type + ", " + value + " : " + e);
1224:                    e.printStackTrace();
1225:                }
1226:            }
1227:
1228:            private static Method findMethod(Class c, String name,
1229:                    Class params[]) {
1230:                Method ms[] = Reflect.getMethods(c);
1231:                int pl = params.length;
1232:                for (int i = 0; i < ms.length; i++) {
1233:                    Method m = ms[i];
1234:                    if (name.equals(m.getName())) {
1235:                        Class mps[] = m.getParameterTypes();
1236:                        if (mps.length == pl) {
1237:                            int j;
1238:                            for (j = 0; j < pl; j++) {
1239:                                if (!(mps[j].isAssignableFrom(params[j])))
1240:                                    break; // j loop
1241:                            }
1242:                            if (j == pl) // all passed
1243:                                return m;
1244:                        }
1245:                    }
1246:                }
1247:                return null;
1248:            }
1249:
1250:            /** 
1251:             * This is not very straight forward due to the way classes were set up
1252:             * The goal is to add a GeolocLocation to an Organization
1253:             * 1) Organizations have an AssignmentPG
1254:             * 2) AssignmentPG contains a Facility object, which is the super
1255:             *    class of the TransportationNode object
1256:             * 3) TransportationNode objects have a PositionPG
1257:             * 4) PositionPG contains a Position object, which is the super
1258:             *    class of the GeolocLocation object
1259:             */
1260:
1261:            /**
1262:             * Creates the Position, fills in the slots based on what's in the prototype-ini file
1263:             * and then sets it for (or adds it to) the organization
1264:             */
1265:            protected int setAssignmentForOrganization(Organization org,
1266:                    String prop, int newVal, StreamTokenizer tokens) {
1267:                if (org != null) {
1268:                    NewGeolocLocation geoloc = aldmf.newGeolocLocation();
1269:                    String geolocClassName = "NewGeolocLocation";
1270:
1271:                    try {
1272:                        newVal = tokens.nextToken();
1273:                        String member = tokens.sval;
1274:                        // Parse through the property section of the file
1275:                        while (newVal != StreamTokenizer.TT_EOF) {
1276:                            if ((tokens.ttype == StreamTokenizer.TT_WORD)
1277:                                    && !(tokens.sval.substring(0, 1)
1278:                                            .equals("["))) {
1279:                                newVal = tokens.nextToken();
1280:                                String dataType = tokens.sval;
1281:
1282:                                newVal = tokens.nextToken();
1283:                                // Call appropriate setters for the slots of the property
1284:                                if (dataType.equals("String")) {
1285:                                    createAndCallSetter(geoloc,
1286:                                            geolocClassName, "set" + member,
1287:                                            dataType, tokens.sval);
1288:                                } else {
1289:                                    try {
1290:                                        // If it's a measure class, create the appropriate measure object,
1291:                                        // and call setter with that as one of the parameters
1292:                                        Class
1293:                                                .forName("org.cougaar.planning.ldm.measure."
1294:                                                        + dataType);
1295:                                        double qty = ((tokens.ttype == StreamTokenizer.TT_NUMBER) ? tokens.nval
1296:                                                : Double
1297:                                                        .parseDouble(tokens.sval));
1298:                                        newVal = tokens.nextToken();
1299:                                        Object o = createMeasureObject(
1300:                                                dataType, qty, tokens.sval);
1301:                                        createAndCallSetter(geoloc,
1302:                                                geolocClassName,
1303:                                                "set" + member, dataType, o);
1304:                                    } catch (Exception e) {
1305:                                        // else it is not a datatype we handle
1306:                                        System.err
1307:                                                .println("OrgRTDataPlugin: Incorrect datatype: "
1308:                                                        + dataType);
1309:                                        e.printStackTrace();
1310:                                    }
1311:                                }
1312:                                newVal = tokens.nextToken();
1313:                                member = tokens.sval;
1314:                            } else {
1315:                                // Reached a left bracket "[", want to exit block
1316:                                break;
1317:                            }
1318:                        } //while
1319:
1320:                        // Add the property to the organization
1321:                        NewAssignmentPG assignProp = (NewAssignmentPG) org
1322:                                .getAssignmentPG();
1323:                        TransportationNode tn = (TransportationNode) assignProp
1324:                                .getHomeStation();
1325:                        if (tn == null) { // There are no NewFacility or NewTransportationNode objects
1326:                            tn = (TransportationNode) getFactory().createAsset(
1327:                                    TransportationNode.class);
1328:                        }
1329:                        NewPositionPG posProp = (NewPositionPG) getFactory()
1330:                                .createPropertyGroup(PositionPGImpl.class);
1331:                        posProp.setPosition((NewPosition) geoloc);
1332:                        tn.setPositionPG(posProp);
1333:                        assignProp.setHomeStation((Facility) tn);
1334:                        org.setAssignmentPG(assignProp);
1335:
1336:                        // set up the home location element of the locationpg
1337:                        {
1338:                            // get the pg
1339:                            LocationSchedulePG lspg = org
1340:                                    .getLocationSchedulePG();
1341:                            if (lspg == null) {
1342:                                org
1343:                                        .setLocationSchedulePG(lspg = new LocationSchedulePGImpl());
1344:                            }
1345:
1346:                            // get the schedule
1347:                            Schedule ls = lspg.getSchedule();
1348:                            if (ls == null) {
1349:                                ls = theLDMF
1350:                                        .newLocationSchedule(EmptyEnumeration
1351:                                                .getEnumeration());
1352:                                ((NewLocationSchedulePG) lspg).setSchedule(ls);
1353:                            }
1354:
1355:                            // now that we have it, lock it so nobody bashes it
1356:                            synchronized (ls) {
1357:                                /*
1358:                                ls.add(new LocationScheduleElementImpl(TimeSpan.MIN_VALUE, 
1359:                                                                       TimeSpan.MAX_VALUE,
1360:                                                                       geoloc));
1361:                                 */
1362:                                ls.add(new HomeLocationScheduleElement(geoloc));
1363:                            }
1364:                        }
1365:                    } catch (Exception e) {
1366:                        e.printStackTrace();
1367:                    }
1368:                } else {
1369:                    System.err.println("OrgRTDataPlugin Error: org is null");
1370:                }
1371:                return newVal;
1372:            }
1373:
1374:            public static class HomeLocationScheduleElement extends
1375:                    TaggedLocationScheduleElement {
1376:                public HomeLocationScheduleElement(Location l) {
1377:                    super (TimeSpan.MIN_VALUE, TimeSpan.MAX_VALUE, l);
1378:                }
1379:
1380:                /** @return the string "HOME" to indicate that this is the home location
1381:                 * of the organization.
1382:                 **/
1383:                public Object getOwner() {
1384:                    return "HOME";
1385:                }
1386:
1387:            }
1388:
1389:            private static class TrivialTimeSpan implements  TimeSpan {
1390:                long myStart;
1391:                long myEnd;
1392:
1393:                public TrivialTimeSpan(long start, long end) {
1394:                    myStart = start;
1395:                    myEnd = end;
1396:                }
1397:
1398:                public long getStartTime() {
1399:                    return myStart;
1400:                }
1401:
1402:                public long getEndTime() {
1403:                    return myEnd;
1404:                }
1405:            }
1406:
1407:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.