001: /*
002: * <copyright>
003: *
004: * Copyright 2003-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: package org.cougaar.lib.aggagent.servlet;
027:
028: import java.io.PrintWriter;
029: import java.util.Collection;
030: import java.util.Iterator;
031: import java.util.LinkedList;
032: import java.util.List;
033: import java.util.Set;
034:
035: import javax.servlet.http.HttpServletRequest;
036:
037: import org.cougaar.core.service.BlackboardService;
038: import org.cougaar.core.service.UIDService;
039: import org.cougaar.core.service.wp.WhitePagesService;
040: import org.cougaar.core.wp.ListAllAgents;
041: import org.cougaar.lib.aggagent.query.AggregationQuery;
042: import org.cougaar.lib.aggagent.query.Alert;
043: import org.cougaar.lib.aggagent.query.AlertDescriptor;
044: import org.cougaar.lib.aggagent.query.QueryResultAdapter;
045: import org.cougaar.lib.aggagent.session.SessionManager;
046: import org.cougaar.lib.aggagent.session.XMLEncoder;
047: import org.cougaar.lib.aggagent.session.XmlIncrement;
048: import org.cougaar.lib.aggagent.util.XmlUtils;
049: import org.cougaar.lib.aggagent.util.Enum.QueryType;
050: import org.cougaar.util.UnaryPredicate;
051: import org.w3c.dom.Element;
052: import org.w3c.dom.NodeList;
053:
054: public class AggregationXMLInterface extends
055: AggregationServletInterface {
056: private SessionManager man = null;
057: private String agentId = null;
058: private WhitePagesService wps = null;
059:
060: public AggregationXMLInterface(BlackboardService bs,
061: SubscriptionMonitorSupport sms, String agentId,
062: WhitePagesService wps, SessionManager man,
063: UIDService uidService) {
064: super (bs, sms, uidService);
065: this .agentId = agentId;
066: this .wps = wps;
067: this .man = man;
068: }
069:
070: public void handleRequest(PrintWriter out,
071: HttpServletRequest request) {
072: if (request.getParameter("GET_QUERIES") != null)
073: getQueries(out);
074: else if (request.getParameter("GET_ALERTS") != null)
075: getAlerts(out);
076: else if (request.getParameter("CREATE_QUERY") != null)
077: publishXMLQuery(request, out);
078: else if (request.getParameter("CREATE_ALERT") != null)
079: publishXMLAlert(request, out);
080: else if (request.getParameter("GET_CLUSTERS") != null)
081: getClusters(out);
082: else if (request.getParameter("GET_RESULT_SET") != null)
083: getResultSet(request, out);
084: else if (request.getParameter("CANCEL_QUERY") != null)
085: removeQueryForThick(request, out);
086: else if (request.getParameter("UPDATE_QUERY") != null)
087: updateQueryForThick(request, out);
088: else if (request.getParameter("CANCEL_ALERT") != null)
089: removeAlert(request, out);
090: else if (request.getParameter("CREATE_PASSIVE_SESSION") != null)
091: createPassiveSession(request, out);
092: else if (request.getParameter("CANCEL_PASSIVE_SESSION") != null)
093: cancelPassiveSession(request, out);
094: else if (request.getParameter("REQUEST_UPDATE") != null)
095: requestUpdate(request, out);
096: else if (request.getParameter("GET_SYSTEM_PROPERTY") != null)
097: getSystemProperty(request, out);
098: else if (request.getParameter("CHECK_URL") != null)
099: checkUrl(out);
100:
101: out.flush();
102: }
103:
104: /**
105: * get all active query result adaptors and send them to the thick client
106: */
107: private void getQueries(PrintWriter out) {
108: Collection qs = query(new QuerySeeker());
109:
110: out.println("<queries>");
111: for (Iterator i = qs.iterator(); i.hasNext();) {
112: out.println(((QueryResultAdapter) i.next()).toWholeXml());
113: }
114: out.println("</queries>");
115: }
116:
117: /**
118: * Return all alerts on the blackboard
119: */
120: private void getAlerts(PrintWriter out) {
121: Collection c = query(new AlertSeeker());
122:
123: out.println("<alerts>");
124: for (Iterator i = c.iterator(); i.hasNext();) {
125: Alert a = (Alert) i.next();
126: AlertDescriptor ad = new AlertDescriptor(a);
127: out.println(ad.toXml());
128: }
129: out.println("</alerts>");
130: }
131:
132: /**
133: * return all agents and node agents on society (except for this one)
134: */
135: private void getClusters(PrintWriter out) {
136: List clusterIds = getAllEncodedAgentNames();
137:
138: out.println("<clusters>");
139: for (Iterator i = clusterIds.iterator(); i.hasNext();) {
140: Object clusterId = i.next();
141: // filter out this agent and any communities
142: if (!clusterId.equals(agentId)
143: && !clusterId.toString().endsWith(".comm")) {
144: out.println("<cluster_id>");
145: out.println(clusterId);
146: out.println("</cluster_id>");
147: }
148: }
149: out.println("</clusters>");
150: }
151:
152: public List getAllEncodedAgentNames() {
153: try {
154: // do full WP list (deprecated!)
155: Set s = ListAllAgents.listAllAgents(wps);
156: // URLEncode the names and sort
157: List l = ListAllAgents.encodeAndSort(s);
158: return l;
159: } catch (Exception e) {
160: throw new RuntimeException("List all agents failed", e);
161: }
162: }
163:
164: /**
165: * publish a new query based on incoming XML.
166: */
167: private void publishXMLQuery(HttpServletRequest request,
168: PrintWriter out) {
169: try {
170: Element root = XmlUtils.parse(request.getInputStream());
171: AggregationQuery aq = new AggregationQuery(root);
172: QueryResultAdapter qra = new QueryResultAdapter(aq,
173: getUIDService().nextUID());
174: publishAdd(qra);
175:
176: if (aq.getType() == QueryType.PERSISTENT) {
177: out.println(qra.getID());
178: } else {
179: if (aq.timeoutSupplied())
180: waitForAndReturnResults(qra.getID(), out, true, aq
181: .getTimeout());
182: else
183: waitForAndReturnResults(qra.getID(), out, true);
184: }
185: } catch (Exception e) {
186: e.printStackTrace();
187: out.println(-1);
188: }
189: }
190:
191: /**
192: * publish a new alert based on incoming XML.
193: */
194: private void publishXMLAlert(HttpServletRequest request,
195: PrintWriter out) {
196: try {
197: Element root = XmlUtils.parse(request.getInputStream());
198: AlertDescriptor ad = new AlertDescriptor(root);
199:
200: QueryResultAdapter qra = findQuery(ad.getQueryId());
201: Alert alert = ad.createAlert();
202: if (alert != null) {
203: qra.addAlert(alert);
204: publishAdd(alert);
205: out.println(0);
206: } else {
207: out.println(-1);
208: }
209: } catch (Exception e) {
210: e.printStackTrace();
211: out.println(-1);
212: }
213: }
214:
215: /**
216: * remove query with given query id
217: */
218: private void removeQueryForThick(HttpServletRequest request,
219: PrintWriter out) {
220: String queryId = request.getParameter("QUERY_ID");
221: findAndRemoveQuery(queryId);
222: out.println("0");
223: }
224:
225: /**
226: * update query with given query and query id
227: */
228: private void updateQueryForThick(HttpServletRequest request,
229: PrintWriter out) {
230: try {
231: String queryId = request.getParameter("QUERY_ID");
232: Element root = XmlUtils.parse(request.getInputStream());
233: AggregationQuery aq = new AggregationQuery(root);
234: findAndUpdateQuery(queryId, aq);
235: out.println("0");
236: } catch (Exception e) {
237: e.printStackTrace();
238: out.println(-1);
239: }
240: }
241:
242: /**
243: * remove alert from query result adapter and log plan
244: */
245: private void removeAlert(HttpServletRequest request, PrintWriter out) {
246: String queryId = request.getParameter("QUERY_ID");
247: String alertName = request.getParameter("ALERT_NAME");
248: QueryResultAdapter qra = findQuery(queryId);
249: Alert alert = qra.removeAlert(alertName);
250: if (alert != null) {
251: publishChange(qra);
252: publishRemove(alert);
253: out.println("0");
254: } else {
255: out.println("-1");
256: }
257: }
258:
259: /**
260: * Return an up to date AggregationResultSet for given query id
261: */
262: private void getResultSet(HttpServletRequest request,
263: PrintWriter out) {
264: String id = request.getParameter("QUERY_ID");
265: QueryResultAdapter qra = findQuery(id);
266: if (qra == null) {
267: out.println("<result_set_not_found />");
268: } else {
269: out.println(qra.getResultSet().toXml());
270: }
271: }
272:
273: /**
274: * create a passive session on this cluster that monitors a set of alerts or
275: * query result set. Return session id.
276: */
277: private void createPassiveSession(HttpServletRequest request,
278: PrintWriter out) {
279: try {
280: MonitorRequestParser requestParser = new MonitorRequestParser(
281: request);
282: String k = man.addSession(requestParser.unaryPredicate,
283: new XmlIncrement(requestParser.xmlEncoder),
284: "PASSIVE SESSION");
285: out.println(k);
286: } catch (Exception e) {
287: e.printStackTrace();
288: out.println(-1);
289: }
290: }
291:
292: /**
293: * cancel passive session
294: */
295: private void cancelPassiveSession(HttpServletRequest request,
296: PrintWriter out) {
297: String sessionId = request.getParameter("SESSION_ID");
298: man.cancelSession(sessionId);
299: out.println("done");
300: }
301:
302: /**
303: * return local system property to client
304: */
305: private void getSystemProperty(HttpServletRequest request,
306: PrintWriter out) {
307: String propertyName = request.getParameter("PROPERTY_NAME");
308: out.println(System.getProperty(propertyName));
309: }
310:
311: /**
312: * check my url. If I received this message, tell client that URL is ok.
313: */
314: private void checkUrl(PrintWriter out) {
315: out.println("url ok");
316: }
317:
318: /**
319: * Handle update request from active passive session
320: */
321: private void requestUpdate(HttpServletRequest request,
322: PrintWriter out) {
323: String sessionId = request.getParameter("SESSION_ID");
324: man.sendUpdate(sessionId, out);
325: }
326:
327: private static class TrivialXMLEncoder implements XMLEncoder {
328: public void encode(Object o, Collection c) {
329: c.add(o);
330: }
331: }
332:
333: private static XMLEncoder sharedXMLEncoder = new TrivialXMLEncoder();
334:
335: /**
336: * Used to create unary predicate and xml encoder based on incoming monitor
337: * request from client.
338: */
339: public static class MonitorRequestParser {
340: public UnaryPredicate unaryPredicate;
341: public XMLEncoder xmlEncoder;
342:
343: public MonitorRequestParser(HttpServletRequest request)
344: throws Exception {
345: Element root = XmlUtils.parse(request.getInputStream());
346: boolean monitorAll = root.getElementsByTagName(
347: "monitor_all").getLength() != 0;
348: String type = root.getAttribute("type");
349: if (type.equals("result_set")) {
350: // create unary predicate
351: if (monitorAll) {
352: unaryPredicate = new QuerySeeker();
353: } else {
354: LinkedList queries = new LinkedList();
355: NodeList nl = root.getElementsByTagName("query");
356: for (int i = 0; i < nl.getLength(); i++) {
357: Element queryElement = (Element) nl.item(i);
358: queries.add(queryElement.getAttribute("id"));
359: }
360: unaryPredicate = new QuerySeeker(queries);
361: }
362:
363: // create xml encoder--well, sort of borrow it, actually...
364: xmlEncoder = sharedXMLEncoder;
365: } else if (type.equals("alert")) {
366: if (monitorAll) {
367: unaryPredicate = new AlertSeeker();
368: } else {
369: // create unary predicate
370: LinkedList alerts = new LinkedList();
371: NodeList nl = root.getElementsByTagName("alert");
372: for (int i = 0; i < nl.getLength(); i++) {
373: Element alertElement = (Element) nl.item(i);
374: alerts.add(new AlertIdentifier(alertElement
375: .getAttribute("query_id"), alertElement
376: .getAttribute("alert_name")));
377: }
378: unaryPredicate = new AlertSeeker(alerts);
379: }
380:
381: // create xml encoder--well, sort of borrow it, actually...
382: xmlEncoder = sharedXMLEncoder;
383: }
384: }
385: }
386: }
|