View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public License,
3    * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4    * obtain one at http://mozilla.org/MPL/2.0/.
5    *
6    * If it is not possible or desirable to put the notice in a particular file,
7    * then You may include the notice in a location (such as a LICENSE file in a
8    * relevant directory) where a recipient would be likely to look for such a
9    * notice.
10   *
11   * 
12   */
13  /*  ---------------------------------------------------------------------------
14   *  US Government, Department of the Army
15   *  Army Materiel Command
16   *  Research Development Engineering Command
17   *  Communications Electronics Research Development and Engineering Center
18   *  ---------------------------------------------------------------------------
19   */
20  package org.miloss.fgsms.presentation;
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.StringWriter;
26  import java.io.UnsupportedEncodingException;
27  import java.net.URL;
28  import java.net.URLEncoder;
29  import java.util.ArrayList;
30  import java.util.Collections;
31  import java.util.Enumeration;
32  import java.util.HashMap;
33  import java.util.HashSet;
34  import java.util.Iterator;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Properties;
38  import java.util.Set;
39  import javax.servlet.ServletContext;
40  import javax.servlet.http.Cookie;
41  import javax.servlet.http.HttpServletRequest;
42  import javax.servlet.http.HttpServletResponse;
43  import javax.xml.bind.JAXBContext;
44  import javax.xml.bind.JAXBElement;
45  import javax.xml.bind.Marshaller;
46  import javax.xml.bind.Unmarshaller;
47  import javax.xml.datatype.DatatypeConfigurationException;
48  import javax.xml.datatype.DatatypeFactory;
49  import javax.xml.datatype.Duration;
50  import javax.xml.stream.XMLInputFactory;
51  import javax.xml.stream.XMLStreamReader;
52  import javax.xml.ws.BindingProvider;
53  import org.apache.log4j.Level;
54  import org.miloss.fgsms.common.Logger;;
55  import org.dom4j.Document;
56  import org.dom4j.DocumentHelper;
57  import org.dom4j.io.OutputFormat;
58  import org.dom4j.io.XMLWriter;
59  import org.miloss.fgsms.common.Constants;
60  import org.miloss.fgsms.common.Utility;
61  import org.miloss.fgsms.services.interfaces.common.GetOperatingStatusRequestMessage;
62  import org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponseMessage;
63  import org.miloss.fgsms.services.interfaces.common.NameValuePair;
64  import org.miloss.fgsms.services.interfaces.common.PolicyType;
65  import org.miloss.fgsms.services.interfaces.common.ProcessPerformanceData;
66  import org.miloss.fgsms.services.interfaces.common.SecurityWrapper;
67  import org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsAllResponseMsg;
68  import org.miloss.fgsms.services.interfaces.dataaccessservice.MachineData;
69  import org.miloss.fgsms.services.interfaces.dataaccessservice.QuickStatURIWrapper;
70  import org.miloss.fgsms.services.interfaces.dataaccessservice.ServiceType;
71  import org.miloss.fgsms.services.interfaces.policyconfiguration.*;
72  import org.miloss.fgsms.services.interfaces.status.GetStatusResponseMsg;
73  
74  /**
75   * Web GUI Presentation layer helper functions
76   *
77   * @author AO
78   */
79  public class Helper {
80  
81       final static boolean DEBUG = false;
82  
83       public static String RenderRuleRunAt(RunAtLocation val) {
84            StringBuilder s = new StringBuilder();
85            s.append("<select name=\"slagenericrulerunat\">");
86            for (int i = 0; i < RunAtLocation.values().length; i++) {
87                 s.append("<option value=\"").append(RunAtLocation.values()[i].value()).append("\" ");
88                 if (val != null && val == RunAtLocation.values()[i]) {
89                      s.append(" selected ");
90                 }
91                 s.append(" >").append(RunAtLocation.values()[i].value()).append("</option>");
92            }
93            s.append("</select>");
94            return s.toString();
95       }
96  
97       /**
98        * used on index2.jsp
99        *
100       * @since 6.2
101       */
102      public static MachineData FindMachineRecord(List<MachineData> data, String Domainname, String Hostname, String policyURL) {
103           if (data == null) {
104                return null;
105           }
106           for (int i = 0; i < data.size(); i++) {
107                if (data.get(i).getDomainName().equalsIgnoreCase(Domainname) && data.get(i).getHostname().equalsIgnoreCase(Hostname)) {
108                     return data.get(i);
109                }
110           }
111           return null;
112      }
113 
114      /**
115       * used on index2.jsp
116       *
117       * @since 6.2
118       */
119      public static ProcessPerformanceData FindProcessRecord(List<MachineData> data, String policyURL) {
120           if (data == null) {
121                return null;
122           }
123           if (policyURL == null) {
124                return null;
125           }
126           for (int i = 0; i < data.size(); i++) {
127                if (data.get(i).getProcessPerformanceData() == null) {
128                     continue;
129                }
130                for (int k = 0; k < data.get(i).getProcessPerformanceData().size(); k++) {
131                     if (data.get(i).getProcessPerformanceData().get(k) != null
132                          && data.get(i).getProcessPerformanceData().get(k).getUri() != null && data.get(i).getProcessPerformanceData().get(k).getUri().equalsIgnoreCase(policyURL)) {
133                          return data.get(i).getProcessPerformanceData().get(k);
134                     }
135                }
136           }
137           return null;
138      }
139 
140      public static boolean FederationContains(List<Duration> d, int timeInMinutes) {
141           if (d == null || d.isEmpty()) {
142                return false;
143           }
144           for (int i = 0; i < d.size(); i++) {
145                long span = Utility.durationToTimeInMS(d.get(i));
146                if (span == ((long) timeInMinutes * 60L * 1000L)) {
147                     return true;
148                }
149           }
150           return false;
151      }
152 
153      /**
154       * used from tree view of home page, returns all nodes that have a
155       * null or empty parent object
156       *
157       * @param completelist
158       * @return
159       */
160      public static List<ServiceType> GetParentNodes(List<ServiceType> completelist) {
161           List<ServiceType> ret = new ArrayList<ServiceType>();
162           if (completelist == null || completelist.isEmpty()) {
163                return ret;
164           }
165           for (int i = 0; i < completelist.size(); i++) {
166                if (Utility.stringIsNullOrEmpty(completelist.get(i).getParentobject())) {
167                     ret.add(completelist.get(i));
168                }
169           }
170           return ret;
171      }
172 
173      /**
174       * used from tree view of home page, returns all child nodes from
175       * a given parent 
176       *
177       * @param uri
178       * @param completelist
179       * @return
180       */
181      public static List<ServiceType> GetChildNodes(String uri, List<ServiceType> completelist) {
182           List<ServiceType> ret = new ArrayList<ServiceType>();
183           if (completelist == null || completelist.isEmpty()) {
184                return ret;
185           }
186           for (int i = 0; i < completelist.size(); i++) {
187                if (!Utility.stringIsNullOrEmpty(completelist.get(i).getParentobject())) {
188                     if (completelist.get(i).getParentobject().equalsIgnoreCase(uri)) {
189                          ret.add(completelist.get(i));
190                     }
191                }
192           }
193           return ret;
194      }
195 
196      /**
197       * used on serviceprofile.jsp 
198       *
199       * @param fc
200       * @return
201       */
202      public static FederationPolicy FindUDDIFederationRecord(FederationPolicyCollection fc) {
203           if (fc == null) {
204                return null;
205           }
206           if (fc.getFederationPolicy().isEmpty()) {
207                return null;
208           }
209           for (int i = 0; i < fc.getFederationPolicy().size(); i++) {
210                if (fc.getFederationPolicy().get(i).getImplementingClassName() != null
211                     && fc.getFederationPolicy().get(i).getImplementingClassName().equalsIgnoreCase("org.miloss.fgsms.uddipub.UddiPublisher")) {
212                     return fc.getFederationPolicy().get(i);
213                }
214           }
215           return null;
216      }
217 
218      /**
219       * used on serviceprofile.jsp 
220       *
221       * @param items
222       * @return
223       */
224      public static String PublishRangeToString(List<Duration> items) {
225           if (items == null || items.isEmpty()) {
226                return null;
227           }
228           StringBuilder r = new StringBuilder();
229           for (int i = 0; i < items.size(); i++) {
230                r = r.append(Helper.DurationToString(items.get(i))).append(" ");
231           }
232           return r.toString().trim();
233      }
234 
235      public static QuickStatURIWrapper FindRecord(GetQuickStatsAllResponseMsg res, String url) {
236           if (res == null || res.getQuickStatURIWrapper() == null || res.getQuickStatURIWrapper().isEmpty()) {
237                return null;
238           }
239           for (int i = 0; i < res.getQuickStatURIWrapper().size(); i++) {
240                if (res.getQuickStatURIWrapper().get(i).getUri().equalsIgnoreCase(url)) {
241                     return res.getQuickStatURIWrapper().get(i);
242                }
243           }
244           return null;
245      }
246 
247      public static boolean ContainsSLAID(List<SLAregistration> items, String sla_id) {
248           if (items == null || items.isEmpty()) {
249                return false;
250           }
251           for (int i = 0; i < items.size(); i++) {
252                if (items.get(i).getSLAID().equalsIgnoreCase(sla_id)) {
253                     return true;
254                }
255           }
256 
257           return false;
258      }
259 
260      public static String ToShortActionString(String action) {
261           if (Utility.stringIsNullOrEmpty(action)) {
262                return "";
263           }
264           String ret = action;
265           int clip = 0;
266           if (ret.lastIndexOf("/") > clip) {
267                clip = ret.lastIndexOf("/");
268           }
269           if (ret.lastIndexOf("}") > clip) {
270                clip = ret.lastIndexOf("}");
271           }
272           if (ret.lastIndexOf(":") > clip) {
273                clip = ret.lastIndexOf(":");
274           }
275           if (ret.lastIndexOf("#") > clip) {
276                clip = ret.lastIndexOf("#");
277           }
278 
279           if (clip > 0) {
280                ret = (ret.substring(clip + 1));
281           }
282           return ret;
283 
284      }
285 
286      public static String PrettyPrintXMLToHtml(String xml) {
287           try {
288                Document doc = DocumentHelper.parseText(xml);
289                StringWriter sw = new StringWriter();
290                OutputFormat format = OutputFormat.createPrettyPrint();
291                XMLWriter xw = new XMLWriter(sw, format);
292                xw.write(doc);
293                return Utility.encodeHTML(sw.toString());
294 
295           } catch (Exception ex) {
296                //LogHelper.getLog().log(Level.INFO, "error creating pretty print xml. It's probably not an xml message: " + ex.getLocalizedMessage());
297           }
298 
299           try {
300                Document doc = DocumentHelper.parseText(xml.substring(xml.indexOf("<")));
301                StringWriter sw = new StringWriter();
302                OutputFormat format = OutputFormat.createPrettyPrint();
303                XMLWriter xw = new XMLWriter(sw, format);
304                xw.write(doc);
305                return Utility.encodeHTML(sw.toString());
306 
307           } catch (Exception ex) {
308                //LogHelper.getLog().log(Level.INFO, "error creating pretty print xml. It's probably not an xml message: " + ex.getLocalizedMessage());
309           }
310           LogHelper.getLog().log(Level.INFO, "error creating pretty print xml. It's probably not an xml message. No action is required.");
311           return Utility.encodeHTML(xml);
312 
313      }
314 
315      /**
316       * used on the index.jsp page of fgsms, finds a particular record
317       * returned from fgsms.StatusService and returns the specific record.
318       * 
319       */
320      public static GetStatusResponseMsg Findrecord(String url, List<GetStatusResponseMsg> list) {
321           if (Utility.stringIsNullOrEmpty(url)) {
322                return null;
323           }
324           if (list == null || list.isEmpty()) {
325                return null;
326           }
327           for (int i = 0; i < list.size(); i++) {
328                if (list.get(i).getURI().equalsIgnoreCase(url)) {
329                     GetStatusResponseMsg t = list.get(i);
330                     list.remove(i);
331                     return t;
332                }
333           }
334           return null;
335      }
336 
337      /**
338       * Use this function for loading properties files from web
339       * applications 
340       */
341      public static Properties loadForJSP(URL name) throws IOException {
342 
343           InputStream in = name.openStream();
344           Properties p = new Properties();
345           p.load(in);
346           in.close();
347           return p;
348      }
349 
350      /**
351       *  returns xyr xmo xd xhr xmin xs representation of a duration
352       * 
353       */
354      public static String DurationToString(Duration d) {
355           if (d == null) {
356                return "";
357           }
358           String s = "";
359           if (d.getYears() > 0) {
360                s += d.getYears() + "yr ";
361           }
362           if (d.getMonths() > 0) {
363                s += d.getMonths() + "mo ";
364           }
365           if (d.getDays() > 0) {
366                s += d.getDays() + "d ";
367           }
368           if (d.getHours() > 0) {
369                s += d.getHours() + "hr ";
370           }
371           if (d.getMinutes() > 0) {
372                s += d.getMinutes() + "min ";
373           }
374           if (d.getSeconds() > 0) {
375                s += d.getSeconds() + "s ";
376           }
377           return s;
378      }
379 
380      /**
381       * returns a duration parsed from xyr xmo xd xhr xmin xs
382       * 
383       * first it will parse it as a xml representation then as a Long then the
384       * specific format
385       */
386      public static Duration StringToDuration(String d) throws DatatypeConfigurationException {
387           if (Utility.stringIsNullOrEmpty(d)) {
388                return null;
389           }
390           String[] s = d.split(" ");
391           if (s == null || s.length == 0) {
392                return null;
393           }
394           DatatypeFactory fac = DatatypeFactory.newInstance();
395           try {
396                Duration dur = fac.newDuration(d);
397                return dur;
398           } catch (Exception ex) {
399           }
400           try {
401                Duration dur = fac.newDuration(Long.parseLong(d));
402                return dur;
403           } catch (Exception ex) {
404           }
405           long durationInMilliSeconds = 0;
406           String temp;
407           long x = 0;
408           for (int i = 0; i < s.length; i++) {
409                if (s[i].contains("yr")) {
410                     temp = s[i].replace("yr", "").trim();
411                     x = Long.parseLong(temp);
412                     durationInMilliSeconds += (x * 365 * 24 * 60 * 60 * 1000);
413                } else if (s[i].contains("mo")) {
414                     temp = s[i].replace("mo", "").trim();
415                     x = Long.parseLong(temp);
416                     durationInMilliSeconds += (x * 30 * 24 * 60 * 60 * 1000);
417                } else if (s[i].contains("d")) {
418                     temp = s[i].replace("d", "").trim();
419                     x = Long.parseLong(temp);
420                     durationInMilliSeconds += (x * 24 * 60 * 60 * 1000);
421                } else if (s[i].contains("hr")) {
422                     temp = s[i].replace("hr", "").trim();
423                     x = Long.parseLong(temp);
424                     durationInMilliSeconds += (x * 60 * 60 * 1000);
425                } else if (s[i].contains("min")) {
426                     temp = s[i].replace("min", "").trim();
427                     x = Long.parseLong(temp);
428                     durationInMilliSeconds += (x * 60 * 1000);
429                } else if (s[i].contains("s")) {
430                     temp = s[i].replace("s", "").trim();
431                     x = Long.parseLong(temp);
432                     durationInMilliSeconds += (x * 1000);
433                }
434           }
435           Duration dur = fac.newDuration(durationInMilliSeconds);
436           return dur;
437      }
438 
439      /**
440       *  returns the number of milliseconds from the following string
441       * format: xyr xmo xd xhr xmin xs 
442       */
443      public static long StringToLongMS(String d) {
444           if (Utility.stringIsNullOrEmpty(d)) {
445                return 0;
446           }
447           String[] s = d.split(" ");
448           if (s == null || s.length == 0) {
449                return 0;
450           }
451           // DatatypeFactory fac = DatatypeFactory.newInstance();
452           long durationInMilliSeconds = 0;
453           String temp;
454           for (int i = 0; i < s.length; i++) {
455                if (s[i].contains("yr")) {
456                     temp = s[i].replace("yr", "").trim();
457                     durationInMilliSeconds += (Long.parseLong(temp) * 365 * 24 * 60 * 60 * 1000);
458                } else if (s[i].contains("mo")) {
459                     temp = s[i].replace("mo", "").trim();
460                     durationInMilliSeconds += (Long.parseLong(temp) * 30 * 24 * 60 * 60 * 1000);
461                } else if (s[i].contains("d")) {
462                     temp = s[i].replace("d", "").trim();
463                     durationInMilliSeconds += (Long.parseLong(temp) * 24 * 60 * 60 * 1000);
464                } else if (s[i].contains("hr")) {
465                     temp = s[i].replace("hr", "").trim();
466                     durationInMilliSeconds += (Long.parseLong(temp) * 60 * 60 * 1000);
467                } else if (s[i].contains("min")) {
468                     temp = s[i].replace("min", "").trim();
469                     durationInMilliSeconds += (Long.parseLong(temp) * 60 * 1000);
470                } else if (s[i].contains("s")) {
471                     temp = s[i].replace("s", "").trim();
472                     durationInMilliSeconds += (Long.parseLong(temp) * 1000);
473                }
474           }
475           return durationInMilliSeconds;
476      }
477 
478      /**
479       * report type to a friendly name for report types
480       *
481       * @param r
482       * @return
483       */
484       public static String ToFriendlyName(String action, PCS pcs, SecurityWrapper c) {
485           if (action == null) {
486                return "Null classname";
487           }
488 
489           GetPluginInformationRequestMsg req = new GetPluginInformationRequestMsg();
490           req.setGetPluginInformationRequestWrapper(new GetPluginInformationRequestWrapper());
491           req.getGetPluginInformationRequestWrapper().setClassification(c);
492           req.getGetPluginInformationRequestWrapper().setPlugin(new Plugin());
493           req.getGetPluginInformationRequestWrapper().getPlugin().setClassname(action);
494           req.getGetPluginInformationRequestWrapper().getPlugin().setPlugintype("REPORTING");
495           GetPluginInformation r = new GetPluginInformation();
496           r.setRequest(req);
497 
498           try {
499                GetPluginInformationResponse pluginInformation = pcs.getPluginInformation(r);
500 
501                return Utility.encodeHTML(pluginInformation.getResponse().getDisplayName());
502           } catch (Exception ex) {
503                LogHelper.getLog().error(ex);
504           }
505           return "Unrecognized report type " + Utility.encodeHTML(action);
506      }
507 
508      /**
509       * base 64 encoder 
510       */
511      public static String encode(String text) {
512          try {
513              return org.apache.commons.codec.binary.Base64.encodeBase64String(text.getBytes(Constants.CHARSET));
514          } catch (UnsupportedEncodingException ex) {
515              LogHelper.getLog().warn("unexpected base64 encoding error", ex);
516          }
517          return "";
518      }
519 
520      public static String ExportServicePolicy(ServicePolicy pol) {
521           try {
522                JAXBContext jc = Utility.getSerializationContext();
523 
524                Marshaller m = jc.createMarshaller();
525                StringWriter sw = new StringWriter();
526 //            org.miloss.fgsms.services.interfaces.policyconfiguration.ObjectFactory pcsfac = new org.miloss.fgsms.services.interfaces.policyconfiguration.ObjectFactory ();
527 
528                m.marshal((pol), sw);
529                String s = sw.toString();
530                return s;
531           } catch (Exception ex) {
532                Logger.getLogger(Helper.class).log(Level.ERROR, null, ex);
533           }
534           return null;
535      }
536 
537      public static ServicePolicy ImportServicePolicy(String pol, PolicyType pt) {
538           try {
539                JAXBContext jc = Utility.getSerializationContext();
540 
541                Unmarshaller u = jc.createUnmarshaller();
542 
543                ByteArrayInputStream bss = new ByteArrayInputStream(pol.getBytes(Constants.CHARSET));
544                //1 = reader
545                //2 = writer
546                XMLInputFactory xf = XMLInputFactory.newInstance();
547                XMLStreamReader r = xf.createXMLStreamReader(bss);
548                
549                //        com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl r = new com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl(bss, new com.sun.org.apache.xerces.internal.impl.PropertyManager(1));
550 
551                switch (pt) {
552                     case MACHINE:
553                          JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) u.unmarshal(r, MachinePolicy.class);
554                          bss.close();
555                          if (foo != null && foo.getValue() != null) {
556                               return foo.getValue();
557                          }
558                          break;
559                     case PROCESS:
560                          JAXBElement<ProcessPolicy> foo2 = (JAXBElement<ProcessPolicy>) u.unmarshal(r, ProcessPolicy.class);
561                          bss.close();
562                          if (foo2 != null && foo2.getValue() != null) {
563                               return foo2.getValue();
564                          }
565                          break;
566                     case STATISTICAL:
567                          JAXBElement<StatisticalServicePolicy> foo3 = (JAXBElement<StatisticalServicePolicy>) u.unmarshal(r, StatisticalServicePolicy.class);
568                          bss.close();
569                          if (foo3 != null && foo3.getValue() != null) {
570                               return foo3.getValue();
571                          }
572                          break;
573                     case STATUS:
574                          JAXBElement<StatusServicePolicy> foo4 = (JAXBElement<StatusServicePolicy>) u.unmarshal(r, StatusServicePolicy.class);
575                          bss.close();
576                          if (foo4 != null && foo4.getValue() != null) {
577                               return foo4.getValue();
578                          }
579                          break;
580                     case TRANSACTIONAL:
581                          JAXBElement<TransactionalWebServicePolicy> foo5 = (JAXBElement<TransactionalWebServicePolicy>) u.unmarshal(r, TransactionalWebServicePolicy.class);
582                          bss.close();
583                          if (foo5 != null && foo5.getValue() != null) {
584                               return foo5.getValue();
585                          }
586                          break;
587                }
588                bss.close();
589                Logger.getLogger(Helper.class).log(Level.WARN, "ServicePolicy is unexpectedly null or empty");
590                return null;
591           } catch (Exception ex) {
592                Logger.getLogger(Helper.class).log(Level.ERROR, null, ex);
593           }
594           return null;
595 
596      }
597 
598      /**
599       * used on manage.jsp to render SLA info in the tab'd box
600       *
601       * @param item
602       * @return
603       */
604      public static String BuildSLASingleAction(SLAAction item, PCS pcs, SecurityWrapper c) {
605           String s = "";
606           GetPluginInformationResponseMsg GetPluginInfo = GetPluginInfo(item.getImplementingClassName(), "SLA_ACTION", pcs, c);
607           if (GetPluginInfo == null) {
608                return "Unknown SLA Action";
609           }
610           return GetPluginInfo.getDisplayName();
611 
612      }
613 
614      public static FederationPolicy BuildFederation(FederationPolicy src, PCS pcs, SecurityWrapper c, HttpServletRequest req) {
615           Enumeration<String> parameterNames = req.getParameterNames();
616           src.getParameterNameValue().clear();
617           while (parameterNames.hasMoreElements()) {
618                String t = parameterNames.nextElement();
619                if (t.startsWith("plugin_")) {
620                     boolean encryptOnSave = false;
621                     String b = req.getParameter("p_enc_" + t.substring(7));
622                     boolean enc = false;
623                     if (b != null) {
624                          try {
625                               enc = Boolean.parseBoolean(b);
626                          } catch (Exception ex) {
627                          }
628                     }
629                     b = req.getParameter("fed_parameter_enc_" + t.substring(7));
630                     if (b != null) {
631                          try {
632                               encryptOnSave = Boolean.parseBoolean(b);
633                          } catch (Exception ex) {
634                          }
635                     }
636                     if (!Utility.stringIsNullOrEmpty(req.getParameter(t))) {
637                          src.getParameterNameValue().add(Utility.newNameValuePair(t.substring(7), req.getParameter(t), encryptOnSave, enc));
638                     }
639                }
640           }
641 
642           return src;
643      }
644 
645      /**
646       * renders an action set as a user readable html string, occurs when
647       * editing existing slas
648       *
649       * @param items
650       * @return
651       */
652      public static String BuildSLAAction(List<SLAAction> items, PCS pcs, SecurityWrapper c) {
653           String s = "";
654           for (int i = 0; i < items.size(); i++) {
655                if (items.get(i) instanceof SLAAction) {
656                     GetPluginInformationResponseMsg GetPluginInfo = GetPluginInfo(items.get(i).getImplementingClassName(), "SLA_ACTION", pcs, c);
657                     if (GetPluginInfo == null) {
658                          s += "Unknown SLA Action<br>";
659                     } else {
660                          s += GetPluginInfo.getDisplayName() + "<br>";
661                     }
662 
663                }
664           }
665 
666           return s;
667      }
668 
669      public static String RuleToString(RuleBaseType rule) {
670           return rule.getClass().getSimpleName();
671      }
672 
673      /**
674       * Converts a rule to a friendly human readable name
675       *
676       * @param rule
677       * @return
678       */
679      public static String ToFriendylName(RuleBaseType rule, PCS pcs, SecurityWrapper c) {
680           if (rule == null) {
681                return "";
682           }
683           if (rule instanceof AndOrNot) {
684                AndOrNot x = (AndOrNot) rule;
685                if (x.getFlag() == JoiningType.AND) {
686                     return "(" + ToFriendylName(x.getLHS(), pcs, c) + " and " + ToFriendylName(x.getRHS(), pcs, c) + ")";
687                }
688                if (x.getFlag() == JoiningType.OR) {
689                     return "(" + ToFriendylName(x.getLHS(), pcs, c) + " or " + ToFriendylName(x.getRHS(), pcs, c) + ")";
690                }
691                if (x.getFlag() == JoiningType.NOT) {
692                     return "not " + ToFriendylName(x.getLHS(), pcs, c);
693                }
694           } else if (rule instanceof SLARuleGeneric) {
695                SLARuleGeneric r = (SLARuleGeneric) rule;
696                GetPluginInformationResponseMsg GetPluginInfo = GetPluginInfo(r.getClassName(), "SLA_RULE", pcs, c);
697                if (GetPluginInfo == null) {
698                     return "Unknown SLA Rule<br>";
699                } else {
700                     return GetPluginInfo.getDisplayName() + "<br>";
701                }
702 
703           }
704 
705           return "Unrecongized rule " + Utility.encodeHTML(rule.getClass().getName());
706      }
707 
708      /**
709       * Converts a rule instance to a friendly human readable string with
710       * parameter values
711       *
712       * @param rule
713       * @return
714       */
715      public static String BuildSLARuleData(RuleBaseType rule, List<Plugin> rule_plugins) {
716 
717           if (rule == null) {
718                return "";
719           }
720           if (rule instanceof AndOrNot) {
721                AndOrNot x = (AndOrNot) rule;
722                if (x.getFlag() == JoiningType.AND) {
723                     return "(" + BuildSLARuleData(x.getLHS(), rule_plugins) + " and " + BuildSLARuleData(x.getRHS(), rule_plugins) + ")";
724                }
725                if (x.getFlag() == JoiningType.OR) {
726                     return "(" + BuildSLARuleData(x.getLHS(), rule_plugins) + " or " + BuildSLARuleData(x.getRHS(), rule_plugins) + ")";
727                }
728                if (x.getFlag() == JoiningType.NOT) {
729                     return "not " + BuildSLARuleData(x.getLHS(), rule_plugins);
730                }
731           }
732 
733           if (rule instanceof SLARuleGeneric) {
734                SLARuleGeneric x = (SLARuleGeneric) rule;
735                for (int i = 0; i < rule_plugins.size(); i++) {
736                     if (rule_plugins.get(i).getClassname().equalsIgnoreCase(x.getClassName())) {
737                          return rule_plugins.get(i).getDisplayname();
738                     }
739                }
740                return "Plugin: " + Utility.encodeHTML(x.getClassName()) + " ";
741           }
742           return "Unrecongized rule " + rule.getClass().getName();
743 
744      }
745      private static final String SLAPARAM_RULE_CLASS = "Class Name <input type=text  style=\"width: 250px; height:25px; \"  name=\"slaruleclass\" value=\"";
746      private static final String SLAPARAM = "Parameter <input type=text  style=\"width: 250px; height:25px; \"  name=\"parameter\" value=\"";
747      private static final String SLAPARAMPARTITION = "Partition <input type=text  style=\"width: 250px; height:25px; \"  name=\"parameter2\" value=\"";
748      private static final String SLATIMEPARAM = "Time <input type=text  style=\"width: 250px; height:25px; \"  name=\"slatimerange\" value=\"";
749 
750      /**
751       * Renders an SLA Rule for editing via browser
752       *
753       * @param rule
754       * @return T
755       */
756      public static String RenderSLAParametersForEditing(RuleBaseType rule) {
757           try {
758                if (rule == null) {
759                     return "Null rule!";
760                }
761                if (rule instanceof AndOrNot) {
762                     AndOrNot x = (AndOrNot) rule;
763                     if (x.getFlag() == JoiningType.AND) {
764                          return "(" + RenderSLAParametersForEditing(x.getLHS()) + " and " + RenderSLAParametersForEditing(x.getRHS()) + ")";
765                     }
766                     if (x.getFlag() == JoiningType.OR) {
767                          return "(" + RenderSLAParametersForEditing(x.getLHS()) + " or " + RenderSLAParametersForEditing(x.getRHS()) + ")";
768                     }
769                     if (x.getFlag() == JoiningType.NOT) {
770                          return "not " + RenderSLAParametersForEditing(x.getLHS());
771                     }
772                }
773 
774                if (rule instanceof SLARuleGeneric) {
775                     SLARuleGeneric x
776                          = (SLARuleGeneric) rule;
777                     return SLAPARAM_RULE_CLASS + Utility.encodeHTML(x.getClassName()) + "\"><br>Process at: " + RenderRuleRunAt(x.getProcessAt());
778                }
779                return "Unrecongized rule " + rule.getClass().getName();
780 
781           } catch (Exception ex) {
782                Logger.getLogger(Helper.class).log(Level.ERROR, null, ex);
783           }
784           return "";
785      }
786 
787      private static String ListToString(ArrayOfXMLNamespacePrefixies namespaces) {
788           if (namespaces == null) {
789                return "none";
790           }
791           if (namespaces.getXMLNamespacePrefixies().isEmpty()) {
792                return "none";
793           }
794           StringBuilder ret = new StringBuilder();
795           for (int i = 0; i < namespaces.getXMLNamespacePrefixies().size(); i++) {
796                ret = ret.append(Utility.encodeHTML(namespaces.getXMLNamespacePrefixies().get(i).getPrefix())).append(":").append(Utility.encodeHTML(namespaces.getXMLNamespacePrefixies().get(i).getNamespace())).append(" ");
797           }
798           return ret.toString().trim();
799      }
800 
801      private static String AggTimeRange(Duration currentvalue) {
802           if (currentvalue == null) {
803                return "<select name=\"slatimerange\">"
804                     + "<option value=5min>5 minutes</option>"
805                     + "<option value=15min>15 minutes</option>"
806                     + "<option value=60min>60 minutes</option>"
807                     + "<option value=24hr>24 hours</option></select>";
808           }
809           long l = Utility.durationToTimeInMS(currentvalue);
810           if (l == 5 * 60 * 1000) {
811                return "<select name=\"slatimerange\">"
812                     + "<option value=5min selected>5 minutes</option>"
813                     + "<option value=15min>15 minutes</option>"
814                     + "<option value=60min>60 minutes</option>"
815                     + "<option value=24hr>24 hours</option></select>";
816           }
817           if (l == 15 * 60 * 1000) {
818                return "<select name=\"slatimerange\">"
819                     + "<option value=5min >5 minutes</option>"
820                     + "<option value=15min selected>15 minutes</option>"
821                     + "<option value=60min>60 minutes</option>"
822                     + "<option value=24hr>24 hours</option></select>";
823           }
824           if (l == 60 * 60 * 1000) {
825                return "<select name=\"slatimerange\">"
826                     + "<option value=5min >5 minutes</option>"
827                     + "<option value=15min >15 minutes</option>"
828                     + "<option value=60min selected>60 minutes</option>"
829                     + "<option value=24hr>24 hours</option></select>";
830           }
831           if (l == Long.parseLong("86400000")) {
832                return "<select name=\"slatimerange\">"
833                     + "<option value=5min >5 minutes</option>"
834                     + "<option value=15min >15 minutes</option>"
835                     + "<option value=60min >60 minutes</option>"
836                     + "<option value=24hr selected>24 hours</option></select>";
837           }
838           return "<select name=\"slatimerange\">"
839                + "<option value=5min>5 minutes</option>"
840                + "<option value=15min>15 minutes</option>"
841                + "<option value=60min>60 minutes</option>"
842                + "<option value=24hr>24 hours</option></select>";
843      }
844      static org.miloss.fgsms.services.interfaces.policyconfiguration.ObjectFactory fac = new ObjectFactory();
845 
846      /**
847       * constructs a rule from a postback
848       *
849       * @param request
850       * @return
851       */
852      public static RuleBaseType BuildRule(HttpServletRequest request, PCS pcs, SecurityWrapper c) {
853           RuleBaseType rule = null;
854           try {
855 
856                //this is the classname of the plugin
857                String s = request.getParameter("rule1");
858 
859                SLARuleGeneric r = new SLARuleGeneric();
860                try {
861                     if (Utility.stringIsNullOrEmpty(s)) {
862                          return null;
863                     }
864                     r.setClassName(s);
865 
866                     GetPluginInformationResponseMsg info = GetPluginInfo(s, "SLA_RULE", pcs, c);
867                     if (info != null) {
868                          List<NameValuePair> requiredParameter = info.getRequiredParameter();
869                          //this is the authoritative list of parameters
870                          boolean requiredparams = true;
871                          for (NameValuePair pair : requiredParameter) {
872                               if (request.getParameter("plugin_" + pair.getName()) == null) {
873                                    return null;
874                               }
875                               r.getParameterNameValue().add(new NameValuePair(pair.getName(),
876                                    request.getParameter("plugin_" + pair.getName()), false, "checked".equalsIgnoreCase(request.getParameter("p_enc_" + pair.getName()))));
877 
878                          }
879 
880                          requiredParameter = info.getOptionalParameter();;
881                          for (NameValuePair pair : requiredParameter) {
882 
883                               if (request.getParameter("plugin_" + pair.getName()) != null) {
884                                    r.getParameterNameValue().add(new NameValuePair(pair.getName(),
885                                         request.getParameter("plugin_" + pair.getName()), false, "checked".equalsIgnoreCase(request.getParameter("p_enc_" + pair.getName()))));
886                               }
887                          }
888                     }
889 
890                     try {
891                          r.setProcessAt(RunAtLocation.valueOf(request.getParameter("slagenericrulerunat")));
892                     } catch (Exception e) {
893                          LogHelper.getLog().log(Level.INFO, "error building SLA Rule, unparsable value for RunAtLocation ", e);
894                          r.setProcessAt(RunAtLocation.FGSMS_SERVER);
895                     }
896                     rule = r;
897                } catch (Exception ex) {
898                     LogHelper.getLog().log(Level.INFO, "error building SLA Rule", ex);
899                }
900 
901           } catch (Exception ex) {
902                LogHelper.getLog().log(Level.INFO, "error building SLA Rule", ex);
903           }
904           return rule;
905      }
906      public static final String ENCRYPTONSAVE = "ENCRYPTONSAVE";
907      public static final String ISENCRYPTED = "ISENCRYPTED";
908      public static final String PARAMETER_PREFIX = "PARAM-";
909 
910      /**
911       * from manage.jsp and scheduledEditPost.jsp, occurs when a new sla is
912       * added to a policy expects "Action" = plugin classname
913       *
914       * @param request
915       * @param pcs
916       * @return
917       */
918      public static SLAAction BuildSLAAction(HttpServletRequest request, PCS pcs, SecurityWrapper c) {
919           SLAAction action = null;
920 
921           try {
922                String s = request.getParameter("Action");
923                //fix for automated reporting service
924                if (s == null || s.equalsIgnoreCase("null") || s.equalsIgnoreCase("none")) {
925                     return null;
926                }
927                action = new SLAAction();
928                action.setImplementingClassName(s);
929                GetPluginInformationResponseMsg plugin = GetPluginInfo(s, "SLA_ACTION", pcs, c);
930                for (int i = 0; i < plugin.getRequiredParameter().size(); i++) {
931                     NameValuePair nvp = new NameValuePair();
932                     nvp.setName(plugin.getRequiredParameter().get(i).getName());
933                     nvp.setValue(request.getParameter("plugin_" + plugin.getRequiredParameter().get(i).getName()));
934                     nvp.setEncryptOnSave(Boolean.parseBoolean(request.getParameter("p_enc_" + plugin.getRequiredParameter().get(i).getName() + ENCRYPTONSAVE)));
935                     nvp.setEncryptOnSave(Boolean.parseBoolean(request.getParameter(PARAMETER_PREFIX + plugin.getRequiredParameter().get(i).getName() + ISENCRYPTED)));
936                     action.getParameterNameValue().add(nvp);
937                }
938                for (int i = 0; i < plugin.getOptionalParameter().size(); i++) {
939                     NameValuePair nvp = new NameValuePair();
940                     nvp.setName(plugin.getOptionalParameter().get(i).getName());
941                     nvp.setValue(request.getParameter(plugin.getOptionalParameter().get(i).getName()));
942                     if (nvp.getValue() != null) {
943                          if (request.getParameter(PARAMETER_PREFIX + plugin.getOptionalParameter().get(i).getName() + ENCRYPTONSAVE) != null) {
944                               nvp.setEncryptOnSave(Boolean.parseBoolean(request.getParameter(PARAMETER_PREFIX + plugin.getOptionalParameter().get(i).getName() + ENCRYPTONSAVE)));
945                          }
946                          if (request.getParameter(PARAMETER_PREFIX + plugin.getOptionalParameter().get(i).getName() + ISENCRYPTED) != null) {
947                               nvp.setEncryptOnSave(Boolean.parseBoolean(request.getParameter(PARAMETER_PREFIX + plugin.getOptionalParameter().get(i).getName() + ISENCRYPTED)));
948                          }
949                          action.getParameterNameValue().add(nvp);
950                     }
951                }
952 
953           } catch (Exception ex) {
954                LogHelper.getLog().log(Level.INFO, "error building SLA ACtion", ex);
955           }
956           return action;
957      }
958 
959      public static SecurityWrapper GetCurrentSecurityLevel(ProxyLoader pl, ServletContext app, HttpServletRequest request, HttpServletResponse response) throws Exception {
960           if (pl == null) {
961                pl = ProxyLoader.getInstance(app);
962           }
963           PCS pcs = pl.GetPCS(app, request, response);
964           GetGlobalPolicyResponseMsg globalPolicy = pcs.getGlobalPolicy(new GetGlobalPolicyRequestMsg());
965           return globalPolicy.getClassification();
966 
967      }
968 
969      public static boolean RuleHasParameters(RuleBaseType rule, PCS pcs, SecurityWrapper c) {
970 
971           if (rule instanceof AndOrNot) {
972                return true;
973           }
974           if (rule instanceof SLARuleGeneric) {
975                SLARuleGeneric x = (SLARuleGeneric) rule;
976                GetPluginInformationResponseMsg info = GetPluginInfo(x.getClassName(), "SLA_RULE", pcs, c);
977                if (info != null) {
978                     return !info.getRequiredParameter().isEmpty() && !info.getOptionalParameter().isEmpty();
979                }
980           }
981           return false;
982      }
983      static Map pluginCache = new HashMap();
984 
985      /**
986       *
987       * @param clazz
988       * @param type FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
989       * @param pcs
990       * @param c
991       * @return
992       */
993      public static GetPluginInformationResponseMsg GetPluginInfo(String clazz, String type, PCS pcs, SecurityWrapper c) {
994           if (pluginCache.containsKey(clazz + type)) {
995                GetPluginInformationExt item = (GetPluginInformationExt) pluginCache.get(clazz + type);
996                //TODO make this configurable
997                if (System.currentTimeMillis() - item.RefreshedAt < 300000) {
998                     return item;
999                }
1000                pluginCache.remove(clazz + type);
1001 
1002           }
1003           GetPluginInformationRequestMsg req = new GetPluginInformationRequestMsg();
1004           req.setGetPluginInformationRequestWrapper(new GetPluginInformationRequestWrapper());
1005           req.getGetPluginInformationRequestWrapper().setClassification(c);
1006           req.getGetPluginInformationRequestWrapper().setPlugin(new Plugin());
1007           //req.getGetPluginInformationRequestWrapper().setOptionalPolicyTypeFilter(pt);
1008           req.getGetPluginInformationRequestWrapper().getPlugin().setClassname(clazz);
1009           req.getGetPluginInformationRequestWrapper().getPlugin().setPlugintype(type);
1010 
1011           GetPluginInformation r = new GetPluginInformation();
1012           r.setRequest(req);
1013           try {
1014                GetPluginInformationResponse pluginInformation = pcs.getPluginInformation(r);
1015 
1016                return pluginInformation.getResponse();
1017           } catch (Exception ex) {
1018                LogHelper.getLog().error(ex);
1019           }
1020           return null;
1021      }
1022 
1023      /**
1024       *
1025       * @param action
1026       * @param pcs
1027       * @param c
1028       * @param item_type FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
1029       * @return
1030       */
1031      public static String GetPluginHelp(SLAAction action, PCS pcs, SecurityWrapper c, String item_type) {
1032           if (action == null) {
1033                return "Null Action";
1034           }
1035 
1036           GetPluginInformationRequestMsg req = new GetPluginInformationRequestMsg();
1037           req.setGetPluginInformationRequestWrapper(new GetPluginInformationRequestWrapper());
1038           req.getGetPluginInformationRequestWrapper().setClassification(c);
1039           req.getGetPluginInformationRequestWrapper().setPlugin(new Plugin());
1040           req.getGetPluginInformationRequestWrapper().getPlugin().setClassname(action.getImplementingClassName());
1041           req.getGetPluginInformationRequestWrapper().getPlugin().setPlugintype(item_type);
1042           GetPluginInformation r = new GetPluginInformation();
1043           r.setRequest(req);
1044 
1045           try {
1046                GetPluginInformationResponse pluginInformation = pcs.getPluginInformation(r);
1047                return pluginInformation.getResponse().getHelp();
1048           } catch (Exception ex) {
1049                LogHelper.getLog().error(ex);
1050           }
1051           return "No help information could be found.";
1052      }
1053 
1054      /**
1055       *
1056       * @param pcs
1057       * @param c
1058       * @param item_type FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
1059       * @return
1060       */
1061      public static List<Plugin> GetPluginList(PCS pcs, SecurityWrapper c, String item_type) {
1062           return GetPluginList(pcs, c, item_type, null);
1063      }
1064 
1065      public static List<Plugin> GetPluginList(PCS pcs, SecurityWrapper c, String item_type, PolicyType pt) {
1066           if (item_type == null) {
1067                return Collections.EMPTY_LIST;
1068           }
1069 
1070           GetPluginListRequestMsg req = new GetPluginListRequestMsg();
1071           req.setClassification(c);
1072           req.setPlugintype(item_type);
1073           req.setOptionalPolicyTypeFilter(pt);
1074           GetPluginList r = new GetPluginList();
1075           r.setRequest(req);
1076 
1077           try {
1078                GetPluginListResponse pluginList = pcs.getPluginList(r);
1079                return pluginList.getResponse().getPlugins();
1080           } catch (Exception ex) {
1081                LogHelper.getLog().error(ex);
1082           }
1083           return Collections.EMPTY_LIST;
1084      }
1085 
1086      /**
1087       *
1088       * @param action
1089       * @param pcs
1090       * @param c
1091       * @param item_type FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
1092       * @return html escaped friendly name of the plugin
1093       */
1094      public static String ToFriendlyName(SLAAction action, PCS pcs, SecurityWrapper c) {
1095           if (action == null) {
1096                return "Null Action";
1097           }
1098 
1099           GetPluginInformationRequestMsg req = new GetPluginInformationRequestMsg();
1100           req.setGetPluginInformationRequestWrapper(new GetPluginInformationRequestWrapper());
1101           req.getGetPluginInformationRequestWrapper().setClassification(c);
1102           req.getGetPluginInformationRequestWrapper().setPlugin(new Plugin());
1103           req.getGetPluginInformationRequestWrapper().getPlugin().setClassname(action.getImplementingClassName());
1104           req.getGetPluginInformationRequestWrapper().getPlugin().setPlugintype("SLA_ACTION");
1105           GetPluginInformation r = new GetPluginInformation();
1106           r.setRequest(req);
1107 
1108           try {
1109                GetPluginInformationResponse pluginInformation = pcs.getPluginInformation(r);
1110 
1111                return Utility.encodeHTML(pluginInformation.getResponse().getDisplayName());
1112           } catch (Exception ex) {
1113                LogHelper.getLog().error(ex);
1114           }
1115           return "Unrecognized action, " + Utility.encodeHTML(action.getImplementingClassName());
1116      }
1117 
1118      private static String XpathNamespacesToString(ArrayOfXMLNamespacePrefixies namespaces) {
1119           if (namespaces == null) {
1120                return "";
1121           }
1122           if (namespaces.getXMLNamespacePrefixies().isEmpty()) {
1123                return "";
1124           }
1125           //prefix##namespace|prefix2##namespace2
1126           StringBuilder ret = new StringBuilder();
1127           for (int i = 0; i < namespaces.getXMLNamespacePrefixies().size(); i++) {
1128                ret = ret.append(Utility.encodeHTML(namespaces.getXMLNamespacePrefixies().get(i).getPrefix())).append("##").append(Utility.encodeHTML(namespaces.getXMLNamespacePrefixies().get(i).getNamespace())).append("|");
1129           }
1130           return ret.toString().substring(1, ret.length() - 1);
1131 
1132      }
1133 
1134      public static int GetHalfScreenWidth(Cookie[] cookies) {
1135           for (int i = 0; i < cookies.length; i++) {
1136 
1137                if (cookies[i].getName().equalsIgnoreCase("screenwidth")) {
1138                     try {
1139                          int width = Integer.parseInt(cookies[i].getValue());
1140                          if (width > 2) {
1141                               return width / 2;
1142                          }
1143                     } catch (Exception ex) {
1144                     }
1145                }
1146 
1147           }
1148           return 320;
1149      }
1150 
1151      public static String ShowOpStat(SecurityWrapper c, org.miloss.fgsms.services.interfaces.status.OpStatusService ss, String url) {
1152           StringBuilder out = new StringBuilder();
1153           String[] urls = url.split("|");
1154           for (int i = 0; i < urls.length; i++) {
1155                try {
1156 
1157                     BindingProvider bp = (BindingProvider) ss;
1158                     bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, urls[i]);
1159 
1160                     GetOperatingStatusRequestMessage req = new GetOperatingStatusRequestMessage();
1161                     req.setClassification(c);
1162                     GetOperatingStatusResponseMessage res = ss.getOperatingStatus(req);
1163                     if (res.isStatus()) {
1164                          out.append("<h2>OK</h2>");
1165 
1166                     } else {
1167                          out.append("<h2>BAD</h2>");
1168                     }
1169                     out.append("Started at: ").append(res.getStartedAt().toString()).append("<br>");
1170                     out.append("Status Message:").append(Utility.encodeHTML(res.getStatusMessage())).append("<br>");
1171                     out.append("Version Data: ").append(Utility.encodeHTML(res.getVersionInfo().getVersionData())).append("<br>");
1172                     out.append("Version Source: ").append(Utility.encodeHTML(res.getVersionInfo().getVersionSource())).append("<br>");
1173                     out.append("Data Sent Failure: ").append(res.getDataNotSentSuccessfully()).append("<br>");
1174                     out.append("Data Sent Success: ").append(res.getDataSentSuccessfully()).append("<br>");
1175                } catch (Exception ex) {
1176                     out.append("Error caught checking stats on ").append(urls[i]).append(" ").append(ex.getMessage());
1177                }
1178           }
1179           return out.toString();
1180      }
1181 
1182      public static String PluginToReadonlyHtmlString(FederationPolicy fp, int index, HttpServletRequest request) {
1183           StringBuilder out = new StringBuilder();
1184           out.append("<table border=1><tr><th>Key</th><th>Value</th></tr>");
1185 
1186           out.append("<tr><td >Policy Id " + (index) + "</td><td>");
1187           out.append("<input type=button value=\"Edit\" name=\"EditFedPol" + index + "\" "
1188                + " onclick=\"javascript:postBackReRender('EditFedPol" + index
1189                + "','profile/getPolicy.jsp?url=" + URLEncoder.encode(request.getParameter("url")) + "','tab1');\">"
1190                + "<input type=button value=Remove name=\"RemoveFedPol" + index + "\" onclick=\"javascript:postBackReRender('RemoveFedPol" + index
1191                + "','profile/getPolicy.jsp?url=" + URLEncoder.encode(request.getParameter("url")) + "','tab1');\"></td></tr>");
1192 
1193           out.append("<tr><td>Plugin</td><td>" + Utility.encodeHTML(fp.getImplementingClassName()) + "</td></tr>");
1194 
1195           for (int i = 0; i < fp.getParameterNameValue().size(); i++) {
1196                out.append("<tr><td>").append(Utility.encodeHTML(fp.getParameterNameValue().get(i).getName())).append("</td><td>");
1197                if (fp.getParameterNameValue().get(i).isEncrypted()) {
1198                     out.append("ENCRYPTED");
1199                } else {
1200                     out.append(Utility.encodeHTML(fp.getParameterNameValue().get(i).getValue()));
1201                }
1202                out.append("</td></tr>");
1203 
1204           }
1205 
1206           out.append("</td></tr>");
1207 
1208           //end federation tab
1209           out.append("</table>");
1210           return out.toString();
1211      }
1212 
1213      public static String federationPluginEditableHtml(FederationPolicy fp, int index, HttpServletRequest request) {
1214           StringBuilder out = new StringBuilder();
1215           out.append("<table class=\"table table-hover\"><tr><th>Key</th><th>Value</th></tr>");
1216 
1217           out.append("<tr><td >Policy Id " + (index) + "</td><td>");
1218           out.append("<input type=button value=\"Edit\" name=\"EditFedPol" + index + "\" "
1219                + " onclick=\"javascript:postBackReRender('EditFedPol" + index
1220                + "','profile/getPolicy.jsp?url=" + URLEncoder.encode(request.getParameter("url")) + "','tab1');\">"
1221                + "<input type=button value=Remove name=\"RemoveFedPol" + index + "\" onclick=\"javascript:postBackReRender('RemoveFedPol" + index
1222                + "','profile/getPolicy.jsp?url=" + URLEncoder.encode(request.getParameter("url")) + "','tab1');\"></td></tr>");
1223 
1224           out.append("<tr><td>Plugin</td><td>" + Utility.encodeHTML(fp.getImplementingClassName()) + "</td></tr>");
1225 
1226           for (int i = 0; i < fp.getParameterNameValue().size(); i++) {
1227                out.append("<tr><td>").append(Utility.encodeHTML(fp.getParameterNameValue().get(i).getName())).append("</td><td>");
1228                if (fp.getParameterNameValue().get(i).isEncrypted()) {
1229                     out.append("ENCRYPTED");
1230                } else {
1231                     out.append(Utility.encodeHTML(fp.getParameterNameValue().get(i).getValue()));
1232                }
1233                out.append("</td></tr>");
1234 
1235           }
1236 
1237           out.append("</td></tr>");
1238 
1239           //end federation tab
1240           out.append("</table>");
1241           return out.toString();
1242      }
1243 
1244      public static String GetPluginParameterValue(List<NameValuePair> params, String parameterName) {
1245           if (params == null) {
1246                return "";
1247           }
1248           for (int i = 0; i < params.size(); i++) {
1249                if (params.get(i).getName().equals(parameterName)) {
1250                     return params.get(i).getValue();
1251                }
1252           }
1253           return "";
1254      }
1255 
1256      /**
1257       * returns "checked=checked" if the selected parameter exists and it's
1258       * already encrypted
1259       *
1260       * @param params
1261       * @param parameterName
1262       * @return
1263       */
1264      public static String GetPluginParameterIsEncrypted(List<NameValuePair> params, String parameterName) {
1265           if (params == null) {
1266                return "";
1267           }
1268           for (int i = 0; i < params.size(); i++) {
1269                if (params.get(i).getName().equals(parameterName) && params.get(i).isEncrypted()) {
1270                     return "checked=checked";
1271                }
1272           }
1273           return "";
1274      }
1275 
1276      /**
1277       * this function is the sausage maker
1278       *
1279       * @param request
1280       * @param pol
1281       * @return
1282       * @throws Exception
1283       */
1284      public static ServicePolicy buildFromHttpPost(HttpServletRequest request, ServicePolicy pol) throws Exception {
1285 
1286            Enumeration em = request.getParameterNames();
1287 
1288           if (DEBUG) {
1289                System.out.println("*********************************************************");
1290                System.out.println("*********************************************************");
1291                System.out.println("*********************************************************");
1292 
1293                while (em.hasMoreElements()) {
1294                     String key = (String) em.nextElement();
1295                     System.out.println(" params.put(\"" + key + "\", \"" + request.getParameter(key) + "\");");
1296                }
1297                System.out.println("*********************************************************");
1298                System.out.println("*********************************************************");
1299                System.out.println("*********************************************************");
1300           }
1301           
1302           //ok so of all the input parameters, it should be enough to completely reconstruct the service policy.
1303           Integer messagecap = 1024000;
1304           try {
1305                messagecap = Integer.parseInt(request.getParameter("messagecap"));
1306                if (messagecap < 1024) {
1307                     messagecap = 1024;
1308                }
1309           } catch (Exception ex) {
1310           }
1311 
1312           if (!Utility.stringIsNullOrEmpty(request.getParameter("datattl"))) {
1313                pol.setDataTTL(Helper.StringToDuration(request.getParameter("datattl")));
1314           }
1315           if (!Utility.stringIsNullOrEmpty(request.getParameter("refreshrate"))) {
1316                pol.setPolicyRefreshRate(Helper.StringToDuration(request.getParameter("refreshrate")));
1317           }
1318 
1319           if (pol instanceof ProcessPolicy) {
1320                ProcessPolicy mp = (ProcessPolicy) pol;
1321                mp.setAlsoKnownAs(request.getParameter("processaka"));
1322                //
1323 
1324                if (!Utility.stringIsNullOrEmpty(request.getParameter("recordopenfiles"))) {
1325                     mp.setRecordOpenFileHandles(true);
1326                } else {
1327                     mp.setRecordOpenFileHandles(false);
1328                }
1329 
1330                if (!Utility.stringIsNullOrEmpty(request.getParameter("recordcpuusage"))) {
1331                     mp.setRecordCPUusage(true);
1332                } else {
1333                     mp.setRecordCPUusage(false);
1334                }
1335 
1336                if (!Utility.stringIsNullOrEmpty(request.getParameter("recordcmemusage"))) {
1337                     mp.setRecordMemoryUsage(true);
1338                } else {
1339                     mp.setRecordMemoryUsage(false);
1340                }
1341 
1342           }
1343 
1344           if (pol instanceof MachinePolicy) {
1345                MachinePolicy mp = (MachinePolicy) pol;
1346 
1347 //recorddiskusage
1348 //recordnetworkusage
1349                if (!Utility.stringIsNullOrEmpty(request.getParameter("recordcpuusage"))) {
1350                     mp.setRecordCPUusage(true);
1351                } else {
1352                     mp.setRecordCPUusage(false);
1353                }
1354 
1355                if (!Utility.stringIsNullOrEmpty(request.getParameter("recordcmemusage"))) {
1356                     mp.setRecordMemoryUsage(true);
1357                } else {
1358                     mp.setRecordMemoryUsage(false);
1359                }
1360 
1361                mp.getRecordDiskUsagePartitionNames().clear();
1362                if ((request.getParameterValues("recorddiskusage") != null)) {
1363                     String[] t = request.getParameterValues("recorddiskusage");
1364                     for (int k = 0; k < t.length; k++) {
1365                          if (!Utility.stringIsNullOrEmpty(t[k])) {
1366                               mp.getRecordDiskUsagePartitionNames().add(t[k]);
1367                          }
1368                     }
1369                }
1370 
1371                mp.getRecordNetworkUsage().clear();
1372                if ((request.getParameterValues("recordnetworkusage") != null)) {
1373                     String[] t = request.getParameterValues("recordnetworkusage");
1374                     for (int k = 0; k < t.length; k++) {
1375                          if (!Utility.stringIsNullOrEmpty(t[k])) {
1376                               mp.getRecordNetworkUsage().add(t[k]);
1377                          }
1378                     }
1379                }
1380 
1381                mp.getRecordDiskSpace().clear();
1382                if ((request.getParameterValues("recorddrivespace") != null)) {
1383                     String[] t = request.getParameterValues("recorddrivespace");
1384                     for (int k = 0; k < t.length; k++) {
1385                          if (!Utility.stringIsNullOrEmpty(t[k])) {
1386                               mp.getRecordDiskSpace().add(t[k]);
1387                          }
1388                     }
1389                }
1390           }
1391 
1392           if (pol instanceof TransactionalWebServicePolicy) {
1393                TransactionalWebServicePolicy tp = (TransactionalWebServicePolicy) pol;
1394                if (!Utility.stringIsNullOrEmpty(request.getParameter("messagecap"))) {
1395                     try {
1396                          int cap = Integer.parseInt(request.getParameter("messagecap"));
1397                          tp.setRecordedMessageCap(cap);
1398                     } catch (Exception ex) {
1399                     }
1400                }
1401                tp.setRecordedMessageCap(messagecap);
1402                if (Utility.stringIsNullOrEmpty(request.getParameter("recordrequest"))) {
1403                     tp.setRecordRequestMessage(false);
1404                } else {
1405                     tp.setRecordRequestMessage(true);
1406                }
1407                if (Utility.stringIsNullOrEmpty(request.getParameter("recordresponse"))) {
1408                     tp.setRecordResponseMessage(false);
1409                } else {
1410                     tp.setRecordResponseMessage(true);
1411                }
1412                if (Utility.stringIsNullOrEmpty(request.getParameter("recordfault"))) {
1413                     tp.setRecordFaultsOnly(false);
1414                } else {
1415                     tp.setRecordFaultsOnly(true);
1416                }
1417 
1418                if (Utility.stringIsNullOrEmpty(request.getParameter("buellerenabled"))) {
1419                     tp.setBuellerEnabled(false);
1420                } else {
1421                     tp.setBuellerEnabled(true);
1422                }
1423 
1424                tp.setHealthStatusEnabled(false);
1425 
1426                if (Utility.stringIsNullOrEmpty(request.getParameter("recordheaders"))) {
1427                     tp.setRecordHeaders(false);
1428                } else {
1429                     tp.setRecordHeaders(true);
1430                }
1431 
1432                List<UserIdentity> userident = new ArrayList<UserIdentity>();
1433                //TODO consumer identity methods
1434                //1 of 4 options, nothing, httpcred, httpheader, xpath
1435                em = request.getParameterNames();
1436                while (em.hasMoreElements()) {
1437                     String key = (String) em.nextElement();
1438                     if (key != null && key.startsWith("uid_")) {
1439                          String[] bits = key.split("_");
1440                          //bits[0]=header
1441                          //bits[1]= uuid
1442                          //bits[2]=field
1443                          if (bits.length == 3) {
1444                               if (bits[2].equals("method")) {
1445                                    String val = request.getParameter(key);
1446                                    if ("httpcred".equals(val)) {
1447                                         UserIdentity ui = new UserIdentity();
1448                                         ui.setUseHttpCredential(true);
1449                                         userident.add(ui);
1450                                    } else if ("httpheader".equals(val)) {
1451                                         UserIdentity ui = new UserIdentity();
1452                                         ui.setUseHttpHeader(true);
1453                                         ui.setHttpHeaderName(request.getParameter(bits[0] + "_" + bits[1] + "_httpheadername"));
1454                                         userident.add(ui);
1455                                    } else if ("xpath".equals(val)) {
1456                                         //ugh
1457                                         UserIdentity ui = new UserIdentity();
1458                                         ui.setXPaths(new ArrayOfXPathExpressionType());
1459                                         //two potentials with even odds
1460                                         //storing an existing xpath setup
1461                                         //storing a new xpath setup
1462 
1463                                         //check for new xpath expressions
1464                                         if (request.getParameterMap().containsKey((bits[0] + "_" + bits[1] + "_xpathexpression")))
1465                                         {
1466                                              XPathExpressionType xpath = new XPathExpressionType();
1467                                              xpath.setXPath(request.getParameter(bits[0] + "_" + bits[1] + "_xpathexpression"));
1468                                              xpath.setIsCertificate("on".equalsIgnoreCase(request.getParameter(bits[0] + "_" + bits[1] + "_x509certxpath")));
1469 
1470                                              //do new xml namespaces
1471                                              String cluster = request.getParameter(bits[0] + "_" + bits[1] + "_xpathprefixes");
1472                                              if (cluster != null && cluster.length() > 0) {
1473                                                   ArrayOfXMLNamespacePrefixies prefixes = new ArrayOfXMLNamespacePrefixies();
1474 
1475                                                   String[] groups = cluster.split("\\|");
1476                                                   for (int i = 0; i < groups.length; i++) {
1477                                                        String[] pairs = groups[i].split("\\#\\#");
1478                                                        if (pairs != null && pairs.length == 2) {
1479 
1480                                                             XMLNamespacePrefixies xml = new XMLNamespacePrefixies();
1481                                                             xml.setPrefix(pairs[0]);
1482                                                             xml.setNamespace(pairs[1]);
1483                                                             prefixes.getXMLNamespacePrefixies().add(xml);
1484                                                        }
1485                                                   }
1486 
1487                                                   if (!prefixes.getXMLNamespacePrefixies().isEmpty()) {
1488                                                        ui.setNamespaces(prefixes);
1489                                                   }
1490                                              }
1491 
1492                                              ui.getXPaths().getXPathExpressionType().add(xpath);
1493                                         }
1494                                         
1495                                         //now for existing xpaths and prefixes, etc
1496                                         //bits[0]=header
1497                                         //bits[1]= uuid
1498                                         //bits[2]=xpath
1499                                         //bits[3]=uuid
1500                                         //bits[4]=xpath OR prefix OR namespace
1501                                         Set<String> uuidsSet = new HashSet<String>();     //this is the set of namespace prefixes we've already seen
1502                                         //need a temporary map for uuid mappings to prefix + namespace
1503                                          Enumeration em2 = request.getParameterNames();
1504                                         while (em2.hasMoreElements()) {
1505                                              String key2 = (String) em2.nextElement();
1506                                              if (key2 != null && key2.startsWith("uid_")) {
1507                                                   String[] bits2 = key2.split("_");
1508                                                   if (bits2.length==5 &&
1509                                                        bits2[0].equals("uid") && 
1510                                                        bits2[2].equals("xpath") && 
1511                                                        bits2[4].equals("xpath")){
1512                                                        if (ui.getXPaths()==null)
1513                                                             ui.setXPaths(new ArrayOfXPathExpressionType());
1514                                                        XPathExpressionType xpath = new XPathExpressionType();
1515                                                        xpath.setXPath(request.getParameter(key2));
1516                                                        xpath.setIsCertificate("on".equalsIgnoreCase(request.getParameter(bits2[0] + "_" + bits2[1] + "_" + bits2[2] + "_" + bits2[3] + "_x509certxpath")));
1517                                                        ui.getXPaths().getXPathExpressionType().add(xpath);
1518                                                        
1519                                                   } else if (bits2.length==5 &&
1520                                                        bits2[0].equals("uid") &&
1521                                                        (bits2[4].equals("prefix") || bits2[4].equals("namespace")))  {
1522                                                        if (!uuidsSet.contains(bits2[3])){
1523                                                             uuidsSet.add(bits2[3]);
1524                                                             if (ui.getNamespaces()==null)
1525                                                                  ui.setNamespaces(new ArrayOfXMLNamespacePrefixies());
1526                                                             XMLNamespacePrefixies xml = new XMLNamespacePrefixies();
1527                                                             xml.setPrefix((request.getParameter(bits2[0] + "_" + bits2[1] + "_" + bits2[2] + "_" + bits2[3] + "_" + "prefix")));
1528                                                             xml.setNamespace((request.getParameter(bits2[0] + "_" + bits2[1] + "_" + bits2[2] + "_" + bits2[3] + "_" + "namespace")));
1529                                                             
1530                                                             ui.getNamespaces().getXMLNamespacePrefixies().add(xml);
1531                                                             
1532                                                        }
1533                                                        
1534                                                        
1535                                                   }
1536                                              }
1537                                         }
1538                                         if (ui.getXPaths()!=null && ui.getXPaths().getXPathExpressionType().isEmpty())
1539                                              ui.setXPaths(null);
1540                                         if (ui.getNamespaces()!=null && ui.getNamespaces().getXMLNamespacePrefixies().isEmpty())
1541                                              ui.setNamespaces(null);
1542                                         userident.add(ui);
1543                                         //x509certxpath
1544                                    }
1545 
1546                                    //httpcred
1547                                    //httpheader
1548                                    //_headername
1549                                    //xpath
1550                                    //XXX_prefix
1551                                    //XXX_namespace
1552                                    //XXX_xpath
1553                               }
1554                          }
1555                          //if (key.equals(request))
1556                          //String value = (String) request.getParameter(key);
1557 
1558                     }
1559 
1560                }
1561 
1562                if (!userident.isEmpty()) {
1563                     ((TransactionalWebServicePolicy) pol).setUserIdentification(new ArrayOfUserIdentity());
1564                     ((TransactionalWebServicePolicy) pol).getUserIdentification().getUserIdentity().addAll(userident);
1565                } else {
1566                     //none are defined, make sure we clear out the list
1567                     ((TransactionalWebServicePolicy) pol).setUserIdentification(null);
1568                }
1569 
1570           }
1571 
1572           if (Utility.stringIsNullOrEmpty(request.getParameter("externalurl"))) {
1573                pol.setExternalURL(null);
1574           } else {
1575                pol.setExternalURL(request.getParameter("externalurl"));
1576           }
1577 
1578           if (Utility.stringIsNullOrEmpty(request.getParameter("displayName"))) {
1579                pol.setDisplayName(null);
1580           } else {
1581                pol.setDisplayName(request.getParameter("displayName"));
1582           }
1583           if (Utility.stringIsNullOrEmpty(request.getParameter("servername"))) {
1584                pol.setMachineName(null);
1585           } else {
1586                pol.setMachineName(request.getParameter("servername"));
1587           }
1588           if (Utility.stringIsNullOrEmpty(request.getParameter("domainname"))) {
1589                pol.setDomainName(null);
1590           } else {
1591                pol.setDomainName(request.getParameter("domainname"));
1592           }
1593           if (Utility.stringIsNullOrEmpty(request.getParameter("bucket"))) {
1594                pol.setBucketCategory(null);
1595           } else {
1596                pol.setBucketCategory(request.getParameter("bucket"));
1597           }
1598           if (Utility.stringIsNullOrEmpty(request.getParameter("parentobject"))) {
1599                pol.setParentObject(null);
1600           } else {
1601                pol.setParentObject(request.getParameter("parentobject"));
1602           }
1603 
1604           if (Utility.stringIsNullOrEmpty(request.getParameter("description"))) {
1605                pol.setDescription(null);
1606           } else {
1607                pol.setDescription(request.getParameter("description"));
1608           }
1609           if (Utility.stringIsNullOrEmpty(request.getParameter("poc"))) {
1610                pol.setPOC(null);
1611           } else {
1612                pol.setPOC(request.getParameter("poc"));
1613           }
1614 
1615           if (!Utility.stringIsNullOrEmpty(request.getParameter("locationlat"))
1616                && !Utility.stringIsNullOrEmpty(request.getParameter("locationlong"))) {
1617                try {
1618                     double lat = Double.parseDouble(request.getParameter("locationlat"));
1619                     double lon = Double.parseDouble(request.getParameter("locationlong"));
1620                     if (lon >= -180 && lon <= 180 && lat <= 90 && lat >= -90) {
1621                          GeoTag location = new GeoTag();
1622                          location.setLatitude(lat);
1623                          location.setLongitude(lon);
1624                          pol.setLocation((location));
1625                     }
1626                } catch (Exception ex) {
1627                }
1628           }
1629 
1630          
1631        
1632           em = request.getParameterNames();
1633           Map<String, SLA> slaCache = new HashMap<String, SLA>();
1634 
1635           Map<String, Boolean> processedIds = new HashMap<String, Boolean>();
1636           Map<SLA, List<SLAAction>> postAppend = new HashMap<SLA, List<SLAAction>>();
1637           while (em.hasMoreElements()) {
1638                String key = (String) em.nextElement();
1639                if (key.startsWith("sla_") && !key.startsWith("sla_action_")) {  //fixme bandaid
1640                     String[] bits = key.split("_");
1641 
1642                     if (!slaCache.containsKey(bits[1])) {
1643                          SLA stemp = new SLA();
1644                          stemp.setGuid(bits[1]);
1645                          stemp.setAction(new ArrayOfSLAActionBaseType());
1646                          stemp.setRule(new SLARuleGeneric());
1647                          slaCache.put(bits[1], stemp);
1648                     }
1649                     SLA stemp = (SLA) slaCache.get(bits[1]);
1650                     //stemp.getAction().getSLAAction().add(new SLAAction());
1651                     SLARuleGeneric rule = ((SLARuleGeneric) stemp.getRule());
1652 
1653                     //sla_{id}_ACTION_{index}_class
1654                     //sla_{id}_ACTION_{index}_{param}
1655                     //sla_{id}_ACTION_{index}_enc_{param}
1656                     //sla_{id}_RULE_class
1657                     //sla_{id}_RULE_
1658                     //sla_{id}_RULE_{param}
1659                     //sla_{id}_RULE_enc_{param}
1660                     if (bits[2].equalsIgnoreCase("ACTION")) {
1661                          //so we have a 1-N of SLAs, each with a list of actions
1662                          //eixsting SLAs have the index equal to a random uuid from the array
1663                          //new SLAs have a UUID to differentiate them
1664 
1665                          //this prsents a problem, if we see a new item before an existing item, we can't just created a new instance and
1666                          //add it to the array. that would cause data mixup from one action to another.
1667                          //this situation requires a different strategy. if we hit a uuid here, start up another loop to grab just those items
1668                          //add the uuid to the 'already processed' list, then add the new action to a list which will be appened after the main
1669                          //loop is complete
1670                          String index = bits[3];
1671 
1672                          if (!processedIds.containsKey(index)) {
1673                               processedIds.put(index, true);
1674                               if (!postAppend.containsKey(stemp)) {
1675                                    postAppend.put(stemp, new ArrayList<SLAAction>());
1676                               }
1677                               List<SLAAction> newactions = postAppend.get(stemp);
1678 
1679                               Enumeration em2 = request.getParameterNames();
1680                               String prefix = "sla_" + stemp.getGuid() + "_ACTION_" + index;
1681                               SLAAction newaction = new SLAAction();
1682                               while (em2.hasMoreElements()) {
1683                                    String key2 = (String) em2.nextElement();
1684                                    if (key2.startsWith(prefix)) {
1685                                         String value = request.getParameter(key2);
1686                                         String[] bits2 = key2.split("_");
1687                                         //build up the action here. parameters, classname and enc
1688                                         if (bits2[4].equalsIgnoreCase("classname")) {
1689                                              newaction.setImplementingClassName(request.getParameter(key2));
1690                                         } else if (bits2[4].equalsIgnoreCase("enc")) {
1691                                              boolean found = false;
1692                                              boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1693                                              for (int kk = 0; kk < newaction.getParameterNameValue().size(); kk++) {
1694                                                   if (newaction.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits2[5])) {
1695                                                        newaction.getParameterNameValue().get(kk).setEncrypted(enc);
1696                                                        found = true;
1697                                                        break;
1698                                                   }
1699                                              }
1700                                              if (!found) {
1701                                                   //haven't seen this parameter yet, add a new one
1702                                                   NameValuePair nvp = new NameValuePair();
1703                                                   nvp.setName(bits2[5]);
1704                                                   nvp.setEncrypted(enc);
1705                                                   newaction.getParameterNameValue().add(nvp);
1706                                              }
1707                                         } else if (bits2[4].equalsIgnoreCase("encOnSave")) {
1708                                              boolean found = false;
1709                                              boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1710                                              for (int kk = 0; kk < newaction.getParameterNameValue().size(); kk++) {
1711                                                   if (newaction.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits2[5])) {
1712                                                        newaction.getParameterNameValue().get(kk).setEncryptOnSave(enc);
1713                                                        found = true;
1714                                                        break;
1715                                                   }
1716                                              }
1717                                              if (!found) {
1718                                                   //haven't seen this parameter yet, add a new one
1719                                                   NameValuePair nvp = new NameValuePair();
1720                                                   nvp.setName(bits2[5]);
1721                                                   nvp.setEncryptOnSave(enc);
1722                                                   newaction.getParameterNameValue().add(nvp);
1723                                              }
1724                                         } else {
1725                                              //must be a parameter
1726                                              boolean found = false;
1727                                              for (int kk = 0; kk < newaction.getParameterNameValue().size(); kk++) {
1728                                                   if (newaction.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits2[4])) {
1729                                                        newaction.getParameterNameValue().get(kk).setValue(request.getParameter(key2));
1730                                                        found = true;
1731                                                        break;
1732                                                   }
1733                                              }
1734                                              if (!found) {
1735                                                   //haven't seen this parameter yet, add a new one
1736                                                   NameValuePair nvp = new NameValuePair();
1737                                                   nvp.setValue(request.getParameter(key2));
1738                                                   nvp.setName(bits2[4]);
1739                                                   newaction.getParameterNameValue().add(nvp);
1740                                              }
1741 
1742                                         }
1743                                    }
1744 
1745                               }
1746                               //TODO validate that the new action has all the necessary parts
1747                               newactions.add(newaction);
1748                          }
1749                     }
1750                     if (bits[2].equalsIgnoreCase("RULE")) {
1751                          if (bits[3].equalsIgnoreCase("class")) {
1752                               rule.setClassName(request.getParameter(key));
1753 
1754                          } else if (bits[3].equalsIgnoreCase("enc")) {
1755                               boolean found = false;
1756                               String value=request.getParameter(key);
1757                               boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1758                               for (int kk = 0; kk < rule.getParameterNameValue().size(); kk++) {
1759                                    if (rule.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[4])) {
1760                                         rule.getParameterNameValue().get(kk).setEncrypted(enc);
1761                                         found = true;
1762                                         break;
1763                                    }
1764                               }
1765                               if (!found) {
1766                                    //haven't seen this parameter yet, add a new one
1767                                    NameValuePair nvp = new NameValuePair();
1768                                    nvp.setName(bits[4]);
1769                                    nvp.setEncrypted(enc);
1770                                    rule.getParameterNameValue().add(nvp);
1771                               }
1772                          } else if (bits[3].equalsIgnoreCase("encOnSave")) {
1773                               boolean found = false;
1774                               String value=request.getParameter(key);
1775                               boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1776                               for (int kk = 0; kk < rule.getParameterNameValue().size(); kk++) {
1777                                    if (rule.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[4])) {
1778                                         rule.getParameterNameValue().get(kk).setEncryptOnSave(enc);
1779                                         found = true;
1780                                         break;
1781                                    }
1782                               }
1783                               if (!found) {
1784                                    //haven't seen this parameter yet, add a new one
1785                                    NameValuePair nvp = new NameValuePair();
1786                                    nvp.setName(bits[4]);
1787                                    nvp.setEncryptOnSave(enc);
1788                                    rule.getParameterNameValue().add(nvp);
1789                               }
1790                          } else {
1791                               //must be a parameter
1792                               boolean found = false;
1793                               
1794                               for (int kk = 0; kk < rule.getParameterNameValue().size(); kk++) {
1795                                    if (rule.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[3])) {
1796                                         rule.getParameterNameValue().get(kk).setValue(request.getParameter(key));
1797                                         found = true;
1798                                         break;
1799                                    }
1800                               }
1801                               if (!found) {
1802                                    //haven't seen this parameter yet, add a new one
1803                                    NameValuePair nvp = new NameValuePair();
1804                                    nvp.setName(bits[3]);
1805                                    nvp.setValue(request.getParameter(key));
1806                                    rule.getParameterNameValue().add(nvp);
1807                               }
1808                          }
1809                     }
1810 
1811                }
1812           }
1813 
1814           //ok now to postappend the new actions
1815           //Map<String, SLA> slaCache = new HashMap<String, SLA>();
1816           //Map<SLA, List<SLAAction>> postAppend = new HashMap<SLA, List<SLAAction>>();
1817           Iterator<SLA> it = slaCache.values().iterator();
1818           while (it.hasNext()) {
1819                SLA t = it.next();
1820                if (postAppend.containsKey(t)) {
1821                     List<SLAAction> n = (List<SLAAction>) postAppend.get(t);
1822                     t.getAction().getSLAAction().addAll(n);
1823                }
1824 
1825           }
1826           if (pol.getServiceLevelAggrements() == null) {
1827                pol.setServiceLevelAggrements(new ArrayOfSLA());
1828           }
1829 
1830           pol.getServiceLevelAggrements().getSLA().clear();
1831           pol.getServiceLevelAggrements().getSLA().addAll(slaCache.values());
1832           if (pol.getServiceLevelAggrements().getSLA().isEmpty()) {
1833                pol.setServiceLevelAggrements(null);
1834           }
1835 
1836           //federation policy
1837           if (pol.getFederationPolicyCollection() == null) {
1838                pol.setFederationPolicyCollection(new FederationPolicyCollection());
1839           }
1840           pol.getFederationPolicyCollection().getFederationPolicy().clear();
1841 
1842           em = request.getParameterNames();
1843           Map<String, FederationPolicy> feds = new HashMap<String, FederationPolicy>();
1844 
1845           while (em.hasMoreElements()) {
1846                String key = (String) em.nextElement();
1847                if (key.startsWith("fed_")) {
1848                     String[] bits = key.split("_");
1849                     String uuid = bits[1];
1850                     if (!feds.containsKey(uuid)) {
1851                          feds.put(uuid, new FederationPolicy());
1852                     }
1853                     FederationPolicy fpol = feds.get(uuid);
1854                     if (bits[2].equals("class")) {
1855                          fpol.setImplementingClassName(request.getParameter(key));
1856                     } else if (bits[2].equalsIgnoreCase("enc")) {
1857                          boolean found = false;
1858                           String value=request.getParameter(key);
1859                               boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1860                          for (int kk = 0; kk < fpol.getParameterNameValue().size(); kk++) {
1861                               if (fpol.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[3])) {
1862                                    fpol.getParameterNameValue().get(kk).setEncrypted(enc);
1863                                    found = true;
1864                                    break;
1865                               }
1866                          }
1867                          if (!found) {
1868                               //haven't seen this parameter yet, add a new one
1869                               NameValuePair nvp = new NameValuePair();
1870                               nvp.setName(bits[3]);
1871                               nvp.setEncrypted(enc);
1872                               fpol.getParameterNameValue().add(nvp);
1873                          }
1874                     } else if (bits[2].equalsIgnoreCase("encOnSave")) {
1875                          boolean found = false;
1876                           String value=request.getParameter(key);
1877                               boolean enc = value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on");
1878                          for (int kk = 0; kk < fpol.getParameterNameValue().size(); kk++) {
1879                               if (fpol.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[3])) {
1880                                    fpol.getParameterNameValue().get(kk).setEncryptOnSave(enc);
1881                                    found = true;
1882                                    break;
1883                               }
1884                          }
1885                          if (!found) {
1886                               //haven't seen this parameter yet, add a new one
1887                               NameValuePair nvp = new NameValuePair();
1888                               nvp.setName(bits[3]);
1889                               nvp.setEncryptOnSave(enc);
1890                               fpol.getParameterNameValue().add(nvp);
1891                          }
1892                     } else {
1893                          //must be a parameter
1894                          boolean found = false;
1895                          for (int kk = 0; kk < fpol.getParameterNameValue().size(); kk++) {
1896                               if (fpol.getParameterNameValue().get(kk).getName().equalsIgnoreCase(bits[2])) {
1897                                    fpol.getParameterNameValue().get(kk).setValue(request.getParameter(key));
1898                                    found = true;
1899                                    break;
1900                               }
1901                          }
1902                          if (!found) {
1903                               //haven't seen this parameter yet, add a new one
1904                               NameValuePair nvp = new NameValuePair();
1905                               nvp.setName(bits[2]);
1906                               nvp.setValue(request.getParameter(key));
1907                               fpol.getParameterNameValue().add(nvp);
1908                          }
1909                     }
1910 
1911                }
1912           }
1913           pol.getFederationPolicyCollection().getFederationPolicy().addAll(feds.values());
1914           if (pol.getFederationPolicyCollection().getFederationPolicy().isEmpty()) {
1915                pol.setFederationPolicyCollection(null);
1916           }
1917 
1918           return pol;
1919      }
1920      
1921      public static String stripScripts(String html){
1922          //TODO apply the OWASP Html Santitizer
1923          return html;
1924      }
1925 }