1 package com.ibm.staf.service.http;
2 
3 /*****************************************************************************/
4 /* Software Testing Automation Framework (STAF)                              */
5 /* (C) Copyright IBM Corp. 2002, 2004, 2005                                  */
6 /*                                                                           */
7 /* This software is licensed under the Eclipse Public License (EPL) V1.0.    */
8 /*****************************************************************************/
9 
10 /*****************************************************************************/
11 /*                                                                           */
12 /* Class: HTTP                                                               */
13 /* Description: This class provides the STAFService Interface and implements */
14 /*              the majority of the service function                         */
15 /*                                                                           */
16 /*****************************************************************************/
17 
18 import com.ibm.staf.*;
19 import com.ibm.staf.service.*;
20 import com.ibm.staf.service.utility.ServiceUtilities;
21 import com.ibm.staf.service.http.html.InvalidParameterValueException;
22 
23 import java.io.File;
24 import java.io.FileOutputStream;
25 import java.io.DataOutputStream;
26 import java.io.PrintWriter;
27 import java.io.StringWriter;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.IOException;
31 import java.io.FileNotFoundException;
32 import java.net.URL;
33 import java.text.SimpleDateFormat;
34 import java.util.Calendar;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.Vector;
38 import java.util.Map;
39 import java.util.List;
40 import java.util.ArrayList;
41 import java.net.UnknownHostException;
42 import java.net.ConnectException;
43 import java.net.MalformedURLException;
44 
45 import com.ibm.staf.service.http.html.*;
46 
47 import org.apache.commons.httpclient.HttpException;
48 
49 public class HTTP implements STAFServiceInterfaceLevel30
50 {
51     public static final boolean DEBUG = false;
52 
53     private static String sHelpMsg;
54     private static String sLineSep;
55 
56     private STAFHandle sHandle;
57     private String fServiceName;
58     private String fLocalMachineName = "";
59     private STAFCommandParser requestParser;
60     private STAFCommandParser infoParser;
61     private STAFCommandParser getParser;
62     private STAFCommandParser htmlActionParser;
63     private STAFCommandParser setParser;
64     private STAFCommandParser delCloseParser;
65 
66     private STAFMapClassDefinition fListSessionMapClass;
67     private STAFMapClassDefinition fSessionMapClass;
68     private STAFMapClassDefinition fSessionOwnerMapClass;
69     private STAFMapClassDefinition fHttpResultMapClass;
70     private STAFMapClassDefinition fAuthHostMapClass;
71     private STAFMapClassDefinition fCookieMapClass;
72     private STAFMapClassDefinition fListFormMapClass;
73     private STAFMapClassDefinition fFormMapClass;
74     private STAFMapClassDefinition fFormControlMapClass;
75     private STAFMapClassDefinition fListLinkMapClass;
76     private STAFMapClassDefinition fLinkMapClass;
77 
78     private SessionList sessionList;
79     private String fTempDir;
80     private int fTempFileCount = 0;
81 
82     /* String Constants */
83 
84     private static final String VERSIONINFO = "3.0.4";
85 
86     // Version of STAF (or later) required for this service
87     // STAF Version 3.1.0 or later is required so that the privacy methods
88     // in STAFUtil are available.
89     private static final String REQUIREDSTAFVERSION = "3.4.0";
90 
91     private final static SimpleDateFormat sTimestampFormat =
92         new SimpleDateFormat("yyyyMMdd-HH:mm:ss");
93 
94     private static final String REQUEST = "REQUEST";
95     private static final String DOPOST = "DOPOST";
96     private static final String DOGET = "DOGET";
97     private static final String METHOD = "METHOD";
98     private static final String URL = "URL";
99     private static final String ENCODED = "ENCODED";
100     private static final String CONTENT = "CONTENT";
101     private static final String HEADER = "HEADER";
102     private static final String PARAMETER = "PARAMETER";
103     private static final String CONTENTFILE ="CONTENTFILE";
104     private static final String FILE = "FILE";
105     private static final String TOMACHINE = "TOMACHINE";
106     private static final String IGNOREERRORS = "IGNOREERRORS";
107     private static final String RETURNHEADERS = "RETURNHEADERS";
108     private static final String NOSTATUS = "NOSTATUS";
109     private static final String NOCONTENT = "RETURNNOCONTENT";
110     private static final String SESSION = "SESSION";
111     private static final String SESSIONS = "SESSIONS";
112     private static final String OPEN = "OPEN";
113     private static final String CLOSE = "CLOSE";
114     private static final String COOKIE = "COOKIE";
115     private static final String COOKIES = "COOKIES";
116     private static final String NAME = "NAME";
117     private static final String GET = "GET";
118     private static final String SET = "SET";
119     private static final String VALUE = "VALUE";
120     private static final String DELETE = "DELETE";
121     private static final String POLICY = "POLICY";
122     private static final String SHOW = "SHOW";
123     private static final String PAGE = "PAGE";
124     private static final String QUERY = "QUERY";
125     private static final String LIST = "LIST";
126     private static final String LINK = "LINK";
127     private static final String LINKS = "LINKS";
128     private static final String FORM = "FORM";
129     private static final String FORMS = "FORMS";
130     private static final String ID = "ID";
131     private static final String INDEX = "INDEX";
132     private static final String FOLLOW = "FOLLOW";
133     private static final String SUBMIT = "SUBMIT";
134     private static final String RESET = "RESET";
135     private static final String FORMCONTROLS = "CONTROLNAMES";
136     private static final String CONTROLNAME = "CONTROLNAME";
137     private static final String AUTOREDIRECT = "FOLLOWREDIRECT";
138     private static final String NOAUTOREDIRECT = "DONOTFOLLOWREDIRECT";
139     private static final String DEFAULTHEADER = "DEFAULTHEADER";
140     private static final String DEFAULTHEADERS = "DEFAULTHEADERS";
141     private static final String AUTHENTICATIONHOSTS = "AUTHENTICATIONHOSTS";
142     private static final String AUTHENTICATIONHOST = "AUTHENTICATIONHOST";
143     private static final String AUTHENTICATIONUSER = "AUTHENTICATIONUSER";
144     private static final String AUTHENTICATIONPWD = "AUTHENTICATIONPASSWORD";
145     private static final String AUTHENTICATIONDOMAIN = "AUTHENTICATIONDOMAIN";
146     private static final String HELP = "HELP";
147     private static final String VERSION = "VERSION";
148 
149     private static final int BASEERROR = 4000;
150     public static final int UNKNOWNHOST = 4001;
151     private static final String UNKNOWNHOSTInfo =
152        "Unknown Host Error";
153     private static final String UNKNOWNHOSTDesc =
154        "The specified host could not be found in the naming service.";
155     public static final int CONNECTERROR = 4002;
156     private static final String CONNECTERRORInfo = "Connect Error";
157     private static final String CONNECTERRORDesc =
158        "The host was located, but a connection could not be made to " +
159        "the specified port.";
160     public static final int INVALIDMETHOD = 4003;
161     private static final String INVALIDMETHODInfo =
162         "Invalid Method";
163     private static final String INVALIDMETHODDesc =
164        "The specified method is not allowed. Allowed methods: POST, PUT, " +
165        "GET, HEAD, OPTIONS, DELETE, and TRACE.";
166     public static final int IOEXCEPTION = 4004;
167     private static final String IOEXCEPTIONInfo = "IO Exception";
168     private static final String IOEXCEPTIONDesc =
169        "The host was located, but an IO exception occurred opening a " +
170        "connection to the URL.";
171     public static final int CONTENTTOOLARGE = 4005;
172     private static final String CONTENTTOOLARGEInfo = "Out of Memory Error";
173     private static final String CONTENTTOOLARGEDesc =
174        "Trying to get content that is too large. Recommend " +
175        "redirecting the content to a file using the FILE option or, " +
176        "if the content is not needed, you may be able to specify the " +
177        "RETURNNOCONTENT option depending on the request.";
178 
179 /*****************************************************************************/
180 /*                                                                           */
181 /* Method: Constructor                                                       */
182 /* Description: Constructor method                                           */
183 /*                                                                           */
184 /*****************************************************************************/
185 
HTTP()186 public HTTP()
187 {
188     /* do nothing */
189 }
190 
191 /*****************************************************************************/
192 /*                                                                           */
193 /* Method: acceptRequest                                                     */
194 /* Description: required by interface STAFServiceInterfaceLevel30            */
195 /*              performs first parse of request                              */
196 /*                                                                           */
197 /*****************************************************************************/
198 
acceptRequest(STAFServiceInterfaceLevel30.RequestInfo info)199 public STAFResult acceptRequest(STAFServiceInterfaceLevel30.RequestInfo info)
200 {
201     // Try block is here to catch any unexpected errors/exceptions
202 
203     try
204     {
205         // Determine the command request (the first word in the request)
206 
207         String action;
208         int spaceIndex = info.request.indexOf(" ");
209 
210         if (spaceIndex != -1)
211             action = info.request.substring(0, spaceIndex);
212         else
213             action = info.request;
214 
215         String actionUC = action.toUpperCase();
216 
217         // Call the appropriate method to handle the command request
218 
219         if ((actionUC.equals(DOPOST)) || (actionUC.equals(DOGET)) ||
220             (actionUC.equals(REQUEST)))
221         {
222             return handleMethod(info);
223         }
224         else if (actionUC.equals(OPEN))
225             return handleOpen(info);
226         else if (actionUC.equals(LIST))
227             return handleList(info);
228         else if (actionUC.equals(SET))
229             return handleSet(info);
230         else if (actionUC.equals(GET))
231             return handleGetPage(info);
232         else if (actionUC.equals(QUERY))
233             return handleQuery(info);
234         else if (actionUC.equals(CLOSE))
235             return handleClose(info);
236         else if (actionUC.equals(FOLLOW))
237             return handleFollow(info);
238         else if (actionUC.equals(SUBMIT))
239             return handleFormAction(info);
240         else if (actionUC.equals(DELETE))
241             return handleDelete(info);
242         else if (actionUC.equals(RESET))
243             return handleFormAction(info);
244         else if (actionUC.equals(HELP))
245             return help(info);
246         else if (actionUC.equals(VERSION))
247             return version(info);
248         else
249         {
250             return new STAFResult(
251                 STAFResult.InvalidRequestString,
252                 "'" + action + "' is not a valid command request for the " +
253                 fServiceName + " service" + sLineSep + sLineSep + sHelpMsg);
254         }
255     }
256     catch (STAFException se)
257     {
258         return new STAFResult(se.rc, se.getMessage());
259     }
260     catch (Throwable t)
261     {
262         // Write the Java stack trace to the JVM log for the service
263 
264         System.out.println(
265             sTimestampFormat.format(Calendar.getInstance().getTime()) +
266             " ERROR: Exception on " + fServiceName + " service request:" +
267             sLineSep + sLineSep + info.request + sLineSep);
268 
269         t.printStackTrace();
270 
271         // And also return the Java stack trace in the result
272 
273         StringWriter sw = new StringWriter();
274         t.printStackTrace(new PrintWriter(sw));
275 
276         if (t.getMessage() != null)
277         {
278             return new STAFResult(
279                 STAFResult.JavaError,
280                 t.getMessage() + sLineSep + sw.toString());
281         }
282         else
283         {
284             return new STAFResult(
285                 STAFResult.JavaError, sw.toString());
286         }
287     }
288 }
289 
290 
291 // enhanced functionality
292 
293 /*****************************************************************************/
294 /*                                                                           */
295 /* Method: handleOpen                                                        */
296 /* Description: Creates a new web session and goes to the specified url.     */
297 /* Parameters: info - request info passed to acceptRequest                   */
298 /* Returns: session id of new session                                        */
299 /*                                                                           */
300 /*****************************************************************************/
301 
handleOpen(STAFServiceInterfaceLevel30.RequestInfo info)302 private STAFResult handleOpen(STAFServiceInterfaceLevel30.RequestInfo info)
303                               throws STAFException
304 {
305     // Verify the requester has at least trust level 3
306 
307     STAFResult trustResult = STAFUtil.validateTrust(
308         3, fServiceName, "OPEN", fLocalMachineName, info);
309 
310     if (trustResult.rc != STAFResult.Ok) return trustResult;
311 
312     if (! info.request.equalsIgnoreCase("OPEN SESSION"))
313     {
314         return new STAFResult(STAFResult.InvalidRequestString,
315                               info.request);
316     }
317 
318     String result;
319 
320     WebSession newSession = new WebSession(sessionList, info, this);
321 
322     result = Integer.toString(newSession.getID());
323 
324     return new STAFResult(STAFResult.Ok, result);
325 }
326 
327 /*****************************************************************************/
328 /*                                                                           */
329 /* Method: handleClose                                                       */
330 /* Description: ends a web session and removes it from the session list.     */
331 /* Parameters: info - request info passed to acceptRequest                   */
332 /* Returns: STAFResult.OK                                                    */
333 /*                                                                           */
334 /*****************************************************************************/
335 
handleClose(STAFServiceInterfaceLevel30.RequestInfo info)336 private STAFResult handleClose(STAFServiceInterfaceLevel30.RequestInfo info)
337                                throws STAFException
338 {
339     // Verify the requester has at least trust level 3
340 
341     STAFResult trustResult = STAFUtil.validateTrust(
342         3, fServiceName, "CLOSE", fLocalMachineName, info);
343 
344     if (trustResult.rc != STAFResult.Ok) return trustResult;
345 
346     // Parse the request
347 
348     STAFCommandParseResult pResult = delCloseParser.parse(info.request);
349 
350     if (pResult.rc != 0)
351     {
352         return new STAFResult(STAFResult.InvalidRequestString,
353                               pResult.errorBuffer);
354     }
355 
356     // Get resolved value for SESSION option and make sure it's an integer
357 
358     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
359         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
360 
361     if (res.rc != 0) return res;
362 
363     int sessionId = Integer.parseInt(res.result);
364 
365     // Check if the requester is the owner of the session
366 
367     WebSession session;
368 
369     try
370     {
371         session = sessionList.getSession(sessionId);
372     }catch (InvalidSessionIDException e)
373     {
374         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
375     }
376 
377     if (!session.isOwner(info.stafInstanceUUID))
378     {
379         // Verify the requester has at least trust level 5 if not the owner
380         // of the session
381 
382         trustResult = STAFUtil.validateTrust(
383             5, fServiceName, "CLOSE", fLocalMachineName, info);
384 
385         if (trustResult.rc != STAFResult.Ok) return trustResult;
386     }
387 
388     // Release the resources held by the session and delete the session
389 
390     try
391     {
392         session.releaseConnection();
393         sessionList.deleteSession(sessionId);
394 
395     }catch (InvalidSessionIDException e)
396     {
397         return new STAFResult(STAFResult.DoesNotExist,e.getMessage());
398     }
399 
400     return new STAFResult(STAFResult.Ok, "");
401 }
402 
403 /*****************************************************************************/
404 /*                                                                           */
405 /* Method: handleQuery                                                       */
406 /* Description: gets information about a specific entity.                    */
407 /* Parameters: info - request info passed to acceptRequest                   */
408 /* Returns: STAFResult containing detailed information on a specific entity  */
409 /*                                                                           */
410 /*****************************************************************************/
411 
handleQuery(STAFServiceInterfaceLevel30.RequestInfo info)412 private STAFResult handleQuery(STAFServiceInterfaceLevel30.RequestInfo info)
413                                throws STAFException
414 {
415     // Verify the requester has at least trust level 2
416 
417     STAFResult trustResult = STAFUtil.validateTrust(
418         2, fServiceName, "QUERY", fLocalMachineName, info);
419 
420     if (trustResult.rc != STAFResult.Ok) return trustResult;
421 
422     // Parse the request
423 
424     STAFCommandParseResult pResult = infoParser.parse(info.request);
425 
426     if (pResult.rc != 0)
427     {
428         return new STAFResult(STAFResult.InvalidRequestString,
429                               pResult.errorBuffer);
430     }
431 
432     // Get resolved value for SESSION option and make sure it's an integer
433 
434     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
435         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
436 
437     if (res.rc != 0) return res;
438 
439     int sessionId = Integer.parseInt(res.result);
440 
441     // Get the session
442 
443     WebSession session;
444 
445     try
446     {
447         session = sessionList.getSession(sessionId);
448     }
449     catch (InvalidSessionIDException e)
450     {
451         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
452     }
453 
454     STAFMarshallingContext mc = new STAFMarshallingContext();
455 
456     String id = "";
457     int idType = -1;
458 
459     if (pResult.optionTimes(ID) > 0)
460     {
461         // Resolve the ID option value
462 
463         res = STAFUtil.resolveRequestVar(
464             pResult.optionValue(ID), sHandle, info.requestNumber);
465 
466         if (res.rc != 0) return res;
467 
468         id = res.result;
469         idType = WebSession.ID_ID_TYPE;
470     }
471     else if (pResult.optionTimes(NAME) > 0)
472     {
473         // Resolve the NAME option value
474 
475         res = STAFUtil.resolveRequestVar(
476             pResult.optionValue(NAME), sHandle, info.requestNumber);
477 
478         if (res.rc != 0) return res;
479 
480         id = res.result;
481         idType = WebSession.NAME_ID_TYPE;
482     }
483     else if (pResult.optionTimes(INDEX) > 0)
484     {
485         // Resolve the INDEX option value
486 
487         res = STAFUtil.resolveRequestVar(
488             pResult.optionValue(INDEX), sHandle, info.requestNumber);
489 
490         if (res.rc != 0) return res;
491 
492         id = res.result;
493         idType = WebSession.INDEX_ID_TYPE;
494     }
495 
496     if (pResult.optionTimes(DEFAULTHEADER) > 0)
497     {
498         // QUERY DEFAULTHEADER
499 
500         res = STAFUtil.resolveRequestVar(
501             pResult.optionValue(DEFAULTHEADER), sHandle, info.requestNumber);
502 
503         if (res.rc != 0) return res;
504 
505         String key = res.result;
506 
507         try
508         {
509             return new STAFResult(STAFResult.Ok,
510                                   session.getDefaultHeaderValue(key));
511         }
512         catch (InvalidElementIDException e)
513         {
514             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
515         }
516     }
517     else if (pResult.optionTimes(AUTHENTICATIONHOST) > 0)
518     {
519         // QUERY AUTHENTICATIONHOST
520 
521         mc.setMapClassDefinition(fAuthHostMapClass);
522         Map authHostMap = fAuthHostMapClass.createInstance();
523 
524         res = STAFUtil.resolveRequestVar(
525             pResult.optionValue(AUTHENTICATIONHOST), sHandle,
526             info.requestNumber);
527 
528         if (res.rc != 0) return res;
529 
530         String key = res.result;
531 
532         try
533         {
534             String[] values = session.getAuthenticationSetValues(key);
535             String user = values[0];
536             String password = values[1];
537             String domain = values[2];
538 
539             if (user != null && !user.equals(""))
540                 authHostMap.put("user", user);
541 
542             if (password != null && !password.equals(""))
543                 authHostMap.put("password", "*******");
544 
545             if (domain != null && !domain.equals(""))
546                 authHostMap.put("domain", domain);
547 
548             mc.setRootObject(authHostMap);
549         }
550         catch (InvalidElementIDException e)
551         {
552             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
553         }
554     }
555     else if (pResult.optionTimes(FORM) > 0)
556     {
557         try
558         {
559             if (id.equals("") && idType == -1)
560             {
561                 id = "1";
562                 idType = WebSession.INDEX_ID_TYPE;
563             }
564 
565             if (pResult.optionTimes(CONTROLNAME) > 0)
566             {
567                 // QUERY FORM CONTROLNAME
568 
569                 mc.setMapClassDefinition(fFormControlMapClass);
570                 Map formMap = fFormControlMapClass.createInstance();
571 
572                 res = STAFUtil.resolveRequestVar(
573                     pResult.optionValue(CONTROLNAME), sHandle,
574                     info.requestNumber);
575 
576                 if (res.rc != 0) return res;
577 
578                 String controlName = res.result;
579 
580                 HashMap data = session.summarizeFormControl(
581                     id, idType, controlName);
582 
583                 String type     = (String)data.get(Parameter.TYPE);
584                 String disabled = (String)data.get(Parameter.DISABLED);
585                 String readOnly = (String)data.get(Parameter.READONLY);
586                 String value    = (String)data.get(Parameter.VALUE);
587 
588                 if (type != null && !type.equals(""))
589                     formMap.put("type", type);
590                 if (disabled != null && !disabled.equals(""))
591                     formMap.put("disabled", disabled);
592                 if (readOnly != null && !readOnly.equals(""))
593                     formMap.put("readOnly", readOnly);
594                 if (value != null && !value.equals(""))
595                     formMap.put("value", STAFUtil.maskPrivateData(value));
596 
597                 formMap.put("possibleValueList",
598                             (List)data.get(Parameter.POSSIBLEVALUES));
599 
600                 mc.setRootObject(formMap);
601             }
602             else
603             {
604                 // QUERY FORM      (Summarize the form)
605 
606                 mc.setMapClassDefinition(fFormMapClass);
607                 Map formMap = fFormMapClass.createInstance();
608 
609                 HashMap data = session.summarizeForm(id, idType);
610 
611                 String formIndex = data.get(WebElement.INDEX).toString();
612                 String formName  = (String)data.get(WebElement.NAME);
613                 String formID    = (String)data.get(WebElement.ID);
614                 String method    = (String)data.get(WebSession.REQUEST_METHOD);
615                 String action    = (String)data.get(WebSession.REQUEST_URL);
616 
617                 if (formIndex != null && !formIndex.equals(""))
618                     formMap.put("formIndex", formIndex);
619                 if (formName != null && !formName.equals(""))
620                     formMap.put("formName", formName);
621                 if (formID != null && !formID.equals(""))
622                     formMap.put("formID", formID);
623                 if (method != null && !method.equals(""))
624                     formMap.put("method", method);
625                 if (action != null && !action.equals(""))
626                     formMap.put("targetUrl", action);
627 
628                 formMap.put("headerMap",
629                             (HashMap)data.get(WebSession.REQUEST_HEADERS));
630 
631                 mc.setRootObject(formMap);
632             }
633         }
634         catch (InvalidElementIDException e)
635         {
636             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
637         }
638     }
639     else if (pResult.optionTimes(COOKIE) > 0)
640     {
641         // QUERY COOKIE
642 
643         mc.setMapClassDefinition(fCookieMapClass);
644         Map cookieMap = fCookieMapClass.createInstance();
645 
646         try
647         {
648             HashMap data = session.summarizeCookie(id);
649 
650             String value = (String)data.get(CookieAccess.VALUE);
651             String domain = (String)data.get(CookieAccess.DOMAIN);
652             String path = (String)data.get(CookieAccess.PATH);
653             String expirationDate = null;
654 
655             if (data.get(CookieAccess.EXPIRATION) != null)
656                 expirationDate = data.get(CookieAccess.EXPIRATION).toString();
657 
658             if (value != null && !value.equals(""))
659                 cookieMap.put("value", value);
660 
661             if (domain != null && !domain.equals(""))
662                 cookieMap.put("domain", domain);
663 
664             if (path != null && !path.equals(""))
665                 cookieMap.put("path", path);
666 
667             if (expirationDate != null && !expirationDate.equals(""))
668                 cookieMap.put("expirationDate", expirationDate);
669 
670             mc.setRootObject(cookieMap);
671         }
672         catch (InvalidCookieIDException e)
673         {
674             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
675 
676         }
677     }
678     else if (pResult.optionTimes(LINK) > 0)
679     {
680         // QUERY LINK
681 
682         mc.setMapClassDefinition(fLinkMapClass);
683         Map linkMap = fLinkMapClass.createInstance();
684 
685         try
686         {
687             HashMap data = session.summarizeLink(id, idType);
688 
689             String linkName = null;
690             String linkID = null;
691             String href = null;
692 
693             if (data.get(WebElement.NAME) != null)
694                 linkName = (String)data.get(WebElement.NAME);
695 
696             if (data.get(WebElement.ID) != null)
697                 linkID = (String)data.get(WebElement.ID);
698 
699             if (data.get(WebLink.HREF) != null)
700                 href = (String)data.get(WebLink.HREF);
701 
702             linkMap.put("linkIndex", data.get(WebElement.INDEX));
703 
704             if (linkID != null && !linkID.equals(""))
705                 linkMap.put("linkID", linkID);
706             if (linkName != null && !linkName.equals(""))
707                 linkMap.put("linkName", linkName);
708             if (href != null && !href.equals(""))
709                 linkMap.put("href", href);
710 
711             mc.setRootObject(linkMap);
712         }
713         catch (InvalidElementIDException e)
714         {
715             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
716         }
717     }
718     else
719     {
720         // QUERY SESSION <Session>  (Summarize the session)
721 
722         mc.setMapClassDefinition(fSessionMapClass);
723         mc.setMapClassDefinition(fSessionOwnerMapClass);
724         Map sessionMap = fSessionMapClass.createInstance();
725         Map ownerMap = fSessionOwnerMapClass.createInstance();
726 
727         HashMap data = session.getSummary();
728 
729         String url              = (String)data.get(WebSession.URL);
730         String title            = (String)data.get(WebSession.TITLE);
731         String statusCode       = (String)data.get(
732             WebSession.RETURN_STATUS_CODE);
733         String statusMessage    = (String)data.get(
734             WebSession.RETURN_STATUS_MESSAGE);
735         String cookiePolicy     = (String)data.get(WebSession.POLICY);
736         String followsRedirects = (String)data.get(WebSession.REQUEST_REDIRECT);
737         String parseContent     = (String)data.get(WebSession.PARSE_CONTENT);
738         String httpProxyHost    = (String)data.get(WebSession.HTTP_PROXY_HOST);
739         Integer httpProxyPort    = (Integer)data.get(WebSession.HTTP_PROXY_PORT);
740         String ownerInstanceUUID= (String)data.get(
741             WebSession.OWNER_INSTANCE_UUID);
742         String ownerMachine     = (String)data.get(WebSession.OWNER_MACHINE);
743         String ownerHandleName  = (String)data.get(
744             WebSession.OWNER_HANDLE_NAME);
745         String ownerHandle      = (String)data.get(WebSession.OWNER_HANDLE);
746 
747         if (url != null && !url.equals(""))
748             sessionMap.put("url", url);
749 
750         if (title != null && !title.equals(""))
751             sessionMap.put("title", title);
752 
753         if (statusCode != null && !statusCode.equals(""))
754             sessionMap.put("statusCode", statusCode);
755 
756         if (statusMessage != null && !statusMessage.equals(""))
757             sessionMap.put("statusMessage", statusMessage);
758 
759         if (cookiePolicy != null && !cookiePolicy.equals(""))
760             sessionMap.put("cookiePolicy", cookiePolicy);
761 
762         if (followsRedirects != null && !followsRedirects.equals(""))
763             sessionMap.put("followsRedirects", followsRedirects);
764 
765         if (parseContent != null && !parseContent.equals(""))
766             sessionMap.put("parseContent", parseContent);
767 
768         if (httpProxyHost != null && !httpProxyHost.equals(""))
769             sessionMap.put("httpProxyHost", httpProxyHost);
770 
771         if (httpProxyPort.intValue() != -1)
772             sessionMap.put("httpProxyPort", httpProxyPort.toString());
773 
774         ownerMap.put("instanceUUID", ownerInstanceUUID);
775         ownerMap.put("machine", ownerMachine);
776         ownerMap.put("handle", ownerHandle);
777 
778         if (ownerHandleName != null & !ownerHandleName.equals(""))
779             ownerMap.put("handleName", ownerHandleName);
780 
781         sessionMap.put("owner", ownerMap);
782 
783         mc.setRootObject(sessionMap);
784     }
785 
786     return new STAFResult(STAFResult.Ok, mc.marshall());
787 }
788 
789 /*****************************************************************************/
790 /*                                                                           */
791 /* Method: handleList                                                        */
792 /* Description: gets a list of the requested entities.            .          */
793 /* Parameters: info - request info passed to acceptRequest                   */
794 /* Returns: STAFResult listing the requested entities                        */
795 /*                                                                           */
796 /*****************************************************************************/
797 
handleList(STAFServiceInterfaceLevel30.RequestInfo info)798 private STAFResult handleList(STAFServiceInterfaceLevel30.RequestInfo info)
799                               throws STAFException
800 {
801     // Verify the requester has at least trust level 2
802 
803     STAFResult trustResult = STAFUtil.validateTrust(
804         2, fServiceName, "LIST", fLocalMachineName, info);
805 
806     if (trustResult.rc != STAFResult.Ok) return trustResult;
807 
808     // Parse the result
809 
810     STAFCommandParseResult pResult = infoParser.parse(info.request);
811 
812     if (pResult.rc != 0)
813     {
814         return new STAFResult(STAFResult.InvalidRequestString,
815                               pResult.errorBuffer);
816     }
817 
818     STAFMarshallingContext mc = new STAFMarshallingContext();
819     List resultList = new ArrayList();
820 
821     if (pResult.optionTimes(SESSION) > 0)
822     {
823         // Get resolved value for SESSION option and make sure it's an integer
824 
825         STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
826             SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
827 
828         if (res.rc != 0) return res;
829 
830         int sessionId = Integer.parseInt(res.result);
831 
832         WebSession session;
833 
834         // Get the session
835         try
836         {
837             session = sessionList.getSession(sessionId);
838         }
839         catch (InvalidSessionIDException e)
840         {
841             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
842         }
843 
844         if (pResult.optionTimes(DEFAULTHEADERS) > 0)
845         {
846             // LIST DEFAULTHEADERS
847 
848             HashMap headers = session.getDefaultHeaders();
849 
850             mc.setRootObject(headers);
851             return new STAFResult(STAFResult.Ok, mc.marshall());
852         }
853         else if (pResult.optionTimes(AUTHENTICATIONHOSTS) > 0)
854         {
855             // LIST AUTHENTICATIONHOSTS
856 
857             HashMap authenticationSets = session.getAuthenticationSets();
858             Iterator it = authenticationSets.keySet().iterator();
859 
860             while(it.hasNext())
861                 resultList.add((String)it.next());
862         }
863         else if (pResult.optionTimes(FORMS) > 0)
864         {
865             // LIST FORMS
866 
867             mc.setMapClassDefinition(fListFormMapClass);
868 
869             HashMap[] list = session.listForms();
870 
871             for (int i = 0; i < list.length; i++)
872             {
873                 Map resultMap = fListFormMapClass.createInstance();
874 
875                 resultMap.put("formIndex", list[i].get(WebElement.INDEX));
876 
877                 String id = (String)list[i].get(WebElement.ID);
878                 String name = (String)list[i].get(WebElement.NAME);
879 
880                 if (id != null && !id.equals(""))
881                     resultMap.put("formID", id);
882 
883                 if (name != null && !name.equals(""))
884                     resultMap.put("formName", name);
885 
886                 resultList.add(resultMap);
887             }
888         }
889         else if (pResult.optionTimes(LINKS) > 0)
890         {
891             // LIST LINKS
892 
893             mc.setMapClassDefinition(fListLinkMapClass);
894 
895             HashMap[] list = session.listLinks();
896 
897             for (int i = 0; i < list.length; i++)
898             {
899                 Map resultMap = fListLinkMapClass.createInstance();
900 
901                 resultMap.put("linkIndex", list[i].get(WebElement.INDEX));
902 
903                 String id = (String)list[i].get(WebElement.ID);
904                 String name = (String)list[i].get(WebElement.NAME);
905 
906                 if (id != null && !id.equals(""))
907                     resultMap.put("linkID", id);
908 
909                 if (name != null && !name.equals(""))
910                     resultMap.put("linkName", name);
911 
912                 resultList.add(resultMap);
913             }
914         }
915         else if (pResult.optionTimes(COOKIES) > 0)
916         {
917             // LIST COOKIES
918 
919             HashMap[] list = session.listCookies();
920 
921             for (int i = 0; i < list.length; i++)
922                 resultList.add(list[i].get(CookieAccess.NAME));
923         }
924         else if (pResult.optionTimes(FORMCONTROLS) > 0)
925         {
926             // LIST FORMCONTROLS
927 
928             String id = "";
929             int idType = -1;
930 
931             if (pResult.optionTimes(ID) > 0)
932             {
933                 // Resolve the ID option value
934 
935                 res = STAFUtil.resolveRequestVar(
936                     pResult.optionValue(ID), sHandle, info.requestNumber);
937 
938                 if (res.rc != 0) return res;
939 
940                 id = res.result;
941                 idType = WebSession.ID_ID_TYPE;
942             }
943             else if (pResult.optionTimes(NAME) > 0)
944             {
945                 // Resolve the NAME option value
946 
947                 res = STAFUtil.resolveRequestVar(
948                     pResult.optionValue(NAME), sHandle, info.requestNumber);
949 
950                 if (res.rc != 0) return res;
951 
952                 id = res.result;
953                 idType = WebSession.NAME_ID_TYPE;
954             }
955             else if (pResult.optionTimes(INDEX) > 0)
956             {
957                 // Resolve the INDEX option value
958 
959                 res = STAFUtil.resolveRequestVar(
960                     pResult.optionValue(INDEX), sHandle, info.requestNumber);
961 
962                 if (res.rc != 0) return res;
963 
964                 id = res.result;
965                 idType = WebSession.INDEX_ID_TYPE;
966             }
967 
968             if (id.equals("") && idType == -1)
969             {
970                 id = "1";
971                 idType = WebSession.INDEX_ID_TYPE;
972             }
973             try
974             {
975                 HashMap data = session.summarizeForm(id, idType);
976                 List controls = (List) data.get(WebForm.CONTROLS);
977 
978                 for (int i = 0; i < controls.size(); i++)
979                     resultList.add(((Parameter)controls.get(i)).getKey());
980             }
981             catch (InvalidElementIDException e)
982             {
983                 return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
984             }
985         }
986     }
987     else
988     {
989         // LIST SESSIONS
990 
991         mc.setMapClassDefinition(fListSessionMapClass);
992 
993         HashMap[] list = sessionList.listSessions();
994 
995         for (int i = 0; i < list.length; i++)
996         {
997             Map sessionMap = fListSessionMapClass.createInstance();
998 
999             sessionMap.put("sessionID", list[i].get(WebSession.ID));
1000 
1001             String url = (String)list[i].get(WebSession.URL);
1002             String title = (String)list[i].get(WebSession.TITLE);
1003 
1004             if (url != null && !url.equals(""))
1005                 sessionMap.put("url", url);
1006 
1007             if (title != null && !title.equals(""))
1008                 sessionMap.put("title", title);
1009 
1010             resultList.add(sessionMap);
1011         }
1012     }
1013 
1014     mc.setRootObject(resultList);
1015 
1016     return new STAFResult(STAFResult.Ok, mc.marshall());
1017 }
1018 
1019 /*****************************************************************************/
1020 /*                                                                           */
1021 /* Method: handleSet                                                         */
1022 /* Description: performs the desired set interaction                         */
1023 /* Parameters: info - request info passed to acceptRequest                   */
1024 /* Returns: STAFResult.OK                                                    */
1025 /*                                                                           */
1026 /*****************************************************************************/
1027 
handleSet(STAFServiceInterfaceLevel30.RequestInfo info)1028 private STAFResult handleSet(STAFServiceInterfaceLevel30.RequestInfo info)
1029     throws STAFException
1030 {
1031     // Verify the requester has at least trust level 3
1032 
1033     STAFResult trustResult = STAFUtil.validateTrust(
1034         3, fServiceName, "SET", fLocalMachineName, info);
1035 
1036     if (trustResult.rc != STAFResult.Ok) return trustResult;
1037 
1038     // Parse the result
1039 
1040     STAFCommandParseResult pResult = setParser.parse(info.request);
1041 
1042     if (pResult.rc != 0)
1043     {
1044         return new STAFResult(STAFResult.InvalidRequestString,
1045                               pResult.errorBuffer);
1046     }
1047 
1048     // Get resolved value for SESSION option and make sure it's an integer
1049 
1050     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
1051         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
1052 
1053     if (res.rc != 0) return res;
1054 
1055     int sessionId = Integer.parseInt(res.result);
1056 
1057     WebSession session;
1058 
1059     // Get the session
1060 
1061     try
1062     {
1063         session = sessionList.getSession(sessionId);
1064     }
1065     catch (InvalidSessionIDException e)
1066     {
1067         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
1068     }
1069 
1070     if (!session.isOwner(info.stafInstanceUUID))
1071     {
1072         // Verify the requester has at least trust level 4 since not the
1073         // session owner
1074 
1075         trustResult = STAFUtil.validateTrust(
1076             4, fServiceName, "SET", fLocalMachineName, info);
1077 
1078         if (trustResult.rc != STAFResult.Ok) return trustResult;
1079     }
1080 
1081     String result = "";
1082 
1083     if (pResult.optionTimes(DEFAULTHEADER) > 0)
1084     {
1085         // Resolve the DEFAULTHEADER option value
1086 
1087         res = STAFUtil.resolveRequestVar(
1088             pResult.optionValue(DEFAULTHEADER), sHandle, info.requestNumber);
1089 
1090         if (res.rc != 0) return res;
1091 
1092         String key = res.result;
1093 
1094         // Resolve the VALUE option value
1095 
1096         res = STAFUtil.resolveRequestVar(
1097             pResult.optionValue(VALUE), sHandle, info.requestNumber);
1098 
1099         if (res.rc != 0) return res;
1100 
1101         String value = res.result;
1102 
1103         session.setDefaultHeader(key, value);
1104 
1105     }
1106     else if (pResult.optionTimes(AUTHENTICATIONHOST) > 0)
1107     {
1108         // Resolve the AUTHENTICATIONHOST option value
1109 
1110         res = STAFUtil.resolveRequestVar(
1111             pResult.optionValue(AUTHENTICATIONHOST), sHandle,
1112             info.requestNumber);
1113 
1114         if (res.rc != 0) return res;
1115 
1116         String key = res.result;
1117 
1118         // Resolve the AUTHENTICATIONUSER option value
1119 
1120         res = STAFUtil.resolveRequestVar(
1121             pResult.optionValue(AUTHENTICATIONUSER), sHandle,
1122             info.requestNumber);
1123 
1124         if (res.rc != 0) return res;
1125 
1126         String user = res.result;
1127 
1128         String pwd = "";
1129         if (pResult.optionTimes(AUTHENTICATIONPWD) > 0)
1130         {
1131             // Resolve the AUTHENTICATIONPWD option value
1132 
1133             res = STAFUtil.resolveRequestVar(
1134                 pResult.optionValue(AUTHENTICATIONPWD), sHandle,
1135                 info.requestNumber);
1136 
1137             if (res.rc != 0) return res;
1138 
1139             // Remove privacy delimiters.  Can remove since never show
1140             // true value of a authentication password on a query request.
1141             pwd = STAFUtil.removePrivacyDelimiters(res.result);
1142         }
1143 
1144         String domain = "";
1145 
1146         if (pResult.optionTimes(AUTHENTICATIONDOMAIN) > 0)
1147         {
1148             // Resolve the AUTHENTICATIONDOMAIN option value
1149 
1150             res = STAFUtil.resolveRequestVar(
1151                 pResult.optionValue(AUTHENTICATIONDOMAIN), sHandle,
1152                 info.requestNumber);
1153 
1154             if (res.rc != 0) return res;
1155 
1156             domain = res.result;
1157         }
1158 
1159         session.setAuthenticationSet(key, user, pwd, domain);
1160 
1161     }
1162     else if (pResult.optionTimes(NOAUTOREDIRECT) > 0)
1163     {
1164         session.setDefaultFollowRedirect(false);
1165 
1166     }
1167     else if (pResult.optionTimes(AUTOREDIRECT) > 0)
1168     {
1169         session.setDefaultFollowRedirect(true);
1170 
1171     }
1172     else if (pResult.optionTimes("PARSECONTENT") > 0)
1173     {
1174         // Resolve the PARSECONTENT option value
1175 
1176         res = STAFUtil.resolveRequestVar(
1177             pResult.optionValue("PARSECONTENT"),
1178             sHandle, info.requestNumber);
1179 
1180         if (res.rc != 0) return res;
1181 
1182         res = session.setParseContent(res.result);
1183 
1184         if (res.rc != 0) return res;
1185     }
1186     else if (pResult.optionTimes("HTTPPROXYHOST") > 0)
1187     {
1188         // Resolve the HTTPPROXYHOST option value
1189 
1190         res = STAFUtil.resolveRequestVar(
1191             pResult.optionValue("HTTPPROXYHOST"),
1192             sHandle, info.requestNumber);
1193 
1194         if (res.rc != 0) return res;
1195 
1196         String proxyHost = res.result;
1197 
1198         if (proxyHost.length() == 0)
1199         {
1200             return new STAFResult(
1201                 STAFResult.InvalidValue,
1202                 "Invalid HTTPPROXYHOST value.  Cannot be blank");
1203         }
1204 
1205         int proxyPort = -1;  // Indicates to use default proxy port
1206 
1207         if (pResult.optionTimes("HTTPPROXYPORT") > 0)
1208         {
1209             // Resolve the HTTPPROXYPORT option value and check if the
1210             // value is an integer
1211 
1212             res = STAFUtil.resolveRequestVarAndCheckInt(
1213                 "HTTPPROXYPORT", pResult.optionValue("HTTPPROXYPORT"),
1214                 sHandle, info.requestNumber);
1215 
1216             if (res.rc != 0) return res;
1217 
1218             proxyPort = Integer.parseInt(res.result);
1219 
1220             if (proxyPort < -1 || proxyPort > 65535)
1221             {
1222                 return new STAFResult(
1223                     STAFResult.InvalidValue,
1224                     "Invalid HTTPPROXYPORT value (" + proxyPort +
1225                     "). Must be in range -1 to 65535.");
1226             }
1227         }
1228 
1229         session.setHttpProxy(proxyHost, proxyPort);
1230     }
1231     else if (pResult.optionTimes(COOKIE) > 0)
1232     {
1233         if (pResult.optionTimes(POLICY) > 0)
1234         {
1235             // Resolve the POLICY option value
1236 
1237             res = STAFUtil.resolveRequestVar(
1238                 pResult.optionValue(POLICY), sHandle, info.requestNumber);
1239 
1240             if (res.rc != 0) return res;
1241 
1242             String policy = res.result;
1243 
1244             session.setCookiePolicy(policy);
1245         }
1246 
1247         // Resolve the NAME option value
1248 
1249         res = STAFUtil.resolveRequestVar(
1250             pResult.optionValue(NAME), sHandle, info.requestNumber);
1251 
1252         if (res.rc != 0) return res;
1253 
1254         String name = res.result;
1255 
1256         if (pResult.optionTimes(VALUE) > 0)
1257         {
1258             // Resolve the VALUE option value
1259 
1260             res = STAFUtil.resolveRequestVar(
1261                 pResult.optionValue(VALUE), sHandle, info.requestNumber);
1262 
1263             if (res.rc != 0) return res;
1264 
1265             String value = res.result;
1266 
1267             try
1268             {
1269                 session.setCookieValue(name, value);
1270             }
1271             catch (InvalidCookieIDException e)
1272             {
1273                 session.addCookie(name, value);
1274             }
1275         }
1276     }
1277     else if (pResult.optionTimes(FORM) > 0)
1278     {
1279         String id = "";
1280         int idType = -1;
1281 
1282         if (pResult.optionTimes(ID) > 0)
1283         {
1284             res = STAFUtil.resolveRequestVar(
1285                 pResult.optionValue(ID), sHandle, info.requestNumber);
1286 
1287             if (res.rc != 0) return res;
1288 
1289             id = res.result;
1290             idType = WebSession.ID_ID_TYPE;
1291         }
1292         else if (pResult.optionTimes(NAME) > 0)
1293         {
1294             res = STAFUtil.resolveRequestVar(
1295                 pResult.optionValue(NAME), sHandle, info.requestNumber);
1296 
1297             if (res.rc != 0) return res;
1298 
1299             id = res.result;
1300             idType = WebSession.NAME_ID_TYPE;
1301         }
1302         else if (pResult.optionTimes(INDEX) > 0)
1303         {
1304             res = STAFUtil.resolveRequestVar(
1305                 pResult.optionValue(INDEX), sHandle, info.requestNumber);
1306 
1307             if (res.rc != 0) return res;
1308 
1309             id = res.result;
1310             idType = WebSession.INDEX_ID_TYPE;
1311         }
1312         else
1313         {
1314             // default to the 1st form on the page
1315             id = "1";
1316             idType = WebSession.INDEX_ID_TYPE;
1317         }
1318 
1319         if (pResult.optionTimes(CONTROLNAME) > 0)
1320         {
1321             res = STAFUtil.resolveRequestVar(
1322                 pResult.optionValue(CONTROLNAME), sHandle, info.requestNumber);
1323 
1324             if (res.rc != 0) return res;
1325 
1326             String control = res.result;
1327 
1328             res = STAFUtil.resolveRequestVar(
1329                 pResult.optionValue(VALUE), sHandle, info.requestNumber);
1330 
1331             if (res.rc != 0) return res;
1332 
1333             String value = res.result;
1334 
1335             try
1336             {
1337                 session.setFormElement(id, idType, control, value);
1338             }
1339             catch (InvalidElementIDException e)
1340             {
1341                 return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
1342             }
1343             catch(InvalidParameterValueException e)
1344             {
1345                 return new STAFResult(STAFResult.InvalidValue, e.getMessage());
1346             }
1347         }
1348     }
1349 
1350     return new STAFResult(STAFResult.Ok, result);
1351 }
1352 
1353 /*****************************************************************************/
1354 /*                                                                           */
1355 /* Method: handleMethod                                                      */
1356 /* Description: creates the specified web request submits it, and return the */
1357 /*              output.                                                      */
1358 /* Parameters: info - request info passed to acceptRequest                   */
1359 /* Returns: STAFResult with the result of the requested method               */
1360 /*                                                                           */
1361 /*****************************************************************************/
1362 
handleMethod( STAFServiceInterfaceLevel30.RequestInfo info)1363 private STAFResult handleMethod(
1364     STAFServiceInterfaceLevel30.RequestInfo info) throws STAFException
1365 {
1366     STAFCommandParseResult pResult = requestParser.parse(info.request);
1367 
1368     if (pResult.rc != 0)
1369     {
1370         return new STAFResult(STAFResult.InvalidRequestString,
1371                               pResult.errorBuffer);
1372     }
1373 
1374     if (pResult.optionTimes(SESSION) == 0)
1375         return handleNonSessionMethod(info);
1376 
1377     return handleSessionMethod(info);
1378 
1379 }
1380 
1381 /*****************************************************************************/
1382 /*                                                                           */
1383 /* Method: handleNonSessionMethod                                            */
1384 /* Description: creates the specified web request submits it, and return the */
1385 /*              output.                                                      */
1386 /* Parameters: info - request info passed to acceptRequest                   */
1387 /* Returns: STAFResult with the result of the requested method               */
1388 /*                                                                           */
1389 /*****************************************************************************/
1390 
handleNonSessionMethod( STAFServiceInterfaceLevel30.RequestInfo info)1391 private STAFResult handleNonSessionMethod(
1392     STAFServiceInterfaceLevel30.RequestInfo info) throws STAFException
1393 {
1394     // Create a temporary new session (only used for this request)
1395     WebSession newSession = new WebSession(sessionList, info, this, true);
1396 
1397     int sessionId = newSession.getID();
1398 
1399     // add SESSION <sessionId> to info
1400     info.request += " SESSION " + sessionId;
1401 
1402     STAFResult res;
1403 
1404     try
1405     {
1406         // execute request
1407         res = handleSessionMethod(info);
1408     }
1409     catch (STAFException e)
1410     {
1411         // Perform clean-up for the temporary session
1412         cleanupNonSessionMethod(sessionId);
1413         throw e;
1414     }
1415 
1416     // Perform clean-up for the temporary session
1417     cleanupNonSessionMethod(sessionId);
1418 
1419     return res;
1420 }
1421 
1422 /*****************************************************************************/
1423 /*                                                                           */
1424 /* Method: handleSessionMethod                                               */
1425 /* Description: creates the specified web request submits it, and return the */
1426 /*              output for an existing session.                              */
1427 /* Parameters: info - request info passed to acceptRequest                   */
1428 /* Returns: STAFResult with the result of the requested method               */
1429 /*                                                                           */
1430 /*****************************************************************************/
1431 
handleSessionMethod( STAFServiceInterfaceLevel30.RequestInfo info)1432 private STAFResult handleSessionMethod(
1433     STAFServiceInterfaceLevel30.RequestInfo info) throws STAFException
1434 {
1435     // Parse the request
1436 
1437     STAFCommandParseResult pResult = requestParser.parse(info.request);
1438 
1439     if (pResult.rc != 0)
1440     {
1441         return new STAFResult(STAFResult.InvalidRequestString,
1442                               pResult.errorBuffer);
1443     }
1444 
1445     // Get method type
1446 
1447     String method = "";
1448     String action = "";
1449     STAFResult res = new STAFResult();
1450 
1451     if (pResult.optionTimes(METHOD) > 0)
1452     {
1453         res = STAFUtil.resolveRequestVar(
1454             pResult.optionValue(METHOD), sHandle, info.requestNumber);
1455 
1456         if (res.rc != 0) return res;
1457 
1458         method = res.result;
1459         action = "REQUEST METHOD";
1460     }
1461     else if (pResult.optionTimes(DOPOST) > 0)
1462     {
1463         method = "POST";
1464         action = "DOPOST";
1465     }
1466     else if (pResult.optionTimes(DOGET) > 0)
1467     {
1468         method = "GET";
1469         action = "DOGET";
1470     }
1471 
1472     // Verify the requester has at least trust level 3
1473 
1474     STAFResult trustResult = STAFUtil.validateTrust(
1475         3, fServiceName, action, fLocalMachineName, info);
1476 
1477     if (trustResult.rc != STAFResult.Ok) return trustResult;
1478 
1479     // Get resolved value for SESSION option and make sure it's an integer
1480 
1481     res = STAFUtil.resolveRequestVarAndCheckInt(
1482         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
1483 
1484     if (res.rc != 0) return res;
1485 
1486     int sessionId = Integer.parseInt(res.result);
1487 
1488     // Resolve the URL option value
1489 
1490     res = STAFUtil.resolveRequestVar(
1491         pResult.optionValue(URL), sHandle, info.requestNumber);
1492 
1493     if (res.rc != 0) return res;
1494 
1495     String url = res.result;
1496 
1497     WebSession session;
1498 
1499     // Get the session
1500     try
1501     {
1502         session = sessionList.getSession(sessionId);
1503     }
1504     catch (InvalidSessionIDException e)
1505     {
1506         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
1507     }
1508 
1509     if (!session.isOwner(info.stafInstanceUUID))
1510     {
1511         // Verify the requester has at least trust level 4 since not the
1512         // session owner
1513 
1514         trustResult = STAFUtil.validateTrust(
1515             4, fServiceName, action, fLocalMachineName, info);
1516 
1517         if (trustResult.rc != STAFResult.Ok) return trustResult;
1518     }
1519 
1520     // Get headers
1521 
1522     int numHeaders = pResult.optionTimes(HEADER);
1523     HashMap headers = null;
1524 
1525     if (numHeaders > 0)
1526     {
1527         headers = new HashMap();
1528 
1529         for (int i = 1; i <= numHeaders; i++)
1530         {
1531             res = STAFUtil.resolveRequestVar(
1532                 pResult.optionValue(HEADER, i), sHandle, info.requestNumber);
1533 
1534             if (res.rc != 0) return res;
1535 
1536             String h = res.result;
1537             int equalPos = h.indexOf("=");
1538 
1539             if (equalPos == -1)
1540             {
1541                 return new STAFResult(STAFResult.InvalidValue,
1542                                       "Invalid HEADER: " + h);
1543             }
1544 
1545             String key = h.substring(0, equalPos);
1546             String value = h.substring(equalPos + 1);
1547             headers.put(key, value);
1548         }
1549     }
1550 
1551     // Get POST parameters
1552 
1553     Vector params = new Vector();
1554     int numParams = pResult.optionTimes(PARAMETER);
1555 
1556     if (numParams > 0)
1557     {
1558         for (int i = 1; i <= numParams; i++)
1559         {
1560             res = STAFUtil.resolveRequestVar(
1561                 pResult.optionValue(PARAMETER, i), sHandle, info.requestNumber);
1562 
1563             if (res.rc != 0) return res;
1564 
1565             String h = res.result;
1566             int equalPos = h.indexOf("=");
1567 
1568             if (equalPos == -1)
1569             {
1570                 return new STAFResult(STAFResult.InvalidValue,
1571                                       "Invalid PARAMETER: " + h);
1572             }
1573 
1574             String key = h.substring(0, equalPos);
1575             String value = h.substring(equalPos + 1);
1576 
1577             Vector pair = new Vector(2);
1578             pair.addElement(key);
1579             pair.addElement(value);
1580 
1581             params.addElement(pair);
1582         }
1583     }
1584     else
1585         params = null;
1586 
1587     // Files to be added to the request
1588     Vector files = new Vector();
1589     int numFiles = pResult.optionTimes(CONTENTFILE);
1590 
1591     if (numFiles > 0)
1592     {
1593         for (int i = 1; i <= numFiles; i++)
1594         {
1595             res = STAFUtil.resolveRequestVar(
1596                 pResult.optionValue(CONTENTFILE, i), sHandle,
1597                 info.requestNumber);
1598 
1599             if (res.rc != 0) return res;
1600 
1601             String h = res.result;
1602             int equalPos = h.indexOf("=");
1603 
1604             if (equalPos == -1)
1605             {
1606                 return new STAFResult(STAFResult.InvalidValue,
1607                                       "Invalid CONTENTFILE: " + h);
1608             }
1609 
1610             String key = h.substring(0, equalPos);
1611             String value = h.substring(equalPos + 1);
1612 
1613             // if CONTENTFILEMACHINE option enabled
1614             //   get ContentFileMachine with same key / parameter name
1615             //   copy file from contentFileMachine to
1616             //    service temp dir
1617             //   change value to temp file path
1618 
1619             Vector pair = new Vector(2);
1620             pair.addElement(key);
1621             pair.addElement(value);
1622 
1623             files.addElement(pair);
1624        }
1625     }
1626     else
1627         files = null;
1628 
1629     // Get content
1630 
1631     String content = null;
1632 
1633     if (pResult.optionTimes(CONTENT) > 0)
1634     {
1635         // Ignore any errors resolving variables in the CONTENT option's value
1636         // as it could contain "{" characters that don't denote STAF variables
1637 
1638         res = resolveRequestVarIgnoreErrors(
1639             pResult.optionValue(CONTENT), sHandle, info.requestNumber);
1640 
1641         if (res.rc != 0) return res;
1642 
1643         content = res.result;
1644     }
1645 
1646     // Resolve auto redirection on 3XX returns
1647 
1648     Boolean redirect = null;
1649     if (pResult.optionTimes(AUTOREDIRECT) > 0)
1650         redirect = new Boolean(true);
1651     if (pResult.optionTimes(NOAUTOREDIRECT) > 0)
1652         redirect = new Boolean(false);
1653 
1654     // Check if the toFile option was specified
1655 
1656     String toFile = null;
1657 
1658     if (pResult.optionTimes(FILE) > 0)
1659     {
1660         res = STAFUtil.resolveRequestVar(
1661             pResult.optionValue(FILE), sHandle, info.requestNumber);
1662 
1663         if (res.rc != STAFResult.Ok) return res;
1664 
1665         toFile = res.result;
1666     }
1667 
1668     String toMachine = null;
1669 
1670     if (pResult.optionTimes(TOMACHINE) > 0)
1671     {
1672         res = STAFUtil.resolveRequestVar(
1673             pResult.optionValue(TOMACHINE), sHandle, info.requestNumber);
1674 
1675         if (res.rc != STAFResult.Ok) return res;
1676 
1677         toMachine = res.result;
1678     }
1679 
1680     // Assign the url encoded option (defaults to false unless the ENCODED
1681     // option is specified.  This option says whether the URL is already
1682     // escaped-encoded
1683 
1684     boolean encoded = false;
1685 
1686     if (pResult.optionTimes(ENCODED) > 0)
1687         encoded = true;
1688 
1689     // Send request
1690 
1691     try
1692     {
1693         session.requestMethod(url, method, headers, params, files, content,
1694                               redirect, toFile, toMachine, encoded);
1695     }
1696     catch (MalformedURLException e)
1697     {
1698         if (e.getMessage() != null)
1699         {
1700             if (e.getMessage().equals("Bad Method"))
1701                 return new STAFResult(INVALIDMETHOD, method);
1702 
1703             if (e.getMessage().startsWith("Invalid URI"))
1704                 return new STAFResult(UNKNOWNHOST, e.getMessage());
1705 
1706             if (e.getMessage().startsWith("Invalid protocol"))
1707                 return new STAFResult(IOEXCEPTION, e.getMessage());
1708         }
1709 
1710         return new STAFResult(STAFResult.InvalidRequestString, e.getMessage());
1711 
1712     }
1713     catch (HttpException e)
1714     {
1715         return new STAFResult(STAFResult.UserDefined,
1716             e.getMessage());
1717 
1718     }
1719     catch(UnknownHostException uhe)
1720     {
1721         return new STAFResult(UNKNOWNHOST, "Unknown Host: " + url);
1722 
1723     }
1724     catch(ConnectException ce)
1725     {
1726         return new STAFResult(CONNECTERROR, "Connection Refused: " + url);
1727 
1728     }
1729     catch (FileNotFoundException e)
1730     {
1731         // error in getting files to be added to a post
1732         return new STAFResult(STAFResult.FileOpenError, e.getMessage());
1733 
1734     }
1735     catch (IOException e)
1736     {
1737         // error getting page
1738 
1739         // XXX this is a hack
1740         //  invalid url error not coming back correctly
1741         if ((e.getMessage() != null) && (e.getMessage().equals(url)))
1742             return new STAFResult(UNKNOWNHOST, "Unknown Host: " + url);
1743 
1744         // Return the Java stack trace in the result
1745 
1746         StringWriter sr = new StringWriter();
1747         e.printStackTrace(new PrintWriter(sr));
1748 
1749         return new STAFResult(
1750             IOEXCEPTION, "Error getting target url\n" + e + "\n" +
1751             sr.toString());
1752     }
1753     catch (STAFException e)
1754     {
1755         return new STAFResult(e.rc, e.getMessage());
1756     }
1757     catch (Exception e)
1758     {
1759         // unexpected error
1760         java.io.StringWriter sr = new java.io.StringWriter();
1761         e.printStackTrace(new java.io.PrintWriter(sr));
1762         System.err.println(sr.toString());
1763 
1764         return new STAFResult(STAFResult.UserDefined,
1765             "HttpClient Error\n" + e + "\n" + e.getMessage());
1766     }
1767 
1768     return getHttpResponse(info, pResult);
1769 }
1770 
1771 /*****************************************************************************/
1772 /*                                                                           */
1773 /* Method: handleFormAction                                                  */
1774 /* Description: performs the desired form interaction                        */
1775 /* Parameters: info - request info passed to acceptRequest                */
1776 /* Returns: STAFResult.OK or the http result of submitting the form          */
1777 /*                                                                           */
1778 /*****************************************************************************/
1779 
handleFormAction(STAFServiceInterfaceLevel30.RequestInfo info)1780 private STAFResult handleFormAction(STAFServiceInterfaceLevel30.RequestInfo
1781                                    info) throws STAFException
1782 {
1783     // Parse the request
1784 
1785     STAFCommandParseResult pResult = htmlActionParser.parse(info.request);
1786 
1787     if (pResult.rc != 0)
1788     {
1789         return new STAFResult(STAFResult.InvalidRequestString,
1790                               pResult.errorBuffer);
1791     }
1792 
1793     String formAction = "SUBMIT FORM";
1794 
1795     if (pResult.optionTimes(RESET) > 0)
1796         formAction = "RESET FORM";
1797 
1798     // Verify the requester has at least trust level 3
1799 
1800     STAFResult trustResult = STAFUtil.validateTrust(
1801         3, fServiceName, formAction, fLocalMachineName, info);
1802 
1803     if (trustResult.rc != STAFResult.Ok) return trustResult;
1804 
1805     // Get resolved value for SESSION option and make sure it's an integer
1806 
1807     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
1808         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
1809 
1810     if (res.rc != 0) return res;
1811 
1812     int sessionId = Integer.parseInt(res.result);
1813 
1814     WebSession session;
1815 
1816     // Get the session
1817 
1818     try
1819     {
1820         session = sessionList.getSession(sessionId);
1821 
1822     }
1823     catch (InvalidSessionIDException e)
1824     {
1825         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
1826     }
1827 
1828     if (!session.isOwner(info.stafInstanceUUID))
1829     {
1830         // Verify the requester has at least trust level 4 if not session owner
1831 
1832         trustResult = STAFUtil.validateTrust(
1833             4, fServiceName, formAction, fLocalMachineName, info);
1834 
1835         if (trustResult.rc != STAFResult.Ok) return trustResult;
1836     }
1837 
1838     // Resolve auto redirection on 3XX returns
1839 
1840     Boolean redirect = null;
1841 
1842     if (pResult.optionTimes(AUTOREDIRECT) > 0)
1843         redirect = new Boolean(true);
1844 
1845     if (pResult.optionTimes(NOAUTOREDIRECT) > 0)
1846         redirect = new Boolean(false);
1847 
1848     String id = "";
1849     int idType = -1;
1850 
1851     if (pResult.optionTimes(ID) > 0)
1852     {
1853         res = STAFUtil.resolveRequestVar(
1854             pResult.optionValue(ID), sHandle, info.requestNumber);
1855 
1856         if (res.rc != 0) return res;
1857 
1858         id = res.result;
1859         idType = WebSession.ID_ID_TYPE;
1860 
1861     }
1862     else if (pResult.optionTimes(NAME) > 0)
1863     {
1864         res = STAFUtil.resolveRequestVar(
1865             pResult.optionValue(NAME), sHandle, info.requestNumber);
1866 
1867         if (res.rc != 0) return res;
1868 
1869         id = res.result;
1870         idType = WebSession.NAME_ID_TYPE;
1871 
1872     }
1873     else if (pResult.optionTimes(INDEX) > 0)
1874     {
1875         res = STAFUtil.resolveRequestVar(
1876             pResult.optionValue(INDEX), sHandle, info.requestNumber);
1877 
1878         if (res.rc != 0) return res;
1879 
1880         id = res.result;
1881         idType = WebSession.INDEX_ID_TYPE;
1882 
1883     }
1884     else
1885     {
1886         // default to the 1st form on the page
1887         id = "1";
1888         idType = WebSession.INDEX_ID_TYPE;
1889     }
1890 
1891     String result = "";
1892 
1893     try
1894     {
1895         if (pResult.optionTimes(RESET) > 0)
1896         {
1897             session.resetForm(id, idType);
1898 
1899         }else if (pResult.optionTimes(SUBMIT) > 0)
1900         {
1901             session.submitForm(id, idType, redirect);
1902 
1903             return getHttpResponse(info, pResult);
1904         }
1905 
1906     }catch (InvalidElementIDException e)
1907     {
1908         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
1909 
1910     }catch (MalformedURLException e)
1911     {
1912         if (e.getMessage() != null)
1913         {
1914             if (e.getMessage().equals("Bad Method"))
1915                 return new STAFResult(INVALIDMETHOD, e.getMessage());
1916 
1917             if (e.getMessage().startsWith("Invalid URI"))
1918                 return new STAFResult(UNKNOWNHOST, e.getMessage());
1919 
1920             if (e.getMessage().startsWith("Invalid protocol"))
1921                 return new STAFResult(IOEXCEPTION, e.getMessage());
1922         }
1923 
1924         return new STAFResult(STAFResult.InvalidRequestString, e.getMessage());
1925 
1926     }catch (HttpException e)
1927     {
1928         return new STAFResult(STAFResult.UserDefined,
1929             e.getMessage());
1930 
1931     }catch(UnknownHostException uhe)
1932     {
1933         return new STAFResult(UNKNOWNHOST, uhe.getMessage());
1934 
1935     }catch(ConnectException ce)
1936     {
1937         return new STAFResult(CONNECTERROR, ce.getMessage());
1938 
1939     }catch (FileNotFoundException e)
1940     {
1941         // error in getting files to be added to a post
1942         return new STAFResult(STAFResult.FileOpenError, e.getMessage());
1943 
1944     }catch (IOException e)
1945     {
1946         // error getting page
1947         return new STAFResult(IOEXCEPTION,
1948             "Error getting target url\n" + e + "\n" + e.getMessage());
1949 
1950     }catch (Exception e)
1951     {
1952         // unexpected error
1953 
1954         return new STAFResult(STAFResult.UserDefined,
1955             "HttpClient Error\n" + e.getMessage());
1956     }
1957 
1958     return new STAFResult(STAFResult.Ok, result);
1959 }
1960 
1961 /*****************************************************************************/
1962 /*                                                                           */
1963 /* Method: handleFollow                                                      */
1964 /* Description: follows the specified link                                   */
1965 /* Parameters: info - request info passed to acceptRequest                */
1966 /* Returns: STAFResult with the http result of following the link            */
1967 /*                                                                           */
1968 /*****************************************************************************/
1969 
handleFollow(STAFServiceInterfaceLevel30.RequestInfo info)1970 private STAFResult handleFollow(STAFServiceInterfaceLevel30.RequestInfo
1971                                    info) throws STAFException
1972 {
1973     // Verify the requester has at least trust level 3
1974 
1975     STAFResult trustResult = STAFUtil.validateTrust(
1976         3, fServiceName, "FOLLOW", fLocalMachineName, info);
1977 
1978     if (trustResult.rc != STAFResult.Ok) return trustResult;
1979 
1980     // Parse the request
1981 
1982     STAFCommandParseResult pResult = htmlActionParser.parse(info.request);
1983 
1984     if (pResult.rc != 0)
1985     {
1986         return new STAFResult(STAFResult.InvalidRequestString,
1987                               pResult.errorBuffer);
1988     }
1989 
1990     // Get resolved value for SESSION option and make sure it's an integer
1991 
1992     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
1993         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
1994 
1995     if (res.rc != 0) return res;
1996 
1997     int sessionId = Integer.parseInt(res.result);
1998 
1999     WebSession session;
2000 
2001     // Get the session
2002 
2003     try
2004     {
2005         session = sessionList.getSession(sessionId);
2006 
2007     }
2008     catch (InvalidSessionIDException e)
2009     {
2010         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2011     }
2012 
2013     if (!session.isOwner(info.stafInstanceUUID))
2014     {
2015         // Verify the requester has at least trust level 4 if not session owner
2016 
2017         trustResult = STAFUtil.validateTrust(
2018             4, fServiceName, "FOLLOW", fLocalMachineName, info);
2019 
2020         if (trustResult.rc != STAFResult.Ok) return trustResult;
2021     }
2022 
2023     // Resolve auto redirection on 3XX returns
2024 
2025     Boolean redirect = null;
2026 
2027     if (pResult.optionTimes(AUTOREDIRECT) > 0)
2028         redirect = new Boolean(true);
2029 
2030     if (pResult.optionTimes(NOAUTOREDIRECT) > 0)
2031         redirect = new Boolean(false);
2032 
2033     String id = "";
2034     int idType = -1;
2035 
2036     if (pResult.optionTimes(ID) > 0)
2037     {
2038         res = STAFUtil.resolveRequestVar(
2039             pResult.optionValue(ID), sHandle, info.requestNumber);
2040 
2041         if (res.rc != 0) return res;
2042 
2043         id = res.result;
2044         idType = WebSession.ID_ID_TYPE;
2045     }
2046     else if (pResult.optionTimes(NAME) > 0)
2047     {
2048         res = STAFUtil.resolveRequestVar(
2049             pResult.optionValue(NAME), sHandle, info.requestNumber);
2050 
2051         if (res.rc != 0) return res;
2052 
2053         id = res.result;
2054         idType = WebSession.NAME_ID_TYPE;
2055     }
2056     else if (pResult.optionTimes(INDEX) > 0)
2057     {
2058         res = STAFUtil.resolveRequestVar(
2059             pResult.optionValue(INDEX), sHandle, info.requestNumber);
2060 
2061         if (res.rc != 0) return res;
2062 
2063         id = res.result;
2064         idType = WebSession.INDEX_ID_TYPE;
2065     }
2066     else
2067         return new STAFResult(STAFResult.DoesNotExist,"No Link Specified.");
2068 
2069     try
2070     {
2071         session.followLink(id, idType, redirect);
2072     }
2073     catch (InvalidElementIDException e)
2074     {
2075         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2076 
2077     }
2078     catch (MalformedURLException e)
2079     {
2080         if (e.getMessage() != null)
2081         {
2082             if (e.getMessage().startsWith("Invalid URI"))
2083                 return new STAFResult(UNKNOWNHOST, e.getMessage());
2084 
2085             if (e.getMessage().startsWith("Invalid protocol"))
2086                 return new STAFResult(IOEXCEPTION, e.getMessage());
2087         }
2088 
2089         return new STAFResult(STAFResult.InvalidRequestString, e.getMessage());
2090 
2091     }
2092     catch (HttpException e)
2093     {
2094         return new STAFResult(STAFResult.UserDefined, e.getMessage());
2095 
2096     }
2097     catch(UnknownHostException uhe)
2098     {
2099         return new STAFResult(UNKNOWNHOST, uhe.getMessage());
2100 
2101     }
2102     catch(ConnectException ce)
2103     {
2104         return new STAFResult(CONNECTERROR, ce.getMessage());
2105 
2106     }
2107     catch (IOException e)
2108     {
2109         // error getting page
2110 
2111         return new STAFResult(IOEXCEPTION,
2112             "Error getting target url\n" + e + "\n" + e.getMessage());
2113 
2114     }
2115     catch (STAFException e)
2116     {
2117         return new STAFResult(e.rc, e.getMessage());
2118     }
2119     catch (Exception e)
2120     {
2121         // unexpected error
2122 
2123         return new STAFResult(
2124             STAFResult.UserDefined, "HttpClient Error\n" + e.getMessage());
2125     }
2126 
2127     return getHttpResponse(info, pResult);
2128 }
2129 
2130 /*****************************************************************************/
2131 /*                                                                           */
2132 /* Method: handleDelete                                                      */
2133 /* Description: Deltes a cookie from the session.                            */
2134 /* Parameters: info - request info passed to acceptRequest                */
2135 /* Returns: STAFResult.OK                                                    */
2136 /*                                                                           */
2137 /*****************************************************************************/
2138 
handleDelete(STAFServiceInterfaceLevel30.RequestInfo info)2139 private STAFResult handleDelete(STAFServiceInterfaceLevel30.RequestInfo info)
2140                                throws STAFException
2141 {
2142     // Verify the requester has at least trust level 3
2143 
2144     STAFResult trustResult = STAFUtil.validateTrust(
2145         3, fServiceName, "DELETE", fLocalMachineName, info);
2146 
2147     if (trustResult.rc != STAFResult.Ok) return trustResult;
2148 
2149     // Parse the request
2150 
2151     STAFCommandParseResult pResult = delCloseParser.parse(info.request);
2152 
2153     if (pResult.rc != 0)
2154     {
2155         return new STAFResult(STAFResult.InvalidRequestString,
2156                               pResult.errorBuffer);
2157     }
2158 
2159     // Get resolved value for SESSION option and make sure it's an integer
2160 
2161     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
2162         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
2163 
2164     if (res.rc != 0) return res;
2165 
2166     int sessionId = Integer.parseInt(res.result);
2167 
2168     WebSession session;
2169 
2170     // Get the session
2171 
2172     try
2173     {
2174         session = sessionList.getSession(sessionId);
2175     }
2176     catch (InvalidSessionIDException e)
2177     {
2178         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2179     }
2180 
2181     if (!session.isOwner(info.stafInstanceUUID))
2182     {
2183         // Verify the requester has at least trust level 4 since not
2184         // session owner
2185 
2186         trustResult = STAFUtil.validateTrust(
2187             4, fServiceName, "DELETE", fLocalMachineName, info);
2188 
2189         if (trustResult.rc != STAFResult.Ok) return trustResult;
2190     }
2191 
2192     if (pResult.optionTimes(DEFAULTHEADER) > 0)
2193     {
2194         res = STAFUtil.resolveRequestVar(
2195             pResult.optionValue(DEFAULTHEADER), sHandle, info.requestNumber);
2196 
2197         if (res.rc != 0) return res;
2198 
2199         String key = res.result;
2200 
2201         try
2202         {
2203             session.deleteDefaultHeader(key);
2204         }
2205         catch (InvalidElementIDException e)
2206         {
2207             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2208         }
2209 
2210     }
2211     else if (pResult.optionTimes(AUTHENTICATIONHOST) > 0)
2212     {
2213         res = STAFUtil.resolveRequestVar(
2214             pResult.optionValue(AUTHENTICATIONHOST), sHandle, info.requestNumber);
2215 
2216         if (res.rc != 0) return res;
2217 
2218         String key = res.result;
2219 
2220         try
2221         {
2222             session.deleteAuthenticationSet(key);
2223         }
2224         catch (InvalidElementIDException e)
2225         {
2226             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2227         }
2228 
2229     }
2230     else if(pResult.optionTimes(COOKIE) > 0)
2231     {
2232         res = STAFUtil.resolveRequestVar(
2233             pResult.optionValue(NAME), sHandle, info.requestNumber);
2234 
2235         if (res.rc != 0) return res;
2236 
2237         String name = res.result;
2238 
2239         try
2240         {
2241             session.deleteCookie(name);
2242         }
2243         catch (InvalidCookieIDException e)
2244         {
2245             return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2246         }
2247     }
2248 
2249     return new STAFResult(STAFResult.Ok,"");
2250 }
2251 
2252 /*****************************************************************************/
2253 /*                                                                           */
2254 /* Method: handleGetPage                                                     */
2255 /* Description: gets the contents of the current page of the specified       */
2256 /*              session                                                      */
2257 /* Parameters: info - request info passed to acceptRequest                */
2258 /* Returns: STAFResult.OK                                                    */
2259 /*                                                                           */
2260 /*****************************************************************************/
2261 
handleGetPage(STAFServiceInterfaceLevel30.RequestInfo info)2262 private STAFResult handleGetPage(STAFServiceInterfaceLevel30.RequestInfo
2263                                    info) throws STAFException
2264 {
2265     // Verify the requester has at least trust level 3
2266 
2267     STAFResult trustResult = STAFUtil.validateTrust(
2268         3, fServiceName, "GET", fLocalMachineName, info);
2269 
2270     if (trustResult.rc != STAFResult.Ok) return trustResult;
2271 
2272     // Parse the request
2273 
2274     STAFCommandParseResult pResult = getParser.parse(info.request);
2275 
2276     if (pResult.rc != 0)
2277     {
2278         return new STAFResult(STAFResult.InvalidRequestString,
2279                               pResult.errorBuffer);
2280     }
2281 
2282     // Get resolved value for SESSION option and make sure it's an integer
2283 
2284     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
2285         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
2286 
2287     if (res.rc != 0) return res;
2288 
2289     int sessionId = Integer.parseInt(res.result);
2290 
2291     WebSession session;
2292 
2293     // Get the session
2294 
2295     try
2296     {
2297         session = sessionList.getSession(sessionId);
2298     }
2299     catch (InvalidSessionIDException e)
2300     {
2301         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2302     }
2303 
2304     String result = "";
2305 
2306     // Get the content
2307 
2308     if (pResult.optionTimes(FILE) == 0)
2309     {
2310         // Get the content as a string
2311 
2312         try
2313         {
2314             result = session.getCurrentContents();
2315         }
2316         catch (STAFException e)
2317         {
2318             return new STAFResult(e.rc, e.getMessage());
2319         }
2320         catch (ContentTooLargeException e)
2321         {
2322             return new STAFResult(CONTENTTOOLARGE, e.toString());
2323         }
2324     }
2325     else // pResult.optionTimes(FILE) > 0
2326     {
2327         res = STAFUtil.resolveRequestVar(
2328             pResult.optionValue(FILE), sHandle, info.requestNumber);
2329 
2330         if (res.rc != 0) return res;
2331 
2332         String fileName = res.result;
2333 
2334         String machineName = null;
2335 
2336         if (pResult.optionTimes(TOMACHINE) > 0)
2337         {
2338             res = STAFUtil.resolveRequestVar(
2339                 pResult.optionValue(TOMACHINE), sHandle, info.requestNumber);
2340 
2341             if (res.rc != 0) return res;
2342 
2343             machineName = res.result;
2344         }
2345 
2346         // Write the result content to the specified file
2347         try
2348         {
2349             session.writeContentToFile(fileName, machineName);
2350         }
2351         catch(IOException e)
2352         {
2353             return new STAFResult(
2354                 STAFResult.FileWriteError,
2355                 "Error writing the content to a file.\n" + e.toString());
2356         }
2357         catch(STAFException e)
2358         {
2359             return new STAFResult(
2360                 e.rc, "Error writing the content to a file.\n" +
2361                 e.getMessage());
2362         }
2363         catch(Exception e)
2364         {
2365             return new STAFResult(
2366                 STAFResult.FileWriteError,
2367                 "Unexpected exception writing the content to a file.\n" +
2368                 e.toString());
2369         }
2370     }
2371 
2372     return new STAFResult(STAFResult.Ok, result);
2373 }
2374 
2375 /*****************************************************************************/
2376 /*                                                                           */
2377 /* Method: getHttpResponse                                                   */
2378 /* Description: format the output of a http request.                         */
2379 /* Parameters: info - request info passed to acceptRequest                   */
2380 /*             pResult - parsed result of the accepted request               */
2381 /* Returns: STAFResult with the result of the last http request              */
2382 /*                                                                           */
2383 /*****************************************************************************/
2384 
getHttpResponse(STAFServiceInterfaceLevel30.RequestInfo info, STAFCommandParseResult pResult)2385 private STAFResult getHttpResponse(STAFServiceInterfaceLevel30.RequestInfo
2386                                    info, STAFCommandParseResult pResult)
2387                                    throws STAFException
2388 {
2389     // Get resolved value for SESSION option and make sure it's an integer
2390 
2391     STAFResult res = STAFUtil.resolveRequestVarAndCheckInt(
2392         SESSION, pResult.optionValue(SESSION), sHandle, info.requestNumber);
2393 
2394     if (res.rc != 0) return res;
2395 
2396     int sessionId = Integer.parseInt(res.result);
2397 
2398     WebSession session;
2399 
2400     // Get the session
2401 
2402     try
2403     {
2404         session = sessionList.getSession(sessionId);
2405     }
2406     catch (InvalidSessionIDException e)
2407     {
2408         return new STAFResult(STAFResult.DoesNotExist, e.getMessage());
2409     }
2410 
2411     boolean showContent = (pResult.optionTimes(NOCONTENT) == 0);
2412     boolean showHeaders = (pResult.optionTimes(RETURNHEADERS) > 0);
2413     boolean status = (pResult.optionTimes(NOSTATUS) == 0);
2414     boolean ignoreErrors = (pResult.optionTimes(IGNOREERRORS) > 0);
2415 
2416     int rc = STAFResult.Ok;
2417 
2418     STAFMarshallingContext mc = new STAFMarshallingContext();
2419     mc.setMapClassDefinition(fHttpResultMapClass);
2420     Map resultMap = fHttpResultMapClass.createInstance();
2421 
2422     int httpRc = session.getCurrentStatusCode();
2423 
2424     if ((!ignoreErrors) && (httpRc > 399) && (httpRc < 600))
2425     {
2426         rc = httpRc + STAFResult.UserDefined;
2427     }
2428 
2429     HashMap response = session.getHttpResponse();
2430 
2431     if (status)
2432     {
2433         resultMap.put("statusCode",
2434                       response.get(WebSession.RETURN_STATUS_CODE));
2435         resultMap.put("statusMessage",
2436                       response.get(WebSession.RETURN_STATUS_MESSAGE));
2437     }
2438 
2439     if (showHeaders)
2440     {
2441         resultMap.put("headers", response.get(WebSession.RETURN_HEADERS));
2442     }
2443 
2444     boolean wroteToFile = false;
2445 
2446     if (pResult.optionTimes(FILE) > 0 )
2447     {
2448         res = STAFUtil.resolveRequestVar(
2449             pResult.optionValue(FILE), sHandle, info.requestNumber);
2450 
2451         if (res.rc != 0) return res;
2452 
2453         String fileName = res.result;
2454 
2455         String machineName = null;
2456 
2457         if (pResult.optionTimes(TOMACHINE) > 0)
2458         {
2459             res = STAFUtil.resolveRequestVar(
2460                 pResult.optionValue(TOMACHINE), sHandle, info.requestNumber);
2461 
2462             if (res.rc != 0) return res;
2463 
2464             machineName = res.result;
2465         }
2466 
2467         try
2468         {
2469             // Write the result content to the specified file
2470             session.writeContentToFile(fileName, machineName);
2471 
2472             if (HTTP.DEBUG)
2473             {
2474                 System.out.println(
2475                     "Completed writing content to file " + fileName +
2476                     " on machine " + machineName);
2477             }
2478 
2479             // Successfully wrote to file so don't return content in result
2480             wroteToFile = true;
2481         }
2482         catch(IOException ioe)
2483         {
2484             String result = "Error writing the content to a file.\n" +
2485                 ioe.toString();
2486 
2487             if (resultMap.get("statusCode") == null)
2488                 result += "\nStatus Code   : <None>";
2489             else
2490                 result += "\nStatus Code   : " + resultMap.get("statusCode");
2491 
2492             if (resultMap.get("statusMessage") == null)
2493                 result += "\nStatus Message: <None>";
2494             else
2495                 result += "\nStatus Message: " + resultMap.get("statusMessage");
2496 
2497             if (resultMap.get("content") == null)
2498                 result += "\nHeaders       : <None>";
2499             else
2500                 result += "\nHeaders       : " + resultMap.get("headers");
2501 
2502             result += "\nContent       : <None>";
2503 
2504             return new STAFResult(STAFResult.FileWriteError, result);
2505         }
2506         catch (STAFException se)
2507         {
2508             String result = "Error writing the content to a file.\n" +
2509                 se.getMessage();
2510 
2511             if (resultMap.get("statusCode") == null)
2512                 result += "\nStatus Code   : <None>";
2513             else
2514                 result += "\nStatus Code   : " + resultMap.get("statusCode");
2515 
2516             if (resultMap.get("statusMessage") == null)
2517                 result += "\nStatus Message: <None>";
2518             else
2519                 result += "\nStatus Message: " + resultMap.get("statusMessage");
2520 
2521             if (resultMap.get("content") == null)
2522                 result += "\nHeaders       : <None>";
2523             else
2524                 result += "\nHeaders       : " + resultMap.get("headers");
2525 
2526             result += "\nContent       : <None>";
2527 
2528             return new STAFResult(STAFResult.FileWriteError, result);
2529         }
2530     }
2531 
2532     if (showContent && !wroteToFile)
2533     {
2534         try
2535         {
2536             resultMap.put("content", session.getCurrentContents());
2537         }
2538         catch (STAFException e)
2539         {
2540             return new STAFResult(e.rc, e.getMessage());
2541         }
2542         catch (ContentTooLargeException e)
2543         {
2544             return new STAFResult(CONTENTTOOLARGE, e.toString());
2545         }
2546     }
2547 
2548     mc.setRootObject(resultMap);
2549 
2550     return new STAFResult(rc, mc.marshall());
2551 }
2552 
2553 /*****************************************************************************/
2554 /*                                                                           */
2555 /* Method: help                                                              */
2556 /* Description: returns service help information                             */
2557 /* Parameters: none                                                          */
2558 /* Returns: STAFResult.OK                                                    */
2559 /*                                                                           */
2560 /*****************************************************************************/
2561 
help(STAFServiceInterfaceLevel30.RequestInfo info)2562 private STAFResult help(STAFServiceInterfaceLevel30.RequestInfo info)
2563 {
2564     // Verify the requester has at least trust level 1
2565 
2566     STAFResult trustResult = STAFUtil.validateTrust(
2567         1, fServiceName, "HELP", fLocalMachineName, info);
2568 
2569     if (trustResult.rc != STAFResult.Ok) return trustResult;
2570 
2571     // Return help text for the service
2572 
2573     return new STAFResult(STAFResult.Ok, sHelpMsg);
2574 }
2575 
2576 
2577 /*****************************************************************************/
2578 /*                                                                           */
2579 /* Method: init                                                              */
2580 /* Description: required by interface STAFServiceInterfaceLevel30            */
2581 /*              creates parsers and registers with STAF                      */
2582 /*                                                                           */
2583 /*****************************************************************************/
2584 
init(STAFServiceInterfaceLevel30.InitInfo initInfo)2585 public STAFResult init(STAFServiceInterfaceLevel30.InitInfo initInfo)
2586 {
2587     /* Generate parsers */
2588     requestParser = new STAFCommandParser();
2589 
2590     requestParser.addOption(REQUEST, 1, STAFCommandParser.VALUENOTALLOWED);
2591     requestParser.addOption(DOPOST, 1, STAFCommandParser.VALUENOTALLOWED);
2592     requestParser.addOption(DOGET, 1, STAFCommandParser.VALUENOTALLOWED);
2593     requestParser.addOption(METHOD, 1, STAFCommandParser.VALUEREQUIRED);
2594     requestParser.addOption(URL, 1, STAFCommandParser.VALUEREQUIRED);
2595     requestParser.addOption(ENCODED, 1, STAFCommandParser.VALUENOTALLOWED);
2596     requestParser.addOption(CONTENT, 1, STAFCommandParser.VALUEREQUIRED);
2597     requestParser.addOption(PARAMETER, 0, STAFCommandParser.VALUEREQUIRED);
2598     requestParser.addOption(CONTENTFILE, 0, STAFCommandParser.VALUEREQUIRED);
2599     requestParser.addOption(HEADER, 0, STAFCommandParser.VALUEREQUIRED);
2600     requestParser.addOption(FILE, 1, STAFCommandParser.VALUEREQUIRED);
2601     requestParser.addOption(TOMACHINE, 1, STAFCommandParser.VALUEREQUIRED);
2602     requestParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2603     requestParser.addOption(IGNOREERRORS, 1, STAFCommandParser.VALUENOTALLOWED);
2604     requestParser.addOption(NOSTATUS, 1, STAFCommandParser.VALUENOTALLOWED);
2605     requestParser.addOption(RETURNHEADERS, 1, STAFCommandParser.VALUENOTALLOWED);
2606     requestParser.addOption(NOCONTENT, 1, STAFCommandParser.VALUENOTALLOWED);
2607     requestParser.addOption(AUTOREDIRECT, 1, STAFCommandParser.VALUENOTALLOWED);
2608     requestParser.addOption(NOAUTOREDIRECT, 1, STAFCommandParser.VALUENOTALLOWED);
2609 
2610     requestParser.addOptionGroup(URL, 1, 1);
2611     requestParser.addOptionGroup(DOGET + " " + CONTENTFILE, 0, 1);
2612     requestParser.addOptionGroup(NOAUTOREDIRECT + " " + AUTOREDIRECT, 0, 1);
2613     requestParser.addOptionGroup(REQUEST + " " + DOGET + " " +DOPOST, 1, 1);
2614     requestParser.addOptionGroup(CONTENT + " " + CONTENTFILE, 0, 1);
2615     requestParser.addOptionGroup(CONTENT + " " + PARAMETER, 0, 1);
2616 
2617     requestParser.addOptionNeed(TOMACHINE, FILE);
2618 
2619     infoParser = new STAFCommandParser();
2620 
2621     infoParser.addOption(QUERY, 1, STAFCommandParser.VALUENOTALLOWED);
2622     infoParser.addOption(LIST, 1, STAFCommandParser.VALUENOTALLOWED);
2623     infoParser.addOption(FORMS, 1, STAFCommandParser.VALUENOTALLOWED);
2624     infoParser.addOption(LINKS, 1, STAFCommandParser.VALUENOTALLOWED);
2625     infoParser.addOption(COOKIES, 1, STAFCommandParser.VALUENOTALLOWED);
2626     infoParser.addOption(DEFAULTHEADERS, 1, STAFCommandParser.VALUENOTALLOWED);
2627     infoParser.addOption(FORMCONTROLS, 1, STAFCommandParser.VALUENOTALLOWED);
2628     infoParser.addOption(AUTHENTICATIONHOSTS, 1,
2629                          STAFCommandParser.VALUENOTALLOWED);
2630     infoParser.addOption(FORM, 1, STAFCommandParser.VALUENOTALLOWED);
2631     infoParser.addOption(LINK, 1, STAFCommandParser.VALUENOTALLOWED);
2632     infoParser.addOption(COOKIE, 1, STAFCommandParser.VALUENOTALLOWED);
2633     infoParser.addOption(SESSIONS, 1, STAFCommandParser.VALUENOTALLOWED);
2634     infoParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2635     infoParser.addOption(NAME, 1, STAFCommandParser.VALUEREQUIRED);
2636     infoParser.addOption(ID, 1, STAFCommandParser.VALUEREQUIRED);
2637     infoParser.addOption(INDEX, 1, STAFCommandParser.VALUEREQUIRED);
2638     infoParser.addOption(DEFAULTHEADER, 1, STAFCommandParser.VALUEREQUIRED);
2639     infoParser.addOption(CONTROLNAME, 1, STAFCommandParser.VALUEREQUIRED);
2640     infoParser.addOption(AUTHENTICATIONHOST, 1,
2641                          STAFCommandParser.VALUEREQUIRED);
2642 
2643     infoParser.addOptionGroup(QUERY + " " + LIST, 1, 1);
2644     infoParser.addOptionGroup(COOKIE + " " + LINK + " " + FORM + " " +
2645                               DEFAULTHEADER + " " + AUTHENTICATIONHOST, 0, 1);
2646     infoParser.addOptionGroup(COOKIES + " " + LINKS + " " + FORMS + " "
2647                              + SESSIONS + " " + DEFAULTHEADERS + " " +
2648                              AUTHENTICATIONHOSTS, 0, 1);
2649     infoParser.addOptionGroup(NAME + " " + ID + " " + INDEX, 0, 1);
2650 
2651     infoParser.addOptionNeed(SESSION, QUERY + " " + FORMCONTROLS + " " +
2652                              COOKIES + " " + LINKS + " " + FORMS  + " " +
2653                              DEFAULTHEADERS + " " + AUTHENTICATIONHOSTS);
2654     infoParser.addOptionNeed(QUERY, SESSION);
2655     infoParser.addOptionNeed(LIST, SESSIONS + " " + SESSION);
2656     infoParser.addOptionNeed(COOKIES + " " + LINKS + " " + FORMS  + " " +
2657                              DEFAULTHEADERS + " " + AUTHENTICATIONHOSTS,
2658                              SESSION);
2659     infoParser.addOptionNeed(COOKIES + " " + LINKS + " " + FORMS  + " " +
2660                              DEFAULTHEADERS + " " + AUTHENTICATIONHOSTS +
2661                              " " + FORMCONTROLS, LIST);
2662     infoParser.addOptionNeed(COOKIE + " " + LINK + " " +
2663                              DEFAULTHEADER + " " + AUTHENTICATIONHOST, QUERY);
2664     infoParser.addOptionNeed(COOKIE, NAME);
2665     infoParser.addOptionNeed(FORM, SESSION);
2666     infoParser.addOptionNeed(FORM, FORMCONTROLS + " " + QUERY);
2667     infoParser.addOptionNeed(FORMCONTROLS + " " + CONTROLNAME, FORM);
2668     infoParser.addOptionNeed(LINK, NAME + " " + ID + " " + INDEX);
2669     infoParser.addOptionNeed(NAME, FORM + " " + LINK + " " + COOKIE);
2670     infoParser.addOptionNeed(ID, FORM + " " + LINK);
2671     infoParser.addOptionNeed(INDEX, FORM + " " + LINK);
2672 
2673     getParser = new STAFCommandParser();
2674 
2675     getParser.addOption(GET, 1, STAFCommandParser.VALUENOTALLOWED);
2676     getParser.addOption(CONTENT, 1, STAFCommandParser.VALUENOTALLOWED);
2677     getParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2678     getParser.addOption(FILE, 1, STAFCommandParser.VALUEREQUIRED);
2679     getParser.addOption(TOMACHINE, 1, STAFCommandParser.VALUEREQUIRED);
2680 
2681     getParser.addOptionGroup(GET, 1, 1);
2682     getParser.addOptionNeed(GET, CONTENT);
2683     getParser.addOptionNeed(GET, SESSION);
2684     getParser.addOptionNeed(TOMACHINE, FILE);
2685 
2686     htmlActionParser = new STAFCommandParser();
2687 
2688     htmlActionParser.addOption(FOLLOW, 1, STAFCommandParser.VALUENOTALLOWED);
2689     htmlActionParser.addOption(SUBMIT, 1, STAFCommandParser.VALUENOTALLOWED);
2690     htmlActionParser.addOption(RESET, 1, STAFCommandParser.VALUENOTALLOWED);
2691     htmlActionParser.addOption(FORM, 1, STAFCommandParser.VALUENOTALLOWED);
2692     htmlActionParser.addOption(LINK, 1, STAFCommandParser.VALUENOTALLOWED);
2693     htmlActionParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2694     htmlActionParser.addOption(NAME, 1, STAFCommandParser.VALUEREQUIRED);
2695     htmlActionParser.addOption(ID, 1, STAFCommandParser.VALUEREQUIRED);
2696     htmlActionParser.addOption(INDEX, 1, STAFCommandParser.VALUEREQUIRED);
2697     htmlActionParser.addOption(FILE, 1, STAFCommandParser.VALUEREQUIRED);
2698     htmlActionParser.addOption(TOMACHINE, 1, STAFCommandParser.VALUEREQUIRED);
2699     htmlActionParser.addOption(IGNOREERRORS, 1,
2700                                STAFCommandParser.VALUENOTALLOWED);
2701     htmlActionParser.addOption(NOSTATUS, 1, STAFCommandParser.VALUENOTALLOWED);
2702     htmlActionParser.addOption(RETURNHEADERS, 1,
2703                                STAFCommandParser.VALUENOTALLOWED);
2704     htmlActionParser.addOption(NOCONTENT, 1, STAFCommandParser.VALUENOTALLOWED);
2705     htmlActionParser.addOption(AUTOREDIRECT, 1,
2706                                STAFCommandParser.VALUENOTALLOWED);
2707     htmlActionParser.addOption(NOAUTOREDIRECT, 1,
2708                                STAFCommandParser.VALUENOTALLOWED);
2709 
2710     htmlActionParser.addOptionGroup(FOLLOW + " " + SUBMIT + " " + RESET, 1, 1);
2711     htmlActionParser.addOptionGroup(NAME + " " + ID + " " + INDEX, 0, 1);
2712     htmlActionParser.addOptionGroup(AUTOREDIRECT + " " + NOAUTOREDIRECT, 0, 1);
2713 
2714     htmlActionParser.addOptionNeed(FOLLOW, LINK);
2715     htmlActionParser.addOptionNeed(SUBMIT + " " + RESET, FORM);
2716     htmlActionParser.addOptionNeed(LINK + " " + FORM, SESSION);
2717     htmlActionParser.addOptionNeed(LINK, NAME + " " + ID + " " + INDEX);
2718     htmlActionParser.addOptionNeed(FILE + " " + IGNOREERRORS + " " + NOSTATUS
2719                                    + " " + RETURNHEADERS + " " + NOCONTENT +
2720                                    " " + AUTOREDIRECT + " " + NOAUTOREDIRECT,
2721                                    SUBMIT + " " + FOLLOW);
2722     htmlActionParser.addOptionNeed(TOMACHINE, FILE);
2723 
2724     setParser = new STAFCommandParser();
2725 
2726     setParser.addOption(SET, 1, STAFCommandParser.VALUENOTALLOWED);
2727     setParser.addOption(FORM, 1, STAFCommandParser.VALUENOTALLOWED);
2728     setParser.addOption(COOKIE, 1, STAFCommandParser.VALUENOTALLOWED);
2729     setParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2730     setParser.addOption(NAME, 1, STAFCommandParser.VALUEREQUIRED);
2731     setParser.addOption(ID, 1, STAFCommandParser.VALUEREQUIRED);
2732     setParser.addOption(INDEX, 1, STAFCommandParser.VALUEREQUIRED);
2733     setParser.addOption(CONTROLNAME, 1, STAFCommandParser.VALUEREQUIRED);
2734     setParser.addOption(VALUE, 1, STAFCommandParser.VALUEREQUIRED);
2735     setParser.addOption(POLICY, 1, STAFCommandParser.VALUEREQUIRED);
2736     setParser.addOption(DEFAULTHEADER, 1, STAFCommandParser.VALUEREQUIRED);
2737     setParser.addOption(AUTHENTICATIONHOST, 1, STAFCommandParser.VALUEREQUIRED);
2738     setParser.addOption(AUTHENTICATIONUSER, 1, STAFCommandParser.VALUEREQUIRED);
2739     setParser.addOption(AUTHENTICATIONPWD, 1, STAFCommandParser.VALUEREQUIRED);
2740     setParser.addOption(AUTHENTICATIONDOMAIN, 1,
2741                         STAFCommandParser.VALUEREQUIRED);
2742     setParser.addOption(AUTOREDIRECT, 1, STAFCommandParser.VALUENOTALLOWED);
2743     setParser.addOption(NOAUTOREDIRECT, 1, STAFCommandParser.VALUENOTALLOWED);
2744     setParser.addOption("PARSECONTENT", 1, STAFCommandParser.VALUEREQUIRED);
2745     setParser.addOption("HTTPPROXYHOST", 1, STAFCommandParser.VALUEREQUIRED);
2746     setParser.addOption("HTTPPROXYPORT", 1, STAFCommandParser.VALUEREQUIRED);
2747 
2748     setParser.addOptionGroup(NAME + " " + ID + " " + INDEX, 0, 1);
2749     setParser.addOptionGroup(FORM + " " + COOKIE +" " +
2750                              DEFAULTHEADER + " " + AUTOREDIRECT + " " +
2751                              NOAUTOREDIRECT + " " + AUTHENTICATIONHOST +
2752                              " PARSECONTENT HTTPPROXYHOST", 0, 1);
2753 
2754     setParser.addOptionNeed(SET, SESSION);
2755     setParser.addOptionNeed(INDEX + " " + ID, FORM);
2756     setParser.addOptionNeed(CONTROLNAME, FORM);
2757     setParser.addOptionNeed(FORM, CONTROLNAME);
2758     setParser.addOptionNeed(COOKIE, NAME + " " + POLICY);
2759     setParser.addOptionNeed(CONTROLNAME + " " + DEFAULTHEADER, VALUE);
2760     setParser.addOptionNeed(AUTHENTICATIONHOST, AUTHENTICATIONUSER);
2761     setParser.addOptionNeed(AUTHENTICATIONUSER + " " + AUTHENTICATIONPWD
2762                             + " " + AUTHENTICATIONDOMAIN, AUTHENTICATIONHOST);
2763     setParser.addOptionNeed("HTTPPROXYPORT", "HTTPPROXYHOST");
2764 
2765     delCloseParser = new STAFCommandParser();
2766 
2767     delCloseParser.addOption(DELETE, 1, STAFCommandParser.VALUENOTALLOWED);
2768     delCloseParser.addOption(CLOSE, 1, STAFCommandParser.VALUENOTALLOWED);
2769     delCloseParser.addOption(COOKIE, 1, STAFCommandParser.VALUENOTALLOWED);
2770     delCloseParser.addOption(NAME, 1, STAFCommandParser.VALUEREQUIRED);
2771     delCloseParser.addOption(SESSION, 1, STAFCommandParser.VALUEREQUIRED);
2772     delCloseParser.addOption(DEFAULTHEADER, 1, STAFCommandParser.VALUEREQUIRED);
2773     delCloseParser.addOption(AUTHENTICATIONHOST, 1,
2774                              STAFCommandParser.VALUEREQUIRED);
2775 
2776     delCloseParser.addOptionGroup(DELETE + " " + CLOSE, 1, 1);
2777 
2778     delCloseParser.addOptionNeed(COOKIE, NAME);
2779     delCloseParser.addOptionNeed(DELETE + " " + CLOSE, SESSION);
2780     delCloseParser.addOptionNeed(DELETE, DEFAULTHEADER + " " + COOKIE + " "
2781                                 + AUTHENTICATIONHOST);
2782     delCloseParser.addOptionNeed(DEFAULTHEADER + " " + COOKIE + " " +
2783                                  AUTHENTICATIONHOST, DELETE);
2784 
2785     // Construct map class for LIST SESSIONS result
2786 
2787     fListSessionMapClass = new STAFMapClassDefinition(
2788         "STAF/Service/HTTP/ListSession");
2789     fListSessionMapClass.addKey("sessionID",  "ID");
2790     fListSessionMapClass.addKey("url", "Url");
2791     fListSessionMapClass.addKey("title", "Title");
2792 
2793     // Construct map class for QUERY SESSION result
2794 
2795     fSessionMapClass = new STAFMapClassDefinition(
2796         "STAF/Service/HTTP/Session");
2797     fSessionMapClass.addKey("url", "Url");
2798     fSessionMapClass.addKey("title", "Title");
2799     fSessionMapClass.addKey("statusCode", "Status Code");
2800     fSessionMapClass.addKey("statusMessage", "Status Message");
2801     fSessionMapClass.addKey("cookiePolicy", "Cookie Policy");
2802     fSessionMapClass.addKey("followsRedirects", "Follows Redirects");
2803     fSessionMapClass.addKey("parseContent", "Parse Content");
2804     fSessionMapClass.addKey("httpProxyHost", "HTTP Proxy Host");
2805     fSessionMapClass.addKey("httpProxyPort", "HTTP Proxy Port");
2806     fSessionMapClass.addKey("owner", "Owner");
2807 
2808     // Construct map class for session owner used in QUERY SESSION result
2809 
2810     fSessionOwnerMapClass = new STAFMapClassDefinition(
2811         "STAF/Service/HTTP/SessionOwner");
2812     fSessionOwnerMapClass.addKey("instanceUUID", "Instance UUID");
2813     fSessionOwnerMapClass.addKey("machine", "Machine");
2814     fSessionOwnerMapClass.addKey("handleName", "Handle Name");
2815     fSessionOwnerMapClass.addKey("handle", "Handle");
2816 
2817     // Construct map classes for results from REQUEST/DOPOST/DOGET/FOLLOWLINK/
2818     // and SUBMIT FORM requests (the result varies based on options specified)
2819 
2820     fHttpResultMapClass = new STAFMapClassDefinition(
2821         "STAF/Service/HTTP/HttpResult");
2822     fHttpResultMapClass.addKey("statusCode", "Status Code");
2823     fHttpResultMapClass.addKey("statusMessage", "Status Message");
2824     fHttpResultMapClass.addKey("headers", "Headers");
2825     fHttpResultMapClass.addKey("content", "Content");
2826 
2827     // Construct map class for QUERY AUTHENTICATIONHOST result
2828 
2829     fAuthHostMapClass = new STAFMapClassDefinition(
2830         "STAF/Service/HTTP/AuthenticationHost");
2831 
2832     fAuthHostMapClass.addKey("user", "User");
2833     fAuthHostMapClass.addKey("password", "Password");
2834     fAuthHostMapClass.addKey("domain", "Domain");
2835 
2836     // Construct map class for QUERY COOKIE result
2837 
2838     fCookieMapClass = new STAFMapClassDefinition(
2839         "STAF/Service/HTTP/Cookie");
2840 
2841     fCookieMapClass.addKey("value", "Cookie Value");
2842     fCookieMapClass.addKey("domain", "Domain");
2843     fCookieMapClass.addKey("path", "Path");
2844     fCookieMapClass.addKey("expirationDate", "Expiration Date");
2845 
2846     // Construct map class for LIST FORMS result
2847 
2848     fListFormMapClass = new STAFMapClassDefinition(
2849         "STAF/Service/HTTP/ListForm");
2850     fListFormMapClass.addKey("formIndex", "Index");
2851     fListFormMapClass.addKey("formID", "Form ID");
2852     fListFormMapClass.addKey("formName", "Form Name");
2853 
2854     // Construct map class for QUERY FORM result
2855 
2856     fFormMapClass = new STAFMapClassDefinition(
2857         "STAF/Service/HTTP/Form");
2858     fFormMapClass.addKey("formIndex", "Index");
2859     fFormMapClass.addKey("formID", "Form ID");
2860     fFormMapClass.addKey("formName", "Form Name");
2861     fFormMapClass.addKey("method", "Method");
2862     fFormMapClass.addKey("targetUrl", "Action");
2863     fFormMapClass.addKey("headerMap", "Headers");
2864 
2865     // Construct map class for QUERY FORM CONTROLNAME result
2866 
2867     fFormControlMapClass = new STAFMapClassDefinition(
2868         "STAF/Service/HTTP/FormControlName");
2869     fFormControlMapClass.addKey("type", "Type");
2870     fFormControlMapClass.addKey("disabled", "Disabled");
2871     fFormControlMapClass.addKey("readOnly", "Read Only");
2872     fFormControlMapClass.addKey("value", "Value");
2873     fFormControlMapClass.addKey("possibleValueList", "Possible Values");
2874 
2875     // Construct map class for LIST LINKS result
2876 
2877     fListLinkMapClass = new STAFMapClassDefinition(
2878         "STAF/Service/HTTP/ListLink");
2879     fListLinkMapClass.addKey("linkIndex", "Index");
2880     fListLinkMapClass.addKey("linkID", "Link ID");
2881     fListLinkMapClass.addKey("linkName", "Link Name");
2882 
2883     // Construct map class for QUERY LINK result
2884 
2885     fLinkMapClass = new STAFMapClassDefinition(
2886         "STAF/Service/HTTP/Link");
2887     fLinkMapClass.addKey("linkIndex", "Index");
2888     fLinkMapClass.addKey("linkID", "Link ID");
2889     fLinkMapClass.addKey("linkName", "Link Name");
2890     fLinkMapClass.addKey("href", "Href");
2891 
2892 
2893     /* Set service name */
2894 
2895     fServiceName = initInfo.name;
2896 
2897     /* Create STAFHandle */
2898 
2899     try
2900     {
2901         sHandle = new STAFHandle("STAF/Service/" + initInfo.name);
2902     }
2903     catch(STAFException se)
2904     {
2905         se.printStackTrace();
2906         return new STAFResult(STAFResult.STAFRegistrationError,
2907                               se.toString());
2908     }
2909 
2910     STAFResult res;
2911 
2912     // Resolve the line separator variable for the local machine
2913 
2914     res = STAFUtil.resolveInitVar("{STAF/Config/Sep/Line}", sHandle);
2915 
2916     if (res.rc != STAFResult.Ok) return res;
2917 
2918     sLineSep = res.result;
2919 
2920     // Verify that the required version of STAF is running on the
2921     // local service machine.
2922     // Note:  Method compareSTAFVersion was added in STAF V3.1.0
2923 
2924     try
2925     {
2926         res = STAFUtil.compareSTAFVersion(
2927             "local", sHandle, REQUIREDSTAFVERSION);
2928 
2929         if (res.rc != STAFResult.Ok)
2930         {
2931             if (res.rc == STAFResult.InvalidSTAFVersion)
2932             {
2933                 return new STAFResult(
2934                     STAFResult.ServiceConfigurationError,
2935                     "Minimum required STAF version for this service " +
2936                     "is not running." + sLineSep + res.result);
2937             }
2938             else
2939             {
2940                 return new STAFResult(
2941                     STAFResult.ServiceConfigurationError,
2942                     "Error verifying the STAF version. RC: " + res.rc +
2943                     ", Additional info: " + res.result);
2944             }
2945         }
2946     }
2947     catch (Error err)
2948     {
2949         return new STAFResult(
2950             STAFResult.ServiceConfigurationError,
2951             "This service requires STAF Version " + REQUIREDSTAFVERSION +
2952             " or later.");
2953     }
2954 
2955     // Resolve the file separator variable for the local machine
2956 
2957     res = STAFUtil.resolveInitVar("{STAF/Config/Sep/File}", sHandle);
2958 
2959     if (res.rc != STAFResult.Ok)
2960     {
2961         try
2962         {
2963             sHandle.unRegister();
2964             return res;
2965         }
2966         catch (STAFException ex)
2967         {
2968             return res;
2969         }
2970     }
2971 
2972     String fileSep = res.result;
2973 
2974     // Resolve the machine variable for the local machine
2975 
2976     res = STAFUtil.resolveInitVar("{STAF/Config/Machine}", sHandle);
2977 
2978     if (res.rc != STAFResult.Ok)
2979     {
2980         try
2981         {
2982             sHandle.unRegister();
2983             return res;
2984         }
2985         catch (STAFException ex)
2986         {
2987             return res;
2988         }
2989     }
2990 
2991     fLocalMachineName = res.result;
2992 
2993     fTempDir = initInfo.writeLocation + fileSep + "tmp" + fileSep +
2994         "service" + fileSep + fServiceName + fileSep;
2995 
2996     File tempdir = new File (fTempDir);
2997 
2998     try
2999     {
3000         tempdir.mkdirs();
3001     }
3002     catch (SecurityException e)
3003     {
3004         return new STAFResult(
3005             STAFResult.FileOpenError,
3006             "Access to HTTP service temporary directory denied.  " +
3007             "Unable to make directory " + fTempDir);
3008     }
3009 
3010     // Assign the help text string for the service
3011 
3012     sHelpMsg = "*** " + fServiceName + " Service Help ***" +
3013         sLineSep + sLineSep +
3014         "OPEN    SESSION" +
3015         sLineSep +
3016         "CLOSE   SESSION <Session>" +
3017         sLineSep +
3018         "LIST    SESSIONS" +
3019         sLineSep +
3020         "LIST    <FORMS | LINKS | COOKIES | DEFAULTHEADERS | AUTHENTICATIONHOSTS |" +
3021         sLineSep +
3022         "        CONTROLNAMES FORM [NAME <Form Name> | ID <Id> | INDEX <Index>]>" +
3023         sLineSep +
3024         "        SESSION <Session>" +
3025         sLineSep +
3026         "QUERY   SESSION <Session>" +
3027         sLineSep +
3028         "GET     SESSION <Session> CONTENT [FILE <File Name> [TOMACHINE <Machine>]]" +
3029         sLineSep + sLineSep +
3030         "REQUEST METHOD <Http Method> URL <Target Url> [ENCODED] [CONTENT <Content>]" +
3031         sLineSep +
3032         "        [HEADER <Key>=<Value>]... [PARAMETER <Key>=<Value>]..." +
3033         sLineSep +
3034         "        [CONTENTFILE <Key>=<File Name>]..." +
3035         sLineSep +
3036         "        [FOLLOWREDIRECT | DONOTFOLLOWREDIRECT] [SESSION <Session>]" +
3037         sLineSep +
3038         "        [FILE <Filename> [TOMACHINE <Machine>]]" +
3039         sLineSep +
3040         "        [IGNOREERRORS] [NOSTATUS] [RETURNHEADERS] [RETURNNOCONTENT]" +
3041         sLineSep +
3042         "DOPOST  URL <Target Url> [ENCODED] [CONTENT <Content>]" +
3043         sLineSep +
3044         "        [HEADER <Key>=<Value>]... [PARAMETER <Key>=<Value>]..."+
3045         sLineSep +
3046         "        [CONTENTFILE <Key>=<File Name>]..." +
3047         sLineSep +
3048         "        [FOLLOWREDIRECT | DONOTFOLLOWREDIRECT] [SESSION <Session>]" +
3049         sLineSep +
3050         "        [FILE <Filename> [TOMACHINE <Machine>]]" +
3051         sLineSep +
3052         "        [IGNOREERRORS] [NOSTATUS] [RETURNHEADERS] [RETURNNOCONTENT]" +
3053         sLineSep +
3054         "DOGET   URL <Target Url> [ENCODED] [CONTENT <Content>]" +
3055         sLineSep +
3056         "        [HEADER <Key>=<Value>]... [PARAMETER <Key>=<Value>]..." +
3057         sLineSep +
3058         "        [FOLLOWREDIRECT | DONOTFOLLOWREDIRECT] [SESSION <Session>]" +
3059         sLineSep +
3060         "        [FILE <Filename> [TOMACHINE <Machine>]]" +
3061         sLineSep +
3062         "        [IGNOREERRORS] [NOSTATUS] [RETURNHEADERS] [RETURNNOCONTENT]"+
3063         sLineSep + sLineSep +
3064         "SET     <FOLLOWREDIRECT | DONOTFOLLOWREDIRECT> SESSION <Session>" +
3065         sLineSep +
3066         "SET     PARSECONTENT <Enabled | Disabled | Autodetect> SESSION <Session>" +
3067         sLineSep +
3068         "SET     HTTPPROXYHOST <Host> [HTTPPROXYPORT <Port>] SESSION <Session>" +
3069         sLineSep + sLineSep +
3070         "QUERY   AUTHENTICATIONHOST <Host> SESSION <Session>" +
3071         sLineSep +
3072         "SET     AUTHENTICATIONHOST <Host> AUTHENTICATIONUSER <User>" +
3073         sLineSep +
3074         "        [AUTHENTICATIONPASSWORD <Password>] [AUTHENTICATIONDOMAIN <Domain>]" +
3075         sLineSep +
3076         "        SESSION <Session>" +
3077         sLineSep +
3078         "DELETE  AUTHENTICATIONHOST <Host> SESSION <Session>" +
3079         sLineSep + sLineSep +
3080         "QUERY   DEFAULTHEADER <Key> SESSION <Session>" +
3081         sLineSep +
3082         "SET     DEFAULTHEADER <Key> VALUE <Value> SESSION <Session>" +
3083         sLineSep +
3084         "DELETE  DEFAULTHEADER <Key> SESSION <Session>" +
3085         sLineSep + sLineSep +
3086         "QUERY   COOKIE NAME <Name> SESSION <Session>" +
3087         sLineSep +
3088         "SET     COOKIE <NAME <Name> VALUE <Value>> | <POLICY <policy>>" +
3089         sLineSep +
3090         "        SESSION <Session>" +
3091         sLineSep +
3092         "DELETE  COOKIE NAME <Name> SESSION <Session>" +
3093         sLineSep + sLineSep +
3094         "QUERY   FORM [NAME <Form Name> | ID <Id> | INDEX <Index>] [CONTROLNAME <Name>]" +
3095         sLineSep +
3096         "        SESSION <Session>" +
3097         sLineSep +
3098         "SET     FORM [NAME <Form Name> | ID <Id> | INDEX <Index>]" +
3099         sLineSep +
3100         "        CONTROLNAME <Name> VALUE <Value> SESSION <Session>" +
3101         sLineSep +
3102         "SUBMIT  FORM [NAME <Form Name> | ID <Id> | INDEX <Index>] SESSION <Session>" +
3103         sLineSep +
3104         "        [FOLLOWREDIRECT | DONOTFOLLOWREDIRECT]" +
3105         sLineSep +
3106         "        [FILE <Filename> [TOMACHINE <Machine>]]" +
3107         sLineSep +
3108         "        [IGNOREERRORS] [NOSTATUS] [RETURNHEADERS] [RETURNNOCONTENT]" +
3109         sLineSep +
3110         "RESET   FORM [NAME <Form Name> | ID <Id> | INDEX <Index>] SESSION <Session>" +
3111         sLineSep + sLineSep +
3112         "QUERY   LINK <NAME <Name> | ID <Id> | INDEX <Index>> SESSION <Session>" +
3113         sLineSep +
3114         "FOLLOW  LINK <NAME <Name> | ID <Id> | INDEX <Index>> SESSION <Session>" +
3115         sLineSep +
3116         "        [FOLLOWREDIRECT | DONOTFOLLOWREDIRECT]" +
3117         sLineSep +
3118         "        [FILE <Filename> [TOMACHINE <Machine>]]" +
3119         sLineSep +
3120         "        [IGNOREERRORS] [NOSTATUS] [RETURNHEADERS] [RETURNNOCONTENT]" +
3121         sLineSep + sLineSep +
3122         "HELP" +
3123         sLineSep + sLineSep +
3124         "VERSION";
3125 
3126     /* Register RCs with the HELP service */
3127 
3128     int rc = this.registerHelp(initInfo.name);
3129 
3130     if (rc != STAFResult.Ok)
3131         return new STAFResult(rc, "Error registering RCs with HELP service.");
3132 
3133     /* Initialize the session list */
3134 
3135     sessionList = new SessionList();
3136 
3137     /* Finished */
3138 
3139     return new STAFResult(rc);
3140 }
3141 
3142 /*****************************************************************************/
3143 /*                                                                           */
3144 /* Method: registerHelp                                                      */
3145 /* Description: registers all HTTP return codes with the HELP service        */
3146 /* Parameters: serviceName - name which this service is registered as        */
3147 /* Returns: int representation of STAFResult                                 */
3148 /*                                                                           */
3149 /*****************************************************************************/
3150 
registerHelp(String name)3151 private int registerHelp(String name)
3152 {
3153     try
3154     {
3155         String request = "REGISTER SERVICE " + name + " ERROR " + UNKNOWNHOST +
3156             " INFO \"" + UNKNOWNHOSTInfo + "\" DESCRIPTION \"" +
3157             UNKNOWNHOSTDesc + "\"";
3158         sHandle.submit("LOCAL", "HELP", request);
3159 
3160         request = "REGISTER SERVICE " + name + " ERROR " + CONNECTERROR +
3161             " INFO \"" + CONNECTERRORInfo + "\" DESCRIPTION \"" +
3162             CONNECTERRORDesc + "\"";
3163         sHandle.submit("LOCAL", "HELP", request);
3164 
3165         request = "REGISTER SERVICE " + name + " ERROR " + INVALIDMETHOD +
3166             " INFO \"" + INVALIDMETHODInfo + "\" DESCRIPTION \"" +
3167             INVALIDMETHODDesc + "\"";
3168         sHandle.submit("LOCAL", "HELP", request);
3169 
3170         request = "REGISTER SERVICE " + name + " ERROR " + IOEXCEPTION +
3171             " INFO \"" + IOEXCEPTIONInfo + "\" DESCRIPTION \"" +
3172             IOEXCEPTIONDesc + "\"";
3173         sHandle.submit("LOCAL", "HELP", request);
3174 
3175         request = "REGISTER SERVICE " + name + " ERROR " + CONTENTTOOLARGE +
3176             " INFO \"" + CONTENTTOOLARGEInfo + "\" DESCRIPTION \"" +
3177             CONTENTTOOLARGEDesc + "\"";
3178         sHandle.submit("LOCAL", "HELP", request);
3179 
3180     }catch(STAFException se)
3181     {
3182         return se.rc;
3183     }
3184 
3185     return STAFResult.Ok;
3186 
3187 }
3188 
3189 /*****************************************************************************/
3190 /*                                                                           */
3191 /* Method: unRegisterHelp                                                    */
3192 /* Description: un-registers all HTTP return codes with the HELP service     */
3193 /* Returns: int representation of STAFResult                                 */
3194 /*                                                                           */
3195 /*****************************************************************************/
3196 
unRegisterHelp()3197 private int unRegisterHelp()
3198 {
3199     try
3200     {
3201         String request = "UNREGISTER SERVICE " + fServiceName + " ERROR "
3202                        + UNKNOWNHOST;
3203         sHandle.submit("LOCAL", "HELP", request);
3204 
3205         request = "UNREGISTER SERVICE " + fServiceName + " ERROR " + CONNECTERROR;
3206         sHandle.submit("LOCAL", "HELP", request);
3207 
3208         request = "UNREGISTER SERVICE " + fServiceName + " ERROR " + INVALIDMETHOD;
3209         sHandle.submit("LOCAL", "HELP", request);
3210 
3211         request = "UNREGISTER SERVICE " + fServiceName + " ERROR " + IOEXCEPTION;
3212         sHandle.submit("LOCAL", "HELP", request);
3213 
3214         request = "UNREGISTER SERVICE " + fServiceName + " ERROR " +
3215             CONTENTTOOLARGE;
3216         sHandle.submit("LOCAL", "HELP", request);
3217 
3218     }
3219     catch(STAFException se)
3220     {
3221         return se.rc;
3222     }
3223 
3224     return STAFResult.Ok;
3225 }
3226 
3227 /*****************************************************************************/
3228 /*                                                                           */
3229 /* Method: term                                                              */
3230 /* Description: required by interface STAFServiceInterfaceLevel30            */
3231 /*                                                                           */
3232 /*****************************************************************************/
3233 
term()3234 public STAFResult term()
3235 {
3236     // Close any open sessions
3237 
3238     HashMap[] list = sessionList.listSessions();
3239 
3240     for (int i = 0; i < list.length; i++)
3241     {
3242         String sessionIdString = (String)list[i].get(WebSession.ID);
3243         int sessionId = Integer.parseInt(sessionIdString);
3244 
3245         // Close session ID
3246 
3247         try
3248         {
3249             WebSession session = sessionList.getSession(sessionId);
3250             session.releaseConnection();
3251             sessionList.deleteSession(sessionId);
3252         }
3253         catch (Exception e)
3254         {
3255             System.out.println(
3256                 "Error closing session " + sessionId +
3257                 " while shutting down the " + fServiceName + " service.\n" +
3258                 e.toString());
3259         }
3260     }
3261 
3262     // Un-register Help Data
3263 
3264     unRegisterHelp();
3265 
3266     // Un-register the service handle
3267 
3268     try
3269     {
3270         sHandle.unRegister();
3271     }
3272     catch (STAFException ex)
3273     {
3274         return new STAFResult(STAFResult.STAFRegistrationError,
3275                               ex.toString());
3276     }
3277 
3278     return new STAFResult(STAFResult.Ok);
3279 
3280 }
3281 
3282 /*****************************************************************************/
3283 /*                                                                           */
3284 /* Method: version                                                           */
3285 /* Description: returns service version information                          */
3286 /* Parameters: none                                                          */
3287 /* Returns: STAFResult.OK                                                    */
3288 /*                                                                           */
3289 /*****************************************************************************/
3290 
version(STAFServiceInterfaceLevel30.RequestInfo info)3291 private STAFResult version(STAFServiceInterfaceLevel30.RequestInfo info)
3292 {
3293     // Verify the requester has at least trust level 1
3294 
3295     STAFResult trustResult = STAFUtil.validateTrust(
3296         1, fServiceName, "VERSION", fLocalMachineName, info);
3297 
3298     if (trustResult.rc != STAFResult.Ok) return trustResult;
3299 
3300     // Return the service's version
3301 
3302     return new STAFResult(STAFResult.Ok, VERSIONINFO);
3303 }
3304 
3305 /*****************************************************************************/
3306 /*                                                                           */
3307 /* Method: cleanupNonSessionMethod                                           */
3308 /* Description: Perform clean-up for the temporary session (used by a        */
3309 /*              non-session method).                                         */
3310 /* Parameters : session id (for the temporary non-session method request)    */
3311 /* Returns    : Nothing                                                      */
3312 /*                                                                           */
3313 /*****************************************************************************/
3314 
cleanupNonSessionMethod(int sessionId)3315 private void cleanupNonSessionMethod(int sessionId)
3316 {
3317     // Delete the temporary file used by the temporary session, if exists
3318     try
3319     {
3320         (new File(getTempDir() + "session" + sessionId + ".tmp")).delete();
3321     }
3322     catch (Exception e)
3323     {
3324         // Ignore any exceptions
3325     }
3326 
3327     // Delete the temporary session
3328     try
3329     {
3330         sessionList.deleteSession(sessionId);
3331     }
3332     catch (InvalidSessionIDException e)
3333     {
3334         // Do nothing
3335     }
3336 }
3337 
3338 /***********************************************************************/
3339 /* Description:                                                        */
3340 /*   This method resolves any STAF variables that are contained within */
3341 /*   the string passed in by submitting a                              */
3342 /*       RESOLVE REQUEST <request#> STRING <value> IGNOREERRORS        */
3343 /*   request to the VAR service on the local system.                   */
3344 /*   Note: Can't use STAFUtil.resolveRequestVar() method because it    */
3345 /*         doesn't support specifying the IGNOREERRORS option for a    */
3346 /*         VAR RESOLVE request.                                        */
3347 /*                                                                     */
3348 /* Input:  String that may contain STAF variables to be resolved       */
3349 /*         STAF handle                                                 */
3350 /*         Request number                                              */
3351 /*                                                                     */
3352 /* Returns:                                                            */
3353 /*   STAFResult.rc = the return code (STAFResult.Ok if successful)     */
3354 /*   STAFResult.result = the resolved value if successful              */
3355 /*                       an error message if not successful            */
3356 /***********************************************************************/
resolveRequestVarIgnoreErrors( String value, STAFHandle handle, int requestNumber)3357 private static STAFResult resolveRequestVarIgnoreErrors(
3358     String value, STAFHandle handle, int requestNumber)
3359 {
3360     if (value.indexOf("{") != -1)
3361     {
3362         // The string may contains STAF variables
3363 
3364         STAFResult resolvedResult = handle.submit2(
3365             "local", "VAR", "RESOLVE REQUEST " + requestNumber +
3366             " STRING " + STAFUtil.wrapData(value) + " IGNOREERRORS");
3367 
3368         return resolvedResult;
3369     }
3370 
3371     return new STAFResult(STAFResult.Ok, value);
3372 }
3373 
getTempDir()3374 public String getTempDir() { return fTempDir; }
getTempFileCount()3375 public int getTempFileCount() { return fTempFileCount++; }
getLocalMachineName()3376 public String getLocalMachineName() { return fLocalMachineName; }
getServiceHandle()3377 public STAFHandle getServiceHandle() { return sHandle; }
3378 
3379 } // end class HTTP
3380