001: /*
002: * <copyright>
003: *
004: * Copyright 2002-2004 BBNT Solutions, LLC
005: * under sponsorship of the Defense Advanced Research Projects
006: * Agency (DARPA).
007: *
008: * You can redistribute this software and/or modify it under the
009: * terms of the Cougaar Open Source License as published on the
010: * Cougaar Open Source Website (www.cougaar.org).
011: *
012: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
013: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
014: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
015: * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
016: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
017: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
018: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
019: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
020: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
021: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
022: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
023: *
024: * </copyright>
025: */
026:
027: package org.cougaar.core.adaptivity;
028:
029: import java.io.PrintWriter;
030: import java.io.StringReader;
031: import java.lang.reflect.Constructor;
032: import java.util.Collection;
033: import java.util.Collections;
034: import java.util.Comparator;
035: import java.util.Iterator;
036: import java.util.List;
037: import java.util.TreeSet;
038:
039: import javax.servlet.http.HttpServletRequest;
040: import javax.servlet.http.HttpServletResponse;
041:
042: import org.cougaar.core.blackboard.BlackboardClient;
043: import org.cougaar.core.service.BlackboardQueryService;
044: import org.cougaar.core.service.BlackboardService;
045: import org.cougaar.core.service.LoggingService;
046: import org.cougaar.core.servlet.ComponentServlet;
047: import org.cougaar.util.UnaryPredicate;
048:
049: /**
050: * Servlet to view adaptivity objects and edit operating mode policies
051: */
052: public class AEViewerServlet extends ComponentServlet implements
053: BlackboardClient {
054:
055: public static final String FRAME = "frame";
056: public static final String AE_FRAME = "ae";
057:
058: public static final String OPERATINGMODE = "OperatingMode";
059: public static final String POLICY = "Policy";
060: public static final String CHANGE = "change";
061: public static final String UID = "uid";
062: public static final String NAME = "name";
063: public static final String KERNEL = "kernel";
064: public static final String VALUE = "value";
065:
066: private LoggingService logger = LoggingService.NULL;
067: private BlackboardQueryService blackboardQuery;
068: private BlackboardService blackboard;
069:
070: private OMComparator omComparator = new OMComparator();
071: private OMPComparator ompComparator = new OMPComparator();
072:
073: private static UnaryPredicate conditionPredicate = new UnaryPredicate() {
074: public boolean execute(Object o) {
075: if (o instanceof Condition) {
076: return true;
077: }
078: return false;
079: }
080: };
081:
082: private static UnaryPredicate omPredicate = new UnaryPredicate() {
083: public boolean execute(Object o) {
084: if (o instanceof OperatingMode) {
085: return true;
086: }
087: return false;
088: }
089: };
090:
091: private static UnaryPredicate omPolicyPredicate = new UnaryPredicate() {
092: public boolean execute(Object o) {
093: if (o instanceof OperatingModePolicy) {
094: return true;
095: }
096: return false;
097: }
098: };
099:
100: public void setLoggingService(LoggingService logger) {
101: if (logger != null) {
102: this .logger = logger;
103: }
104: }
105:
106: public void setBlackboardQueryService(
107: BlackboardQueryService blackboardQuery) {
108: this .blackboardQuery = blackboardQuery;
109: }
110:
111: public void setBlackboardService(BlackboardService blackboard) {
112: this .blackboard = blackboard;
113: }
114:
115: public String getBlackboardClientName() {
116: return getPath();
117: }
118:
119: public long currentTimeMillis() {
120: return -1; // N/A
121: }
122:
123: public void unload() {
124: if (blackboard != null) {
125: serviceBroker.releaseService(this , BlackboardService.class,
126: blackboard);
127: blackboard = null;
128: }
129: if (blackboardQuery != null) {
130: serviceBroker.releaseService(this ,
131: BlackboardQueryService.class, blackboardQuery);
132: blackboardQuery = null;
133: }
134: if (logger != LoggingService.NULL) {
135: serviceBroker.releaseService(this , LoggingService.class,
136: logger);
137: logger = LoggingService.NULL;
138: }
139: super .unload();
140: }
141:
142: public void doGet(HttpServletRequest request,
143: HttpServletResponse response) {
144: String frame = request.getParameter(FRAME);
145: response.setContentType("text/html");
146: try {
147: PrintWriter out = response.getWriter();
148: if (!(AE_FRAME.equals(frame))) {
149: // generate outer frame page
150: writeTopFrame(out);
151: } else {
152: // generate real AE frame
153: String objectType = request.getParameter(CHANGE);
154: if (objectType != null) {
155: if (objectType.equals(POLICY)) {
156: changePolicy(request, out);
157: } else if (objectType.equals(OPERATINGMODE)) {
158: changeOperatingMode(request, out);
159: }
160: } else {
161: /* send adaptivity objects */
162: sendData(out);
163: }
164: }
165: out.close();
166: } catch (java.io.IOException ie) {
167: ie.printStackTrace();
168: }
169: }
170:
171: private void changePolicy(HttpServletRequest request,
172: PrintWriter out) {
173:
174: String uid = request.getParameter(UID);
175:
176: // get the string representing the policy
177: String policyString = request.getParameter(KERNEL);
178: StringReader reader = new StringReader(policyString);
179: OperatingModePolicy[] policies = null;
180: try {
181: // Use the parser to create a new policy
182: Parser parser = new Parser(reader, logger);
183: policies = parser.parseOperatingModePolicies();
184: } catch (java.io.IOException ioe) {
185: ioe.printStackTrace();
186: } finally {
187: reader.close();
188: }
189:
190: // find the existing policy on the blackboard
191: Collection blackboardCollection = blackboardQuery
192: .query(new UIDPredicate(uid));
193: OperatingModePolicy bbPolicy = (OperatingModePolicy) blackboardCollection
194: .iterator().next();
195:
196: // set the existing policy's kernel to be that of the newly
197: // parsed policy
198: bbPolicy.setPolicyKernel(policies[0].getPolicyKernel());
199:
200: blackboard.openTransaction();
201: // write the updated policy to the blackboard
202: blackboard.publishChange(bbPolicy);
203: blackboard.closeTransaction();
204:
205: out
206: .println("<html><head></head><body><h2>Policy Changed</h2><br>");
207: out.println(bbPolicy.toString());
208: }
209:
210: private void changeOperatingMode(HttpServletRequest request,
211: PrintWriter out) {
212:
213: // get the string representing the operating mode
214: String omName = request.getParameter(NAME);
215: // find the existing operating mode on the blackboard
216: Collection blackboardCollection = blackboardQuery
217: .query(new OMByNamePredicate(omName));
218: OperatingMode bbOM = (OperatingMode) blackboardCollection
219: .iterator().next();
220:
221: String newValue = request.getParameter(VALUE);
222:
223: Class omClass = bbOM.getValue().getClass();
224:
225: // Is it a String?
226: try {
227: if (omClass == String.class) {
228: // set it and be done with it.
229: bbOM.setValue(newValue);
230: } else {
231: // If not, hope that whatever it is has a String constructor
232: Constructor cons = null;
233: try {
234: cons = omClass
235: .getConstructor(new Class[] { String.class });
236: } catch (NoSuchMethodException nsme) {
237: System.err
238: .println("AEViewerServlet: Error, no String constructor for OperatingMode containing class "
239: + omClass + " " + nsme);
240: out
241: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
242: out
243: .println("There is no String constructor for OperatingMode containing class "
244: + omClass + " " + nsme);
245: return;
246: } catch (RuntimeException re) {
247: out
248: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
249: out.println(re);
250: return;
251: }
252:
253: if (cons != null) {
254: // Make a new one of whatever it is and set OM value
255: Comparable newThing = (Comparable) cons
256: .newInstance((Object[]) new String[] { newValue });
257: bbOM.setValue(newThing);
258: } else {
259: out
260: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
261: out.print("Can't set ");
262: out.print(bbOM.getName());
263: out.print("to " + newValue);
264: out.println("<br>No constructor " + omClass
265: + "(String)");
266: }
267: }
268: } catch (IllegalArgumentException iae) {
269: out
270: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
271: out.print(newValue);
272: out.print(" is not a valid value for ");
273: out.println(bbOM.getName());
274: out.print("<br>");
275: out.println(iae);
276: return;
277: } catch (java.lang.reflect.InvocationTargetException ite) {
278: out
279: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
280: out.print(newValue);
281: out.print(" is not a valid value for ");
282: out.println(bbOM.getName());
283: out.print("<br>");
284: out.println(ite);
285: return;
286: } catch (InstantiationException ie) {
287: out
288: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
289: out.print(ie);
290: return;
291: } catch (IllegalAccessException iae) {
292: out
293: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
294: out.print(iae);
295: return;
296: } catch (RuntimeException re) {
297: out
298: .println("<html><head></head><body><h2>ERROR - OperatingMode Not Changed</h2><br>");
299: out.print(re);
300: return;
301: }
302:
303: blackboard.openTransaction();
304: // write the updated operating mode to the blackboard
305: blackboard.publishChange(bbOM);
306: blackboard.closeTransaction();
307:
308: out
309: .println("<html><head></head><body><h2>OperatingMode Changed</h2><br>");
310: out.println(bbOM.toString());
311: }
312:
313: /**
314: * Suck the Policies, Conditions, and Operating Modes out of the
315: * blackboard and send them to the requestor
316: */
317: private void sendData(PrintWriter out) {
318: out.println("<html><head></head><body>");
319:
320: writeAgentSelector(out);
321:
322: writeConditions(out);
323:
324: out.println("<h2><CENTER>Operating Modes</CENTER></h2>");
325: writeOMTable(out);
326:
327: out
328: .print("<H2><CENTER>Operating Mode Policies</CENTER></H2><P>\n");
329: writePolicyTable(out);
330: }
331:
332: private void writeTopFrame(PrintWriter out) {
333: // generate outer frame page:
334: // top: select "/agent"
335: // bottom: real AE frame
336: out.print("<html><head><title>AE Viewer</title></head>"
337: + "<frameset rows=\"10%,90%\">\n" + "<frame src=\""
338: + "/agents?format=select&suffix="
339: + getEncodedAgentName() + "\" name=\"agentFrame\">\n"
340: + "<frame src=\"/$" + getEncodedAgentName() + getPath()
341: + "?" + FRAME + "=" + AE_FRAME + "\" name=\""
342: + AE_FRAME + "\">\n" + "</frameset>\n"
343: + "<noframes>Please enable frame support</noframes>"
344: + "</html>\n");
345: }
346:
347: private void writeAgentSelector(PrintWriter out) {
348:
349: out
350: .print("<script language=\"JavaScript\">\n"
351: + "<!--\n"
352: + "function mySubmit() {\n"
353: + " var obj = top.agentFrame.document.agent.name;\n"
354: + " var encAgent = obj.value;\n"
355: + " if (encAgent.charAt(0) == '.') {\n"
356: + " alert(\"Please select an agent name\")\n"
357: + " return false;\n"
358: + " }\n"
359: + " document.myForm.target=\""
360: + AE_FRAME
361: + "\"\n"
362: + " document.myForm.action=\"/$\"+encAgent+\""
363: + getPath()
364: + "\"\n"
365: + " return true\n"
366: + "}\n"
367: + "// -->\n"
368: + "</script>\n"
369: + "<h2><center>Adaptivity Viewer at "
370: + getEncodedAgentName()
371: + "</center></h2>\n"
372: + "<form name=\"myForm\" method=\"get\" "
373: + "onSubmit=\"return mySubmit()\">\n"
374: + "<input type=hidden name=\""
375: + FRAME
376: + "\" value=\""
377: + AE_FRAME
378: + "\">\n"
379: + "Select an agent above, <input type=submit name=\"formSubmit\" value=\"Reload\">"
380: + "<br>\n</form>");
381: }
382:
383: /**
384: * Creates a sorted HTML list of the conditions in the blackboard
385: **/
386: private void writeConditions(PrintWriter out) {
387: out.println("<h2><CENTER>Conditions</CENTER></h2><br>");
388: Collection conditions = blackboardQuery
389: .query(conditionPredicate);
390:
391: // Sort the Conditions. Is there a better way of doing this?
392: TreeSet sortedConditions = new TreeSet();
393: for (Iterator it = conditions.iterator(); it.hasNext();) {
394: sortedConditions.add(it.next().toString());
395: }
396: out.print("<UL>");
397: for (Iterator it = sortedConditions.iterator(); it.hasNext();) {
398: out.print("<LI>");
399: out.println(it.next().toString());
400: }
401: out.println("</UL>");
402: }
403:
404: /**
405: * Create a HTML table with a form in each row for editing a policy
406: */
407: private void writeOMTable(PrintWriter out) {
408: out.println("<table>");
409: out
410: .println("<tr><th>OperatingMode Name</th><th>Valid Values</th><th>Value</th></tr>");
411:
412: // Sort the OperatingModes
413: List oms = (List) blackboardQuery.query(omPredicate);
414: try {
415: Collections.sort(oms, omComparator);
416: } catch (ClassCastException e) {
417: e.printStackTrace();
418: }
419:
420: for (Iterator it = oms.iterator(); it.hasNext();) {
421:
422: out.print("<FORM METHOD=\"GET\" ACTION=\"/$");
423: out.print(getEncodedAgentName());
424: out.print(getPath());
425: out.println("\"><input type=hidden name=\"" + FRAME
426: + "\" value=\"" + AE_FRAME + "\">\n");
427:
428: OperatingMode om = (OperatingMode) it.next();
429:
430: out.print("<td>");
431: out.print(om.getName());
432: out.println("</td>");
433:
434: out.print("<td>");
435: out.print(om.getAllowedValues().toString());
436: out.println("</td>");
437:
438: out.print("<td>");
439: out.print("<INPUT TYPE=text NAME=");
440: out.print(VALUE);
441: out.print(" VALUE=\"");
442: out.print(om.getValue().toString());
443: out.print("\"SIZE=20>");
444: out.println("</td>");
445:
446: out
447: .print("<td> <INPUT TYPE=submit value=\"Submit\"> </td>");
448:
449: out.print("<tr> <td><INPUT TYPE=hidden NAME=");
450: out.print(CHANGE);
451: out.print(" VALUE=\"");
452: out.print(OPERATINGMODE);
453: out.println("\"</td>");
454:
455: out.print("<td>");
456: out.print("<INPUT TYPE=hidden NAME=");
457: out.print(NAME);
458: out.print(" VALUE=\"");
459: out.print(om.getName());
460: out.println("\"> </td> </tr>");
461: out.println("</form>");
462: }
463: out.println("</table>");
464: }
465:
466: /**
467: * Create a HTML table with a form in each row for editing a policy
468: */
469: private void writePolicyTable(PrintWriter out) {
470: out.println("<table>\n");
471: out
472: .println("<tr><th>Name</th><th>Authority</th><th>UID</th><th>Kernel</th></tr>");
473:
474: // Sort the OperatingModePolicies
475: List policies = (List) blackboardQuery.query(omPolicyPredicate);
476: try {
477: Collections.sort(policies, ompComparator);
478: } catch (ClassCastException e) {
479: e.printStackTrace();
480: }
481:
482: for (Iterator it = policies.iterator(); it.hasNext();) {
483:
484: out.print("<FORM METHOD=\"GET\" ACTION=\"/$"
485: + getEncodedAgentName() + getPath()
486: + "\" target=\"" + AE_FRAME + "\">\n"
487: + "<input type=hidden name=\"" + FRAME
488: + "\" value=\"" + AE_FRAME + "\">\n");
489:
490: OperatingModePolicy omp = (OperatingModePolicy) it.next();
491: out.println("<tr> <td>");
492: out.print(omp.getName());
493: out.println("</td><td>");
494: out.println(omp.getAuthority());
495: out.println("</td><td>");
496: out.print(omp.getUID());
497: out.println("</td>");
498:
499: out.print("<td> <INPUT TYPE=\"text\" NAME=");
500: out.print(KERNEL);
501: out.print(" VALUE=\"");
502: out.print(omp.getPolicyKernel().toString());
503: out.print(";\"SIZE=80> </td>");
504:
505: out
506: .println("<td> <input type=submit value=\"Submit\"></td></tr>");
507:
508: out.print("<td> <INPUT TYPE=hidden NAME=");
509: out.print(CHANGE);
510: out.print(" VALUE=\"");
511: out.print(POLICY);
512: out.println("\" <td>");
513:
514: out.print("<td> <INPUT TYPE=hidden NAME=");
515: out.print(UID);
516: out.print(" VALUE=\"");
517: out.print(omp.getUID());
518: out.print("\" </td>");
519:
520: out.println("</form>");
521: }
522: out.println("</table></body></html>");
523: }
524:
525: private class UIDPredicate implements UnaryPredicate {
526: String uid;
527:
528: public UIDPredicate(String uidString) {
529: uid = uidString;
530: }
531:
532: public boolean execute(Object o) {
533: if (o instanceof OperatingModePolicy) {
534: OperatingModePolicy omp = (OperatingModePolicy) o;
535: if (uid.equals(omp.getUID().toString())) {
536: return true;
537: }
538: }
539: return false;
540: }
541: }
542:
543: private class OMByNamePredicate implements UnaryPredicate {
544: String name;
545:
546: public OMByNamePredicate(String omName) {
547: name = omName;
548: }
549:
550: public boolean execute(Object o) {
551: if (o instanceof OperatingMode) {
552: OperatingMode om = (OperatingMode) o;
553: if (name.equals(om.getName())) {
554: return true;
555: }
556: }
557: return false;
558: }
559: }
560:
561: private class OMComparator implements Comparator {
562:
563: // alphabetical sort
564: public int compare(Object o1, Object o2) {
565: if ((o1 instanceof OperatingMode)
566: && (o2 instanceof OperatingMode)) {
567: OperatingMode om1 = (OperatingMode) o1;
568: OperatingMode om2 = (OperatingMode) o2;
569:
570: String om1Name = om1.getName();
571: String om2Name = om2.getName();
572:
573: return om1Name.compareTo(om2Name);
574: }
575: throw new ClassCastException("Expecting OperatingMode");
576: }
577:
578: public boolean equals(Object other) {
579: if (other instanceof OMComparator) {
580: return true;
581: }
582: return false;
583: }
584: }
585:
586: private class OMPComparator implements Comparator {
587:
588: // alphabetical sort
589: public int compare(Object o1, Object o2) {
590: if ((o1 instanceof OperatingModePolicy)
591: && (o2 instanceof OperatingModePolicy)) {
592: OperatingModePolicy omp1 = (OperatingModePolicy) o1;
593: OperatingModePolicy omp2 = (OperatingModePolicy) o2;
594:
595: String omp1Name = omp1.getName();
596: String omp2Name = omp2.getName();
597:
598: return omp1Name.compareTo(omp2Name);
599: }
600: throw new ClassCastException(
601: "Expecting OperatingModePolicy");
602: }
603:
604: public boolean equals(Object other) {
605: if (other instanceof OMComparator) {
606: return true;
607: }
608: return false;
609: }
610: }
611: }
|