View Javadoc
1   /**
2    * This Source Code Form is subject to the terms of the Mozilla Public
3    * License, v. 2.0. If a copy of the MPL was not distributed with this
4    * file, You can 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
7    * file, then You may include the notice in a location (such as a LICENSE
8    * file in a relevant directory) where a recipient would be likely to look
9    * for such a notice.
10   *
11   * 
12   */
13  /*  ---------------------------------------------------------------------------
14   *  U.S. 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.sla;
21  
22  import java.io.*;
23  import java.net.URLEncoder;
24  import java.sql.Connection;
25  import java.sql.PreparedStatement;
26  import java.sql.ResultSet;
27  import java.sql.SQLException;
28  import java.util.*;
29  import java.util.concurrent.atomic.AtomicReference;
30  import javax.mail.Message;
31  import javax.mail.Session;
32  import javax.mail.Transport;
33  import javax.mail.internet.InternetAddress;
34  import javax.mail.internet.MimeMessage;
35  import javax.xml.bind.*;
36  import javax.xml.stream.XMLInputFactory;
37  import javax.xml.stream.XMLStreamReader;
38  import org.apache.log4j.Level;
39  import org.miloss.fgsms.common.Constants;
40  import org.miloss.fgsms.common.Logger;
41  ;
42  import org.miloss.fgsms.common.DBSettingsLoader;
43  import org.miloss.fgsms.common.DBUtils;
44  import org.miloss.fgsms.common.Utility;
45  import org.miloss.fgsms.plugins.sla.AlertContainer;
46  import org.miloss.fgsms.plugins.sla.AlertType;
47  import org.miloss.fgsms.plugins.sla.SLAActionInterface;
48  import org.miloss.fgsms.plugins.sla.SLARuleInterface;
49  import org.miloss.fgsms.services.interfaces.common.DriveInformation;
50  import org.miloss.fgsms.services.interfaces.common.PolicyType;
51  import org.miloss.fgsms.services.interfaces.common.ProcessPerformanceData;
52  import org.miloss.fgsms.services.interfaces.common.SecurityWrapper;
53  import org.miloss.fgsms.services.interfaces.datacollector.AddMachineAndProcessDataRequestMsg;
54  import org.miloss.fgsms.services.interfaces.datacollector.AddStatisticalDataRequestMsg;
55  import org.miloss.fgsms.services.interfaces.policyconfiguration.*;
56  import org.miloss.fgsms.sla.rules.ChangeInAvailabilityStatus;
57  import us.gov.ic.ism.v2.ClassificationType;
58  
59  /**
60   * Provides a number of key functions that are related to SLA management,
61   * alerting, and status setting This does most of the SLA work
62   *
63   * @author AO
64   */
65  
66  
67  public class SLACommon {
68  
69      /**
70       * Thie following items are for SLA Logger actions
71       */
72      private static final Logger log = Logger.getLogger("fgsms.SLAProcessor");
73      private static ResourceBundle bundle = null;
74  
75      /**
76       * loads a resource from the properties file
77       *
78       * @param key
79       * @return
80       */
81      public static String getBundleString(String key) {
82          SetupBundle();
83          return bundle.getString(key);
84      }
85  
86      private static synchronized void SetupBundle() {
87          if (bundle == null) {
88              try {
89                  bundle = ResourceBundle.getBundle("org.miloss.fgsms.sla/SLAResources", Locale.getDefault());
90              } catch (Exception ex) {
91                  log.log(Level.FATAL, "unable to load the resource bundle for " + "org.miloss.fgsms.sla/SLAResources" + Locale.getDefault().toString(), ex);
92              }
93          }
94          if (bundle == null) {
95              try {
96                  bundle = ResourceBundle.getBundle("org.miloss.fgsms.sla/SLAResources");
97              } catch (Exception ex) {
98                  log.log(Level.FATAL, "unable to load the resource bundle for " + "org.miloss.fgsms.sla/SLAResources", ex);
99              }
100         }
101         if (bundle == null) {
102             bundle = new ResourceBundle() {
103                 @Override
104                 protected Object handleGetObject(String key) {
105                     return "Bundle not available!";
106                 }
107 
108                 @Override
109                 public Enumeration<String> getKeys() {
110                     return null;
111                 }
112             };
113         }
114     }
115 
116     /**
117      * Returns the current machine's hostname using
118      * InetAddress.getLocalHost().getHostName().toLowerCase(); The hostname will
119      * always be lower case. This function should never throw an exception. If
120      * the current machine does not have a valid hostname or it is not dns
121      * resolvable, then "ADDRESS_UNKNOWN" is returned
122      *
123      * @return
124      */
125     public static String GetHostName() {
126         return Utility.getHostName();
127     }
128 
129     /**
130      * used by NT SLA processor for web services loads service policies with SLA
131      * policies defined Connection must be to the config database, remains open
132      * after executing
133      *
134      * @param con an open database connection to the config database, remains
135      * open after returning
136      * @return
137      */
138     private static List<ServicePolicy> loadServicePolicies(Connection con) {
139         SetupBundle();
140         PreparedStatement comm = null;
141         ResultSet results = null;
142         try {
143             List<ServicePolicy> l = new ArrayList<ServicePolicy>();
144 
145             comm = con.prepareStatement("Select * from ServicePolicies where hassla=true;");
146 
147             //ret.PublishToUDDITimeRange = null;
148             /////////////////////////////////////////////
149             //get the policy for this service
150             /////////////////////////////////////////////
151             Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
152             results = comm.executeQuery();
153 
154             while (results.next()) {
155                 ServicePolicy ret = null;
156 
157                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
158 
159                 byte[] s = results.getBytes("xmlpolicy");
160 
161                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
162                 XMLInputFactory xf = XMLInputFactory.newInstance();
163                 XMLStreamReader r = xf.createXMLStreamReader(bss);
164                 switch (pt) {
165                     case MACHINE:
166                         JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
167                         if (foo == null || foo.getValue() == null) {
168                             log.log(Level.WARN, bundle.getString("MachinePolicyNull"));
169                         } else {
170                             ret = foo.getValue();
171                         }
172                         break;
173                     case PROCESS:
174                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
175                         if (foo3 == null || foo3.getValue() == null) {
176                             log.log(Level.WARN, bundle.getString("ProcessPolicyNull"));
177                         } else {
178                             ret = foo3.getValue();
179                         }
180                         break;
181                     case STATISTICAL:
182                         JAXBElement<StatisticalServicePolicy> foo1 = (JAXBElement<StatisticalServicePolicy>) um.unmarshal(r, StatisticalServicePolicy.class);
183                         if (foo1 == null || foo1.getValue() == null) {
184                             log.log(Level.WARN, bundle.getString("BrokerPolicyNull"));
185                         } else {
186                             ret = foo1.getValue();
187                         }
188                         break;
189                     case STATUS:
190                         JAXBElement<StatusServicePolicy> foo2 = (JAXBElement<StatusServicePolicy>) um.unmarshal(r, StatusServicePolicy.class);
191                         if (foo2 == null || foo2.getValue() == null) {
192                             log.log(Level.WARN, bundle.getString("StatusPolicyNull"));
193                         } else {
194                             ret = foo2.getValue();
195                         }
196                         break;
197                     case TRANSACTIONAL:
198                         JAXBElement<TransactionalWebServicePolicy> foo4 = (JAXBElement<TransactionalWebServicePolicy>) um.unmarshal(r, TransactionalWebServicePolicy.class);
199                         if (foo4 == null || foo4.getValue() == null) {
200                             log.log(Level.WARN, bundle.getString("WSPolicyNull"));
201                         } else {
202                             ret = foo4.getValue();
203                         }
204                         break;
205                 }
206 
207                 r.close();
208                 bss.close();
209 
210                 l.add(ret);
211 
212             }
213             return l;
214         } catch (Exception ex) {
215             log.log(Level.WARN, bundle.getString("ErrorLoadingPolicyForSLA"), ex);
216         } finally {
217             DBUtils.safeClose(results);
218             DBUtils.safeClose(comm);
219         }
220         return new ArrayList<ServicePolicy>();
221     }
222 
223     /**
224      * used by NT SLA for web services
225      *
226      * @return either an empty list, or a list containing service policies that
227      * contain SLA's
228      */
229     public static List<ServicePolicy> LoadServicePoliciesPooled() {
230         SetupBundle();
231         Connection con = Utility.getConfigurationDBConnection();
232         List<ServicePolicy> r = null;
233         try {
234             r = loadServicePolicies(con);
235         } catch (Exception ex) {
236             log.log(Level.ERROR, bundle.getString("ErrorLoadingPolicy"), ex);
237         } finally {
238             DBUtils.safeClose(con);
239         }
240         if (r == null) {
241             r = new ArrayList<ServicePolicy>();
242         }
243         return r;
244     }
245 
246     /**
247      * used by NT SLA for web services
248      *
249      * @return
250      */
251     public static List<ServicePolicy> LoadServicePoliciesNotPooled() {
252         Connection con = Utility.getConfigurationDB_NONPOOLED_Connection();
253         SetupBundle();
254         List<ServicePolicy> r = null;
255         try {
256             r = loadServicePolicies(con);
257         } catch (Exception ex) {
258             log.log(Level.ERROR, bundle.getString("ErrorLoadingPolicy"), ex);
259         } finally {
260             DBUtils.safeClose(con);
261         }
262         if (r == null) {
263             r = new ArrayList<ServicePolicy>();
264         }
265         return r;
266     }
267 
268     /**
269      * Loads a specific policy, connection stays open after running
270      *
271      * @param con
272      * @param uRI
273      * @return
274      */
275     private static ServicePolicy loadPolicy(final Connection con, final String uRI) {
276         if (Utility.stringIsNullOrEmpty(uRI)) {
277             throw new IllegalArgumentException("requestedURI");
278         }
279         SetupBundle();
280         PreparedStatement comm = null;
281         ResultSet results = null;
282         try {
283 
284             ServicePolicy ret = null;
285 
286             comm = con.prepareStatement("Select * from ServicePolicies where URI=?;");
287             comm.setString(1, uRI);
288 
289             results = comm.executeQuery();
290 
291             if (results.next()) {
292                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
293                 Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
294                 byte[] s = results.getBytes("xmlpolicy");
295 
296                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
297                 //1 = reader
298                 //2 = writer
299                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
300                 XMLInputFactory xf = XMLInputFactory.newInstance();
301                 XMLStreamReader r = xf.createXMLStreamReader(bss);
302                 switch (pt) {
303                     case MACHINE:
304                         JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
305                         if (foo == null || foo.getValue() == null) {
306                             log.log(Level.WARN, "policy is unexpectedly null or empty");
307                         } else {
308                             ret = foo.getValue();
309                         }
310                         break;
311                     case PROCESS:
312                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
313                         if (foo3 == null || foo3.getValue() == null) {
314                             log.log(Level.WARN, "policy is unexpectedly null or empty");
315                         } else {
316                             ret = foo3.getValue();
317                         }
318                         break;
319                     case STATISTICAL:
320                         JAXBElement<StatisticalServicePolicy> foo1 = (JAXBElement<StatisticalServicePolicy>) um.unmarshal(r, StatisticalServicePolicy.class);
321                         if (foo1 == null || foo1.getValue() == null) {
322                             log.log(Level.WARN, "policy is unexpectedly null or empty");
323                         } else {
324                             ret = foo1.getValue();
325                         }
326                         break;
327                     case STATUS:
328                         JAXBElement<StatusServicePolicy> foo2 = (JAXBElement<StatusServicePolicy>) um.unmarshal(r, StatusServicePolicy.class);
329                         if (foo2 == null || foo2.getValue() == null) {
330                             log.log(Level.WARN, "policy is unexpectedly null or empty");
331                         } else {
332                             ret = foo2.getValue();
333                         }
334                         break;
335                     case TRANSACTIONAL:
336                         JAXBElement<TransactionalWebServicePolicy> foo4 = (JAXBElement<TransactionalWebServicePolicy>) um.unmarshal(r, TransactionalWebServicePolicy.class);
337                         if (foo4 == null || foo4.getValue() == null) {
338                             log.log(Level.WARN, "policy is unexpectedly null or empty");
339                         } else {
340                             ret = foo4.getValue();
341                         }
342                         break;
343                 }
344                 r.close();
345                 bss.close();
346 
347                 return ret;
348             }
349 
350         }catch (Exception ex) {
351             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
352         } finally {
353             DBUtils.safeClose(results);
354             DBUtils.safeClose(comm);
355         }
356         return null;
357 
358     }
359 
360     /**
361      * Loads a policy using a caching mechanism, used by DCS and DAS if the
362      * policy does not exist, it will NOT be created
363      *
364      * @param uRI
365      * @return
366      */
367     public static ServicePolicy LoadPolicyPooled(String uRI) {
368         SetupBundle();
369         Connection con = Utility.getConfigurationDBConnection();
370         ServicePolicy sp = loadPolicy(con, uRI);
371         try {
372             con.close();
373         } catch (SQLException ex) {
374             log.log(Level.WARN, bundle.getString("ErrorClosingDB"), ex);
375         }
376         return sp;
377     }
378 
379     /**
380      * used by qpid agents
381      *
382      * @param uRI
383      * @return
384      */
385     @Deprecated
386     public static ServicePolicy LoadPolicyNotPooled(String uRI) {
387         SetupBundle();
388         Connection con = Utility.getConfigurationDB_NONPOOLED_Connection();
389         ServicePolicy sp = loadPolicy(con, uRI);
390         DBUtils.safeClose(con);
391         return sp;
392     }
393 
394     public static String GenerateSubscriptionLink(String property) {
395         SetupBundle();
396         return String.format(bundle.getString("AlertingSettings"), property);
397         //return "You are currently subscribed to receive email alerts for this service. <a href=\"" + property + "/alertingSettings.jsp\">Click here</a> to manage your subscriptions.";
398     }
399 
400     /**
401      *
402      * @param con stays open after executing
403      * @param guid
404      * @return may be null
405      */
406     private static InternetAddress[] getSubscribers(Connection con, String guid) {
407         SetupBundle();
408         PreparedStatement prepareStatement=null;
409         ResultSet rs= null;
410         try {
411             List<InternetAddress> emails = new ArrayList<InternetAddress>();
412 
413             prepareStatement = con.prepareStatement("select users.username,email,email1,email2,email3 from slasub, users where slaid=? and slasub.username=users.username;");
414             prepareStatement.setString(1, guid);
415             rs = prepareStatement.executeQuery();
416             //String emails = "";
417             while (rs.next()) {
418                 InternetAddress a;
419                 try {
420                     if (!Utility.stringIsNullOrEmpty(rs.getString("email"))) {
421                         a = new InternetAddress(rs.getString("email").trim());
422                         emails.add(a);
423                     }
424                 } catch (Exception ex) {
425                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("users.username")) + rs.getString("email"), ex);
426                     //"Error creating InternetAddress object which is used to send email to %s, perhaps its an invalid email address " + rs.getString("users.username"), ex);
427                 }
428                 try {
429                     if (!Utility.stringIsNullOrEmpty(rs.getString("email1"))) {
430                         a = new InternetAddress(rs.getString("email1").trim());
431                         emails.add(a);
432                     }
433                 } catch (Exception ex) {
434                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("users.username")) + rs.getString("email1"), ex);
435                 }
436                 try {
437                     if (!Utility.stringIsNullOrEmpty(rs.getString("email2"))) {
438                         a = new InternetAddress(rs.getString("email2").trim());
439                         emails.add(a);
440                     }
441                 } catch (Exception ex) {
442                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("users.username")) + rs.getString("email2"), ex);
443                 }
444                 try {
445                     if (!Utility.stringIsNullOrEmpty(rs.getString("email3"))) {
446                         a = new InternetAddress(rs.getString("email3").trim());
447                         emails.add(a);
448                     }
449                 } catch (Exception ex) {
450                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("users.username")) + rs.getString("email3"), ex);
451                 }
452 
453             }
454             
455             Set<InternetAddress> nodup = new HashSet<InternetAddress>(emails);
456             InternetAddress[] d = new InternetAddress[nodup.size()];
457             return emails.toArray(d);
458         } catch (SQLException ex) {
459             log.log(Level.ERROR, bundle.getString("ErrorSQLException"), ex);
460         } catch (Exception ex) {
461             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
462         } finally {
463             DBUtils.safeClose(rs);
464             DBUtils.safeClose(prepareStatement);
465         }
466         return null;
467     }
468 
469     /**
470      * Returns a list of user's email addresses that are subscribed to a
471      * specific SLA with email actions
472      *
473      * @param guid
474      * @return
475      */
476     @Deprecated
477     public static InternetAddress[] GetSubscribersNotPooled(String guid) {
478         SetupBundle();
479         Connection con = Utility.getConfigurationDB_NONPOOLED_Connection();
480         InternetAddress[] sp = getSubscribers(con, guid);
481          DBUtils.safeClose(con);
482         return sp;
483     }
484 
485     /**
486      * Returns a list of user's email addresses that are subscribed to a
487      * specific SLA with email actions
488      *
489      * @param guid
490      * @return
491      */
492     public static InternetAddress[] GetSubscribersPooled(String guid) {
493         SetupBundle();
494         Connection con = Utility.getConfigurationDBConnection();
495         InternetAddress[] sp = getSubscribers(con, guid);
496           DBUtils.safeClose(con);
497         return sp;
498 
499     }
500 
501     /**
502      * gets a service policy from the database, will not create one if one does not exist.
503      * @param requestedURI
504      * @param pooled
505      * @return 
506      */
507     private static org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicy getPolicy(final String requestedURI, final boolean pooled) {
508         Connection con = null;
509         SetupBundle();
510          PreparedStatement comm = null;
511          ResultSet results =null;
512         try {
513             if (Utility.stringIsNullOrEmpty(requestedURI)) {
514                 throw new IllegalArgumentException("requestedURI");
515             }
516             if (pooled) {
517                 con = Utility.getConfigurationDBConnection();
518             } else {
519                 con = Utility.getConfigurationDB_NONPOOLED_Connection();
520             }
521 
522             ServicePolicy ret = null;
523            
524 
525             comm = con.prepareStatement("Select * from ServicePolicies where URI=?;");
526             comm.setString(1, requestedURI);
527 
528             results = comm.executeQuery();
529 
530             if (results.next()) {
531                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
532                 Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
533                 byte[] s = results.getBytes("xmlpolicy");
534 
535                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
536                 //1 = reader
537                 //2 = writer
538                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
539                 XMLInputFactory xf = XMLInputFactory.newInstance();
540                 XMLStreamReader r = xf.createXMLStreamReader(bss);
541                 switch (pt) {
542                     case MACHINE:
543                         JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
544                         if (foo == null || foo.getValue() == null) {
545                             log.log(Level.WARN, bundle.getString("MachinePolicyNull"));
546                         } else {
547                             ret = foo.getValue();
548                         }
549                         break;
550                     case PROCESS:
551                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
552                         if (foo3 == null || foo3.getValue() == null) {
553                             log.log(Level.WARN, bundle.getString("ProcessPolicyNull"));
554                         } else {
555                             ret = foo3.getValue();
556                         }
557                         break;
558                     case STATISTICAL:
559                         JAXBElement<StatisticalServicePolicy> foo1 = (JAXBElement<StatisticalServicePolicy>) um.unmarshal(r, StatisticalServicePolicy.class);
560                         if (foo1 == null || foo1.getValue() == null) {
561                             log.log(Level.WARN, bundle.getString("BrokerPolicyNull"));
562                         } else {
563                             ret = foo1.getValue();
564                         }
565                         break;
566                     case STATUS:
567                         JAXBElement<StatusServicePolicy> foo2 = (JAXBElement<StatusServicePolicy>) um.unmarshal(r, StatusServicePolicy.class);
568                         if (foo2 == null || foo2.getValue() == null) {
569                             log.log(Level.WARN, bundle.getString("StatusPolicyNull"));
570                         } else {
571                             ret = foo2.getValue();
572                         }
573                         break;
574                     case TRANSACTIONAL:
575                         JAXBElement<TransactionalWebServicePolicy> foo4 = (JAXBElement<TransactionalWebServicePolicy>) um.unmarshal(r, TransactionalWebServicePolicy.class);
576                         if (foo4 == null || foo4.getValue() == null) {
577                             log.log(Level.WARN, bundle.getString("WSPolicyNull"));
578                         } else {
579                             ret = foo4.getValue();
580                         }
581                         break;
582                 }
583                 r.close();
584                 bss.close();
585                 return ret;
586             }
587         
588         } catch (JAXBException ex) {
589             log.log(Level.ERROR, bundle.getString("ErrorMarshallingPolicy"), ex);
590         } catch (SQLException ex) {
591             log.log(Level.ERROR, bundle.getString("ErrorSQLException"), ex);
592         } catch (Exception ex) {
593             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
594         } finally {
595             DBUtils.safeClose(results);
596             DBUtils.safeClose(comm);
597             DBUtils.safeClose(con);
598         }
599         
600         return null;
601 
602     }
603 
604     private static boolean containsChangeInStatus(RuleBaseType b) {
605         if (b == null) {
606             return false;
607         }
608         if (b instanceof SLARuleGeneric) {
609             {
610                 SLARuleGeneric asd = (SLARuleGeneric) b;
611                 if (asd.getClassName().equalsIgnoreCase(ChangeInAvailabilityStatus.class.getCanonicalName())) {
612                     return true;
613                 }
614             }
615 
616         }
617         if (b instanceof AndOrNot) {
618             AndOrNot x = (AndOrNot) b;
619             if (x.getFlag() == JoiningType.AND) {
620                 return containsChangeInStatus(x.getLHS()) && containsChangeInStatus(x.getRHS());
621             }
622             if (x.getFlag() == JoiningType.OR) {
623                 return containsChangeInStatus(x.getLHS()) || containsChangeInStatus(x.getRHS());
624             }
625         }
626         return false;
627     }
628 
629     /**
630      * Call this function when a monitored item changes status. This function
631      * will handle all actions related to the change, such as sending emails
632      *
633      * @param uri
634      * @param oldstatus
635      * @param oldmsg
636      * @param currenstatus
637      * @param s
638      * @param pooled
639      */
640     public static void TriggerStatusChange(String uri, Boolean oldstatus, String oldmsg, Boolean currenstatus, String s, boolean pooled) {
641         SetupBundle();
642         ServicePolicy pol = SLACommon.getPolicy(uri, pooled);
643         if (pol == null || pol.getServiceLevelAggrements() == null
644                 || pol.getServiceLevelAggrements().getSLA().isEmpty()) {
645             return;
646         }
647 
648         for (int i = 0; i < pol.getServiceLevelAggrements().getSLA().size(); i++) {
649             if (containsChangeInStatus(pol.getServiceLevelAggrements().getSLA().get(i).getRule())) {
650                 String msgplain = String.format(bundle.getString("StatusChangeEmailAlertPlain"), uri, s);
651                 String msghtml = String.format(bundle.getString("StatusChangeEmailAlertHtml"), Utility.encodeHTML(uri), oldmsg, s, (currenstatus ? "OK" : "NG"));
652                 //"Change In Status Alert for " + pol.getURL() + " current status is " + s, "<br>The service identified by " + Utility.encodeHTML(uri) + " current availablity status has changed. It was previously " + oldmsg + " and is now " + s + "<br>"
653                 //                + "<h2>Current Status: " + (currenstatus ? "OK" : "NG") + "</h2>"
654                 ProcessAlerts(msgplain, msghtml, uri, null,
655                         System.currentTimeMillis(), null, pooled,
656                         false, pol.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction(),
657                         pol.getServiceLevelAggrements().getSLA().get(i).getGuid(), pol, AlertType.Status);
658             }
659 
660         }
661     }
662 
663     public static void RecordSLAFault(AtomicReference<String> faultMsg, final String uRL, final String relatedMsgID, long timeInMillis, String incidentid, final boolean pooled) {
664         SetupBundle();
665         Connection con = null;
666          PreparedStatement com=null;
667         try {
668             if (pooled) {
669                 con = Utility.getPerformanceDBConnection();
670             } else {
671                 con = Utility.getPerformanceDB_NONPOOLED_Connection();
672             }
673            
674             if (Utility.stringIsNullOrEmpty(relatedMsgID)) {
675                 /*
676                  * Non transactional
677                  */
678                 com = con.prepareStatement("INSERT INTO slaviolations (utcdatetime, msg, uri, incidentid)"
679                         + " VALUES (?, ?, ?, ?); ");
680                 com.setLong(1, timeInMillis);
681                 com.setBytes(2, faultMsg.get().getBytes(Constants.CHARSET));
682                 com.setString(3, uRL);
683                 com.setString(4, incidentid);
684             } else {
685                 com = con.prepareStatement("INSERT INTO slaviolations (utcdatetime, msg, uri, relatedtransaction, incidentid)"
686                         + "VALUES (?, ?, ?, ?, ?); "
687                         + "UPDATE rawdata SET  slafault=? WHERE transactionid=?;");
688                 com.setLong(1, timeInMillis);
689                 if (faultMsg == null || faultMsg.get() == null) {
690                     com.setBytes(2, "No fault message provided.".getBytes(Constants.CHARSET));
691                 } else {
692                     com.setBytes(2, faultMsg.get().getBytes(Constants.CHARSET));
693                 }
694                 com.setString(3, uRL);
695                 com.setString(4, relatedMsgID);
696                 com.setString(5, incidentid);
697                 //com.setLong(6, timeInMillis);
698                 com.setString(6, incidentid);
699                 com.setString(7, relatedMsgID);
700             }
701 
702             com.execute();
703         } catch (Exception ex) {
704             log.log(Level.ERROR, bundle.getString("ErrorSavingSLAViolation"), ex);
705         } finally {
706             DBUtils.safeClose(com);
707             DBUtils.safeClose(con);
708         }
709 
710     }
711 
712     /**
713      * returns all of the mail settings, use from pooled connections with jndi
714      *
715      * @return
716      */
717     public static Properties LoadSLAPropertiesPooled() {
718         Connection con = Utility.getConfigurationDBConnection();
719         Properties p = loadSLAProperties(con);
720         DBUtils.safeClose(con);
721         return p;
722     }
723 
724     /**
725      * returns all of the mail settings, use from nonpooled connections,
726      * connections loaded from properties file in common
727      *
728      * @return
729      */
730     @Deprecated
731     public static Properties LoadSLAPropertiesNotPooled() {
732         Connection con = Utility.getConfigurationDB_NONPOOLED_Connection();
733         Properties p = loadSLAProperties(con);
734         DBUtils.safeClose(con);
735         return p;
736     }
737 
738     /**
739      * This function loads all of the Email properties from the database
740      *
741      * @param config
742      * @return
743      */
744     private static Properties loadSLAProperties(Connection config) {
745         SetupBundle();
746         Properties p = new Properties();
747         PreparedStatement com = null;
748         ResultSet rs = null;
749         try {
750             if (config == null) {
751                 return p;
752             }
753             com = config.prepareStatement("Select * from mail;");
754             rs = com.executeQuery();
755             while (rs.next()) {
756                 p.put(rs.getString("property"), rs.getString("valuecol"));
757             }
758         } catch (SQLException ex) {
759             log.log(Level.WARN, bundle.getString("ErrorLoadingSendMailSettings"), ex);
760         } catch (Exception ex) {
761             log.log(Level.WARN, bundle.getString("ErrorUncaughtException"), ex);
762         } finally {
763             DBUtils.safeClose(rs);
764             DBUtils.safeClose(com);
765         }
766         return p;
767     }
768 
769     /**
770      * sends and informative alert to everyone in the database that has the
771      * admin role (site admins)
772      *
773      * @param agentUsername
774      * @param url
775      * @param pooled
776      * @param p
777      */
778     public static void AlertGlobalAdminsNewPolicyCreated(String agentUsername, String url, boolean pooled, PolicyType p) {
779         SetupBundle();
780         try {
781             //get all subscribers
782 
783             Properties props = null;
784             if (pooled) {
785                 props = LoadSLAPropertiesPooled();
786             } else {
787                 props = LoadSLAPropertiesNotPooled();
788             }
789 
790             Session mailSession = Session.getDefaultInstance(props);
791             Message simpleMessage = new MimeMessage(mailSession);
792             InternetAddress from;
793             InternetAddress[] to = null;
794             from = new InternetAddress(props.getProperty("defaultReplyAddress"));
795             if (pooled) {
796                 to = GetAllfgsmsAdminsEmailAddressPooled();
797             } else {
798                 to = GetAllfgsmsAdminsEmailAddressNotPooled();
799             }
800             simpleMessage.setFrom(from);
801             log.log(Level.INFO, "Sending New Policy Alert to Administrators via Email to " + to.length + " addresses");
802             for (int i = 0; i < to.length; i++) {
803 
804                 try {
805                     simpleMessage.setRecipient(Message.RecipientType.TO, to[i]);
806                     simpleMessage.setSubject(bundle.getString("AlertGlobalAdminsNewPolicyCreatedSubject"));
807 //"A new policy has been created by:<br><br>" + Utility.encodeHTML(agentUsername) + "<br><br>URL: " + Utility.encodeHTML(url)
808                     //                        + "<br><br>The Policy Type for this service is  " + p.value() + "<br><br>This email is just an informative alert that a new service has been detected and that users may wish to gain access to it.<Br>"
809                     //                    + "<a href=\"" + props.getProperty("fgsms.GUI.URL") + "\">fgsms</a>" + "<br>" + GenerateManageLink(url, props.getProperty("fgsms.GUI.URL")) + "<br>"
810                     simpleMessage.setContent(
811                             String.format(bundle.getString("AlertGlobalAdminsNewPolicyCreated"),
812                                     Utility.encodeHTML(agentUsername),
813                                     Utility.encodeHTML(url),
814                                     p.value(),
815                                     props.getProperty("fgsms.GUI.URL")) + GenerateManageLink(url, props.getProperty("fgsms.GUI.URL")),
816                             bundle.getString("EmailEncodingType"));
817                     Transport.send(simpleMessage);
818                 } catch (Exception ex) {
819                     log.log(Level.ERROR, bundle.getString("ErrorSendingEmail") + to[i].getAddress() + ex);
820                 }
821             }
822         } catch (Exception ex) {
823             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException") + ex.toString());
824         }
825     }
826 
827     public static String GenerateManageLink(String uri, String baseurl) {
828         SetupBundle();
829         return String.format(bundle.getString("ManageLink"), baseurl, URLEncoder.encode(uri));
830         //"<a href=\"" + baseurl + "/manage.jsp?url=" + URLEncoder.encode(uri) + "\">Manage this policy</a>";
831     }
832 
833     public static void AlertUserSLASubscribed(String subscribersUsername, List<String> subscribersEmail, SetAlertRegistrationsRequestMsg request, boolean pooled) {
834         SetupBundle();
835         try {
836             //get all subscribers
837 
838             Properties props = null;
839             if (pooled) {
840                 props = LoadSLAPropertiesPooled();
841             } else {
842                 props = LoadSLAPropertiesNotPooled();
843             }
844 
845             Session mailSession = Session.getDefaultInstance(props);
846             Message simpleMessage = new MimeMessage(mailSession);
847             InternetAddress from;
848 
849             from = new InternetAddress(props.getProperty("defaultReplyAddress"));
850             for (int k = 0; k < subscribersEmail.size(); k++) {
851                 try {
852                     InternetAddress to = new InternetAddress(subscribersEmail.get(k).trim());
853                     simpleMessage.setFrom(from);
854                     simpleMessage.setRecipient(Message.RecipientType.TO, to);
855                     simpleMessage.setSubject(bundle.getString("AlertSubscriptionSubject"));
856                     StringBuilder sb = new StringBuilder();
857                     sb = sb.append(subscribersUsername).append(bundle.getString("AlertSubscriptionBody1"));
858                     for (int i = 0; i < request.getItems().size(); i++) {
859                         sb = sb.append("<li>").append(Utility.encodeHTML(request.getItems().get(i).getServiceUri())).append(" - ").append(Utility.encodeHTML(request.getItems().get(i).getSLAID())).append("</li>");
860                     }
861                     sb = sb.append(bundle.getString("AlertSubscriptionBody2")).append(SLACommon.GenerateSubscriptionLink(props.getProperty("fgsms.GUI.URL")));
862                     simpleMessage.setContent(sb.toString(), bundle.getString("EmailEncodingType"));
863                     Transport.send(simpleMessage);
864                 } catch (Exception e) {
865                     //log.log(Level.ERROR, "AlertUserSLASubscribed Error sending SLA alert email! " + subscribersEmail.get(k) + " " + e.getMessage());
866                     log.log(Level.ERROR, bundle.getString("ErrorSendingEmail") + subscribersEmail.get(k) + " " + e.getMessage());
867                     log.log(Level.DEBUG, bundle.getString("ErrorSendingEmail") + subscribersEmail.get(k), e);
868                 }
869             }
870         } catch (Exception ex) {
871             //log.log(Level.ERROR, "AlertUserSLASubscribed Error sending SLA alert email! " + ex.getMessage());
872             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
873         }
874     }
875 
876     /**
877      * sends an email to email subscribed users for alerts, letting them know
878      * that the SLA was deleted, along with their subscription
879      *
880      * @param currentUser
881      * @param subscribersUsername
882      * @param subscribersEmail
883      * @param uRL
884      * @param id
885      * @param pooled
886      */
887     public static void AlertUserSLADeleted(String currentUser, String subscribersUsername, List<String> subscribersEmail, String uRL, String id, boolean pooled) {
888         SetupBundle();
889         try {
890             //get all subscribers
891 
892             Properties props = null;
893             if (pooled) {
894                 props = LoadSLAPropertiesPooled();
895             } else {
896                 props = LoadSLAPropertiesNotPooled();
897             }
898 
899             Session mailSession = Session.getDefaultInstance(props);
900             Message simpleMessage = new MimeMessage(mailSession);
901             InternetAddress from;
902 
903             from = new InternetAddress(props.getProperty("defaultReplyAddress"));
904             for (int k = 0; k < subscribersEmail.size(); k++) {
905                 try {
906                     InternetAddress to = new InternetAddress(subscribersEmail.get(k).trim());
907                     simpleMessage.setFrom(from);
908                     simpleMessage.setRecipient(Message.RecipientType.TO, to);
909                     simpleMessage.setSubject(bundle.getString("AlertSubscriptionDeletedSubject"));
910 
911                     simpleMessage.setContent(
912                             String.format(bundle.getString("AlertSubscriptionDeletedBody"), subscribersUsername, Utility.encodeHTML(uRL),
913                                     Utility.encodeHTML(id), Utility.encodeHTML(currentUser), props.getProperty("fgsms.GUI.URL"))
914                             //subscribersUsername + "<br><br>The SLA subscription for the service located at<br><br>" + uRL
915                             //+ "<br><br>with the id " + id + " has been removed because either the SLA parameters were removed or the service is no longer monitored and was removed. This action was performed by  " + currentUser + ".<br>"
916                             //+ "<a href=\"" + props.getProperty("fgsms.GUI.URL") + "\">fgsms</a>" + "<br><br>"
917                             + SLACommon.GenerateSubscriptionLink(props.getProperty("fgsms.GUI.URL")), bundle.getString("EmailEncodingType"));
918                     Transport.send(simpleMessage);
919                 } catch (Exception e) {
920                     log.log(Level.ERROR, bundle.getString("ErrorSendingEmail") + subscribersEmail.get(k), e);
921                     //log.log(Level.ERROR, "AlertUserSLADeleted Error sending SLA alert email! " + subscribersEmail.get(k) + " " + e.getMessage());
922                 }
923             }
924         } catch (Exception ex) {
925             //log.log(Level.ERROR, "AlertUserSLADeleted Error sending SLA alert email! " + ex.getMessage());
926             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
927         }
928     }
929 
930     @Deprecated
931     public static InternetAddress[] GetAllfgsmsAdminsEmailAddressNotPooled() {
932         SetupBundle();
933         Connection con = Utility.getConfigurationDB_NONPOOLED_Connection();
934         InternetAddress[] sp = getAllfgsmsAdminsEmailAddress(con);
935         DBUtils.safeClose(con);
936         return sp;
937     }
938 
939     public static InternetAddress[] GetAllfgsmsAdminsEmailAddressPooled() {
940         SetupBundle();
941         Connection con = Utility.getConfigurationDBConnection();
942         InternetAddress[] sp = getAllfgsmsAdminsEmailAddress(con);
943        DBUtils.safeClose(con);
944         return sp;
945 
946     }
947 
948     private static InternetAddress[] getAllfgsmsAdminsEmailAddress(Connection con) {
949         SetupBundle();
950         PreparedStatement prepareStatement=null;
951         ResultSet rs = null;
952         try {
953             List<InternetAddress> emails = new ArrayList<InternetAddress>();
954 
955             prepareStatement = con.prepareStatement("select username,email,email1,email2,email3 from users where rolecol='admin';");
956             rs = prepareStatement.executeQuery();
957             //String emails = "";
958             while (rs.next()) {
959                 InternetAddress a;
960                 try {
961                     if (!Utility.stringIsNullOrEmpty(rs.getString("email"))) {
962                         a = new InternetAddress(rs.getString("email").trim());
963                         emails.add(a);
964                     }
965                 } catch (Exception ex) {
966                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("username")) + rs.getString("email"), ex);
967                 }
968                 try {
969                     if (!Utility.stringIsNullOrEmpty(rs.getString("email1"))) {
970                         a = new InternetAddress(rs.getString("email1").trim());
971                         emails.add(a);
972                     }
973                 } catch (Exception ex) {
974                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("username")) + rs.getString("email1"), ex);
975                 }
976                 try {
977                     if (!Utility.stringIsNullOrEmpty(rs.getString("email2"))) {
978                         a = new InternetAddress(rs.getString("email2").trim());
979                         emails.add(a);
980                     }
981                 } catch (Exception ex) {
982                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("username")) + rs.getString("email2"), ex);
983                 }
984                 try {
985                     if (!Utility.stringIsNullOrEmpty(rs.getString("email3"))) {
986                         a = new InternetAddress(rs.getString("email3").trim());
987                         emails.add(a);
988                     }
989                 } catch (Exception ex) {
990                     log.log(Level.WARN, String.format(bundle.getString("ErrorCreateInternetAddress"), rs.getString("username")) + rs.getString("email3"), ex);
991                 }
992             }
993             
994             Set<InternetAddress> s = new HashSet<InternetAddress>(emails);
995             InternetAddress[] d = new InternetAddress[s.size()];
996             return s.toArray(d);
997         } catch (SQLException ex) {
998             log.log(Level.ERROR, bundle.getString("ErrorSQLException"), ex);
999         } catch (Exception ex) {
1000             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
1001         } finally {
1002             DBUtils.safeClose(rs);
1003             DBUtils.safeClose(prepareStatement);
1004         }
1005         return null;
1006 
1007     }
1008 
1009     public static boolean ListContainsStatisticalRules(ArrayOfSLA serviceLevelAggrements) {
1010         if (serviceLevelAggrements == null) {
1011             return false;
1012         }
1013 
1014         if (serviceLevelAggrements.getSLA().isEmpty()) {
1015             return false;
1016         }
1017         for (int i = 0; i < serviceLevelAggrements.getSLA().size(); i++) {
1018             if (containsStatisticalRules(serviceLevelAggrements.getSLA().get(i).getRule())) {
1019                 return true;
1020             }
1021         }
1022         return false;
1023     }
1024 
1025     private static boolean containsStatisticalRules(RuleBaseType rule) {
1026         if (rule == null) {
1027             return false;
1028         }
1029         //FIXME
1030         return true;
1031     }
1032 
1033     /*
1034      public static void ProcessStatisticalSLARules2(String modifiedurl, Map currenttopics, boolean pooled) {
1035      ServicePolicy pol = null;
1036      SetupBundle();
1037      if (pooled) {
1038      pol = LoadPolicyPooled(modifiedurl);
1039      } else {
1040      pol = LoadPolicyNotPooled(modifiedurl);
1041      }
1042      if (pol == null) {
1043      return;
1044      }
1045      if (pol.getServiceLevelAggrements() == null) {
1046      return;
1047      }
1048      if (pol.getServiceLevelAggrements().getValue() == null) {
1049      return;
1050      }
1051      if (pol.getServiceLevelAggrements().getValue().getSLA() == null) {
1052      return;
1053      }
1054      if (pol.getServiceLevelAggrements().getValue().getSLA().isEmpty()) {
1055      return;
1056      }
1057      for (int i = 0; i < pol.getServiceLevelAggrements().getValue().getSLA().size(); i++) {
1058            
1059             
1060      if (ProcessStatisticalSLARulesRecursive(req, pooled, null, null, null))
1061      if (pol.getServiceLevelAggrements().getValue().getSLA().get(i).getRule() instanceof QueueOrTopicDoesNotExist) {
1062      QueueOrTopicDoesNotExist rr = (QueueOrTopicDoesNotExist) pol.getServiceLevelAggrements().getValue().getSLA().get(i).getRule();
1063      boolean found = false;
1064      if (currenttopics.containsKey(rr.getParameter())) {
1065      found = true;
1066      }
1067 
1068      if (!found) {
1069      String msg = String.format(bundle.getString("SLAQueueNotExists"), rr.getParameter());
1070      String id = UUID.randomUUID().toString();
1071      RecordSLAFault(new AtomicReference<String>(msg), modifiedurl, null, System.currentTimeMillis(), id, pooled);
1072      ProcessAlerts(msg, "<h2>" + Utility.encodeHTML(msg) + "</h2>", modifiedurl, null, System.currentTimeMillis(), id, pooled, false, pol.getServiceLevelAggrements().getValue().getSLA().get(i).getAction().getSLAActionBaseType(), pol.getServiceLevelAggrements().getValue().getSLA().get(i).getGuid(), pol, AlertType.Status);
1073      }
1074      }
1075      if (pol.getServiceLevelAggrements().getValue().getSLA().get(i).getRule() instanceof BrokerQueueSizeGreaterThan) {
1076      BrokerQueueSizeGreaterThan rr = (BrokerQueueSizeGreaterThan) pol.getServiceLevelAggrements().getValue().getSLA().get(i).getRule();
1077      Iterator it = currenttopics.keySet().iterator();
1078      StringBuilder msg = new StringBuilder();
1079      while (it.hasNext()) {
1080      String str = (String) it.next();
1081      long get = (Long) currenttopics.get(str);
1082      if (get > rr.getParameter()) {
1083      msg.append("The queue named ").append(str).append(" has a queue size of ").append(get).append(" which is greater than the SLA parameter of ").append(rr.getParameter()).append(". ");
1084      }
1085      }
1086      String s = msg.toString();
1087      if (!Utility.stringIsNullOrEmpty(s)) {
1088      String id = UUID.randomUUID().toString();
1089      RecordSLAFault(new AtomicReference<String>(s), modifiedurl, null, System.currentTimeMillis(), id, pooled);
1090      ProcessAlerts(s, "<h2>" + Utility.encodeHTML(s) + "</h2>", modifiedurl, null, System.currentTimeMillis(), id, pooled, false, pol.getServiceLevelAggrements().getValue().getSLA().get(i).getAction().getSLAActionBaseType(), pol.getServiceLevelAggrements().getValue().getSLA().get(i).getGuid(), pol, AlertType.Status);
1091      }
1092      }
1093      }
1094      }*/
1095     /**
1096      * will never return null, but returned value may be an empty list if no
1097      * policies are defined
1098      *
1099      * @param hostname
1100      * @return
1101      */
1102     public static List<ProcessPolicy> LoadProcessPoliciesPooledByHostname(String hostname) {
1103         if (Utility.stringIsNullOrEmpty(hostname)) {
1104             throw new IllegalArgumentException("hostname");
1105         }
1106         SetupBundle();
1107         Connection con = Utility.getConfigurationDBConnection();
1108         List<ProcessPolicy> l = new ArrayList<ProcessPolicy>();
1109         PreparedStatement comm = null;
1110          ResultSet results=null;
1111         try {
1112 
1113             ProcessPolicy ret = null;
1114             
1115 
1116             comm = con.prepareStatement("Select * from ServicePolicies where policytype=? and hostname=?;");
1117             comm.setInt(1, PolicyType.PROCESS.ordinal());
1118             comm.setString(2, hostname);
1119 
1120             results = comm.executeQuery();
1121 
1122             while (results.next()) {
1123                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
1124                 Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
1125                 byte[] s = results.getBytes("xmlpolicy");
1126 
1127                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1128                 //1 = reader
1129                 //2 = writer
1130                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
1131                 XMLInputFactory xf = XMLInputFactory.newInstance();
1132                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1133                 switch (pt) {
1134                     case PROCESS:
1135                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
1136                         if (foo3 == null || foo3.getValue() == null) {
1137                             log.log(Level.WARN, bundle.getString("ProcessPolicyNull"));
1138                         } else {
1139                             ret = foo3.getValue();
1140                         }
1141                         break;
1142                 }
1143                 r.close();
1144                 bss.close();
1145 
1146                 l.add(ret);
1147             }
1148         } catch (JAXBException ex) {
1149             log.log(Level.ERROR, bundle.getString("ErrorMarshallingPolicy"), ex);
1150         } catch (SQLException ex) {
1151             log.log(Level.ERROR, bundle.getString("ErrorSQLException"), ex);
1152         } catch (Exception ex) {
1153             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
1154         } finally {
1155             DBUtils.safeClose(results);
1156             DBUtils.safeClose(comm);
1157             DBUtils.safeClose(con);
1158         }
1159         
1160         return l;
1161 
1162     }
1163 
1164     /**
1165      * may return null if no policy exists
1166      *
1167      * @param hostname
1168      * @return
1169      */
1170     private static MachinePolicy loadMachinePolicyPooled(String hostname) {
1171         if (Utility.stringIsNullOrEmpty(hostname)) {
1172             throw new IllegalArgumentException("hostname");
1173         }
1174         SetupBundle();
1175         Connection con = Utility.getConfigurationDBConnection();
1176         MachinePolicy ret = null;
1177         PreparedStatement comm = null;
1178         ResultSet results = null;
1179         try {
1180 
1181             comm = con.prepareStatement("Select * from ServicePolicies where policytype=? and hostname=?;");
1182             comm.setInt(1, PolicyType.MACHINE.ordinal());
1183             comm.setString(2, hostname);
1184 
1185             results = comm.executeQuery();
1186 
1187             while (results.next()) {
1188                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
1189                 Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
1190                 byte[] s = results.getBytes("xmlpolicy");
1191 
1192                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1193                 //1 = reader
1194                 //2 = writer
1195                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
1196                 XMLInputFactory xf = XMLInputFactory.newInstance();
1197                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1198                 switch (pt) {
1199                     case MACHINE:
1200                         JAXBElement<MachinePolicy> foo3 = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
1201                         if (foo3 == null || foo3.getValue() == null) {
1202                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1203                         } else {
1204                             ret = foo3.getValue();
1205                         }
1206                         break;
1207                 }
1208                 r.close();
1209                 bss.close();
1210             }
1211            
1212         } catch (JAXBException ex) {
1213             log.log(Level.ERROR, bundle.getString("ErrorMarshallingPolicy"), ex);
1214         } catch (SQLException ex) {
1215             log.log(Level.ERROR, bundle.getString("ErrorSQLException"), ex);
1216         } catch (Exception ex) {
1217             log.log(Level.ERROR, bundle.getString("ErrorUncaughtException"), ex);
1218         } finally {
1219             DBUtils.safeClose(results);
1220             DBUtils.safeClose(comm);
1221             DBUtils.safeClose(con);
1222         }
1223         GlobalPolicy gp = DBSettingsLoader.GetGlobalPolicy(true);
1224         if (ret != null) {
1225             ret.setPolicyRefreshRate(gp.getPolicyRefreshRate());
1226         }
1227         return ret;
1228     }
1229 
1230     public static MachinePolicy ProcessMachineLevelSLAs(AddMachineAndProcessDataRequestMsg req, boolean pooled) {
1231         MachinePolicy mp = loadMachinePolicyPooled(req.getHostname());
1232         AuxHelper.TryUpdateStatus(req.getMachineData().isOperationalstatus(),
1233                 req.getMachineData().getUri(),
1234                 req.getMachineData().getStatusmessage(), pooled,
1235                 PolicyType.MACHINE,
1236                 req.getDomainname(),
1237                 req.getHostname());
1238         processMachineSLAs(req, mp, pooled);
1239 
1240         return mp;
1241     }
1242 
1243     public static List<ProcessPolicy> ProcessProcessLevelSLAs(AddMachineAndProcessDataRequestMsg req, boolean pooled) {
1244         List<ProcessPolicy> ret = LoadProcessPoliciesPooledByHostname(req.getHostname());
1245         for (int i = 0; i < req.getProcessData().size(); i++) {
1246             //Bug fix, if a process policy was deleted at the agent doesn't know about it, this will actually recreate the process policy, which is not desired.
1247             if (PolicyExists(req.getProcessData().get(i).getUri(), pooled)) {
1248                 AuxHelper.TryUpdateStatus(req.getProcessData().get(i).isOperationalstatus(),
1249                         req.getProcessData().get(i).getUri(),
1250                         req.getProcessData().get(i).getStatusmessage(), pooled,
1251                         PolicyType.PROCESS,
1252                         req.getDomainname(),
1253                         req.getHostname());
1254                 processProcessSLAs(req.getProcessData().get(i), ret, pooled);
1255             }
1256         }
1257 
1258         return ret;
1259     }
1260 
1261     private static boolean processMachineSLAsRecursive(AddMachineAndProcessDataRequestMsg req, RuleBaseType rule, MachinePolicy pol, boolean pooled, AtomicReference<String> outFaultmsg) {
1262         if (outFaultmsg == null) {
1263             outFaultmsg = new AtomicReference<String>();
1264         }
1265         if (pol == null) {
1266             log.log(Level.INFO, bundle.getString("ErrorProcessMachineSLANullPolicy") + req.getDomainname() + " " + req.getHostname());
1267             return false;
1268         }
1269         SetupBundle();
1270         StringBuilder sb = new StringBuilder();
1271 
1272         if (pol.getServiceLevelAggrements() == null) {
1273             return false;
1274         }
1275 
1276         if (rule instanceof AndOrNot) {
1277             AndOrNot aon = (AndOrNot) rule;
1278             switch (aon.getFlag()) {
1279                 case AND:
1280                     return processMachineSLAsRecursive(req, rule, pol, pooled, outFaultmsg) && processMachineSLAsRecursive(req, rule, pol, pooled, outFaultmsg);
1281                 case OR:
1282                     return processMachineSLAsRecursive(req, rule, pol, pooled, outFaultmsg) || processMachineSLAsRecursive(req, rule, pol, pooled, outFaultmsg);
1283                 case NOT:
1284                     return !processMachineSLAsRecursive(req, rule, pol, pooled, outFaultmsg);
1285             }
1286         }
1287 
1288         if (rule instanceof SLARuleGeneric) {
1289             SLARuleGeneric x = (SLARuleGeneric) rule;
1290             if (x.getProcessAt() == RunAtLocation.FGSMS_SERVER) {
1291                 Class c = null;
1292                 try {
1293                     c = Thread.currentThread().getContextClassLoader().loadClass(x.getClassName());
1294                 } catch (ClassNotFoundException ex) {
1295                     log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1296                 }
1297                 Object obj = null;
1298                 if (c != null) {
1299                     try {
1300                         obj = c.newInstance();
1301                     } catch (InstantiationException ex) {
1302                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1303 
1304                     } catch (IllegalAccessException ex) {
1305                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1306                     }
1307                     SLARuleInterface cast = null;
1308                     try {
1309                         cast = (SLARuleInterface) obj;
1310                     } catch (ClassCastException ex) {
1311                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleTypeCast"), x.getClassName(), SLARuleInterface.class.getCanonicalName()), ex);
1312                     }
1313                     try {
1314                         AtomicReference<String> f = new AtomicReference<String>();
1315                         if (cast != null && cast.CheckTransactionalRule(req.getMachineData(), x.getParameterNameValue(), f)) {
1316                             sb = sb.append(f.get());
1317                             outFaultmsg.set(sb.toString() + " " + outFaultmsg.get());
1318                             return true;
1319                         }
1320                     } catch (Exception ex) {
1321                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleUnexpectedError"), x.getClassName()), ex);
1322                     }
1323                 }
1324             }
1325         }
1326         return false;
1327     }
1328 
1329     /**
1330      * does process specific SLA processing, scope: just right now
1331      *
1332      * @param processData
1333      * @param pooled
1334      */
1335     private static void processMachineSLAs(AddMachineAndProcessDataRequestMsg req, MachinePolicy pol, boolean pooled) {
1336 
1337         if (pol == null || pol.getServiceLevelAggrements() == null) {
1338             return;
1339         }
1340         for (int i = 0; i < pol.getServiceLevelAggrements().getSLA().size(); i++) {
1341             RuleBaseType rule = pol.getServiceLevelAggrements().getSLA().get(i).getRule();
1342 
1343             AtomicReference<String> msg = new AtomicReference<String>();
1344             if (processMachineSLAsRecursive(req, rule, pol, pooled, msg)) {
1345                 String id = UUID.randomUUID().toString();
1346                 RecordSLAFault(new AtomicReference<String>(msg.get()), pol.getURL(), req.getMachineData().getId(), System.currentTimeMillis(), id, pooled);
1347                 ProcessAlerts(msg.get(), "<h2" + Utility.encodeHTML(msg.get()) + "</h2>", pol.getURL(), req.getMachineData().getId(), System.currentTimeMillis(), id, pooled,
1348                         false, pol.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction(), pol.getServiceLevelAggrements().getSLA().get(i).getGuid(), pol, AlertType.Performance);
1349             }
1350         }
1351     }
1352 
1353     private static boolean processProcessSLAsRecursive(ProcessPerformanceData machineData, List<ProcessPolicy> pol, boolean pooled, RuleBaseType rule, AtomicReference<String> outFaultMsg) {
1354 
1355         if (rule instanceof AndOrNot) {
1356             AndOrNot aon = (AndOrNot) rule;
1357             switch (aon.getFlag()) {
1358                 case AND:
1359                     return processProcessSLAsRecursive(machineData, pol, pooled, rule, outFaultMsg) && processProcessSLAsRecursive(machineData, pol, pooled, rule, outFaultMsg);
1360                 case OR:
1361                     return processProcessSLAsRecursive(machineData, pol, pooled, rule, outFaultMsg) || processProcessSLAsRecursive(machineData, pol, pooled, rule, outFaultMsg);
1362                 case NOT:
1363                     return !processProcessSLAsRecursive(machineData, pol, pooled, rule, outFaultMsg);
1364             }
1365         }
1366         if (rule instanceof SLARuleGeneric) {
1367             SLARuleGeneric x = (SLARuleGeneric) rule;
1368             if (x.getProcessAt() == RunAtLocation.FGSMS_SERVER) {
1369                 Class c = null;
1370                 try {
1371                     c = Thread.currentThread().getContextClassLoader().loadClass(x.getClassName());
1372                 } catch (ClassNotFoundException ex) {
1373                     log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1374                 }
1375                 Object obj = null;
1376                 if (c != null) {
1377                     try {
1378                         obj = c.newInstance();
1379                     } catch (InstantiationException ex) {
1380                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1381 
1382                     } catch (IllegalAccessException ex) {
1383                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1384                     }
1385                     SLARuleInterface cast = null;
1386                     try {
1387                         cast = (SLARuleInterface) obj;
1388                     } catch (ClassCastException ex) {
1389                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleTypeCast"), x.getClassName(), SLARuleInterface.class.getCanonicalName()), ex);
1390                     }
1391                     try {
1392                         AtomicReference<String> f = new AtomicReference<String>();
1393                         if (cast != null && cast.CheckTransactionalRule(machineData, x.getParameterNameValue(), f)) {
1394                             outFaultMsg.set(f.get() + " " + outFaultMsg.get());
1395                             return true;
1396                         }
1397                     } catch (Exception ex) {
1398                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleUnexpectedError"), x.getClassName()), ex);
1399                     }
1400                 }
1401             }
1402         }
1403         return false;
1404     }
1405 
1406     /**
1407      * process SLAs for specific processes
1408      *
1409      * @param machineData
1410      * @param pol
1411      * @param pooled
1412      */
1413     private static void processProcessSLAs(ProcessPerformanceData machineData, List<ProcessPolicy> pol, boolean pooled) {
1414         if (pol == null) {
1415             log.log(Level.WARN, bundle.getString("ErrorProcessSLANullPolicy") + machineData.getUri());
1416             return;
1417         }
1418         SetupBundle();
1419         ProcessPolicy pp = locateRecord(pol, machineData.getUri());
1420         if (pp == null) {
1421             return;
1422         }
1423         if (pp.getServiceLevelAggrements() == null) {
1424             return;
1425         }
1426         for (int i = 0; i < pp.getServiceLevelAggrements().getSLA().size(); i++) {
1427             RuleBaseType rule = pp.getServiceLevelAggrements().getSLA().get(i).getRule();
1428 
1429             AtomicReference<String> fault = new AtomicReference<String>();
1430 
1431             if (processProcessSLAsRecursive(machineData, pol, pooled, rule, fault)) {
1432                 String id = UUID.randomUUID().toString();
1433                 RecordSLAFault(new AtomicReference<String>(fault.get()), pp.getURL(), machineData.getId(), System.currentTimeMillis(), id, pooled);
1434                 ProcessAlerts((fault.get()), "<h2>" + Utility.encodeHTML(fault.get()) + "</h2>", pp.getURL(), machineData.getId(), System.currentTimeMillis(),
1435                         id, pooled, false, pp.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction(),
1436                         pp.getServiceLevelAggrements().getSLA().get(i).getGuid(), pp, AlertType.Performance);
1437             }
1438         }
1439     }
1440 
1441     private static ProcessPolicy locateRecord(List<ProcessPolicy> pol, String uri) {
1442         if (pol == null || pol.isEmpty()) {
1443             return null;
1444         }
1445         for (int i = 0; i < pol.size(); i++) {
1446             if (pol.get(i).getURL().equalsIgnoreCase(uri)) {
1447                 return pol.get(i);
1448             }
1449         }
1450         return null;
1451     }
1452 
1453     private static boolean processStatisticalSLARulesRecursive(AddStatisticalDataRequestMsg req, boolean pooled, RuleBaseType rule, AtomicReference<String> outFaultMsg, AtomicReference<AlertType> alertType) {
1454         if (rule instanceof AndOrNot) {
1455             AndOrNot aon = (AndOrNot) rule;
1456             switch (aon.getFlag()) {
1457                 case AND:
1458                     return processStatisticalSLARulesRecursive(req, pooled, rule, outFaultMsg, alertType) && processStatisticalSLARulesRecursive(req, pooled, rule, outFaultMsg, alertType);
1459                 case OR:
1460                     return processStatisticalSLARulesRecursive(req, pooled, rule, outFaultMsg, alertType) || processStatisticalSLARulesRecursive(req, pooled, rule, outFaultMsg, alertType);
1461                 case NOT:
1462                     return !processStatisticalSLARulesRecursive(req, pooled, rule, outFaultMsg, alertType);
1463             }
1464         }
1465         if (rule instanceof SLARuleGeneric) {
1466             SLARuleGeneric x = (SLARuleGeneric) rule;
1467             if (x.getProcessAt() == RunAtLocation.FGSMS_SERVER) {
1468                 Class c = null;
1469                 try {
1470                     c = Thread.currentThread().getContextClassLoader().loadClass(x.getClassName());
1471                 } catch (ClassNotFoundException ex) {
1472                     log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1473                 }
1474                 Object obj = null;
1475                 if (c != null) {
1476                     try {
1477                         obj = c.newInstance();
1478                     } catch (InstantiationException ex) {
1479                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1480 
1481                     } catch (IllegalAccessException ex) {
1482                         log.log(Level.ERROR, SLACommon.getBundleString("ErrorSLAPluginRuleNCDF") + x.getClassName(), ex);
1483                     }
1484                     SLARuleInterface cast = null;
1485                     try {
1486                         cast = (SLARuleInterface) obj;
1487                     } catch (ClassCastException ex) {
1488                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleTypeCast"), x.getClassName(), SLARuleInterface.class.getCanonicalName()), ex);
1489                     }
1490                     try {
1491                         AtomicReference<String> f = new AtomicReference<String>();
1492                         if (cast != null && cast.CheckTransactionalRule(req.getBrokerURI(), req.getData(), x.getParameterNameValue(), f)) {
1493                             alertType.set(cast.GetType());
1494                             outFaultMsg.set(f.get() + " " + outFaultMsg.get());
1495                             return true;
1496                         }
1497                     } catch (Exception ex) {
1498                         log.log(Level.ERROR, String.format(SLACommon.getBundleString("ErrorSLAPluginRuleUnexpectedError"), x.getClassName()), ex);
1499                     }
1500                 }
1501             }
1502         }
1503         return false;
1504     }
1505 
1506     /**
1507      * processes broker rules for when a queue or topic doesn't exist and
1508      * QueueOrTopicDoesNotExist, BrokerQueueSizeGreaterThan Map contains the key
1509      * (topic name), value, size of the queue
1510      *
1511      * @param req
1512      * @param pooled
1513      */
1514     public static void ProcessStatisticalSLARules(AddStatisticalDataRequestMsg req, boolean pooled) {
1515         ServicePolicy pol = null;
1516         SetupBundle();
1517         if (pooled) {
1518             pol = LoadPolicyPooled(req.getBrokerURI());
1519         } else {
1520             pol = LoadPolicyNotPooled(req.getBrokerURI());
1521         }
1522         if (pol == null) {
1523             return;
1524         }
1525         if (pol.getServiceLevelAggrements() == null) {
1526             return;
1527         }
1528 
1529         if (pol.getServiceLevelAggrements().getSLA() == null) {
1530             return;
1531         }
1532         if (pol.getServiceLevelAggrements().getSLA().isEmpty()) {
1533             return;
1534         }
1535         for (int i = 0; i < pol.getServiceLevelAggrements().getSLA().size(); i++) {
1536             AtomicReference<String> ref = new AtomicReference<String>();
1537             AtomicReference<AlertType> alertType = new AtomicReference<AlertType>();
1538             if (processStatisticalSLARulesRecursive(req, pooled, pol.getServiceLevelAggrements().getSLA().get(i).getRule(), ref, alertType)) {
1539                 String id = UUID.randomUUID().toString();
1540                 RecordSLAFault(new AtomicReference<String>(ref.get()), req.getBrokerURI(), null, System.currentTimeMillis(), id, pooled);
1541                 ProcessAlerts(ref.get(), Utility.encodeHTML(ref.get()), req.getBrokerURI(), null, System.currentTimeMillis(), id, pooled, false,
1542                         pol.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction(), pol.getServiceLevelAggrements().getSLA().get(i).getGuid(), pol,
1543                         alertType.get());
1544             }
1545         }
1546 
1547     }
1548 
1549     /**
1550      * removes the trailing comma
1551      *
1552      * @param msg
1553      * @return
1554      */
1555     private static String trimFaultMsg(String msg) {
1556         if (Utility.stringIsNullOrEmpty(msg)) {
1557             return "";
1558         }
1559         String s = msg.trim();
1560         if (s.endsWith(",")) {
1561             s = s.substring(0, s.length() - 1);
1562         }
1563         return s;
1564     }
1565 
1566     /**
1567      * Handles sending of alert messages. Items are added a queue and processed
1568      * either via Jboss's worker pool or via a singleton SLA processor thread.
1569      *
1570      * @param faultMsg human readable fault message
1571      * @param htmlEncodedFaultMessage html formatted alert message
1572      * @param modifiedurl the policy url
1573      * @param relatedMessageId a related record that caused this action to be
1574      * trigger, may be null
1575      * @param currentTimeMillis the time it was trigger
1576      * @param incidentid a unique identifier for the SLA, it will be recorded
1577      * using this ID
1578      * @param pooled are we in jboss and can we use jndi for database lookups?
1579      * @param sendtoAdminsOnly
1580      * @param slaActionBaseType the action to trigger
1581      * @param SLAID the UUID of the SLA Rule/Action set
1582      * @param t service policy
1583      * @param at alert type
1584      */
1585     public static void ProcessAlerts(String faultMsg, String htmlEncodedFaultMessage, String modifiedurl, String relatedMessageId, long currentTimeMillis,
1586             String incidentid, boolean pooled, boolean sendtoAdminsOnly, List<SLAAction> slaActionBaseType,
1587             String SLAID, ServicePolicy t, AlertType at) {
1588         SetupBundle();
1589         if (slaActionBaseType == null || slaActionBaseType.isEmpty()) {
1590             log.log(Level.WARN, bundle.getString("ErrorNullSLAAlert"));
1591             return;
1592         }
1593 
1594         SLAProcessorSingleton instance = SLAProcessorSingleton.getInstance();
1595         org.oasis_open.docs.wsdm.muws2_2.ObjectFactory f = new org.oasis_open.docs.wsdm.muws2_2.ObjectFactory();
1596         for (int i = 0; i < slaActionBaseType.size(); i++) {
1597             AlertContainer alert = null;
1598             switch (at) {
1599                 case Performance:
1600                     alert = new AlertContainer(trimFaultMsg(faultMsg), htmlEncodedFaultMessage, modifiedurl, relatedMessageId, currentTimeMillis, incidentid, pooled, sendtoAdminsOnly, slaActionBaseType.get(i), SLAID, t, f.createPerformanceReport());
1601                     break;
1602                 case Status:
1603                     alert = new AlertContainer(trimFaultMsg(faultMsg), htmlEncodedFaultMessage, modifiedurl, relatedMessageId, currentTimeMillis, incidentid, pooled, sendtoAdminsOnly, slaActionBaseType.get(i), SLAID, t, f.createAvailabilitySituation());
1604             }
1605 
1606             SLAProcessorSingleton.EnqueueAlert(alert);
1607         }
1608 
1609     }
1610 
1611     /**
1612      * Checks for the existence of a policy
1613      *
1614      * @param uri
1615      * @param pooled
1616      * @return
1617      */
1618     public static boolean PolicyExists(String uri, boolean pooled) {
1619         boolean found = false;
1620         Connection con = null;
1621         if (pooled) {
1622             con = Utility.getConfigurationDBConnection();
1623         } else {
1624             con = Utility.getConfigurationDB_NONPOOLED_Connection();
1625         }
1626         PreparedStatement cmd=null;
1627         ResultSet rs=null;
1628         try {
1629             cmd = con.prepareStatement("select count(*) from servicepolicies where uri=?;");
1630             cmd.setString(1, uri);
1631             rs = cmd.executeQuery();
1632             if (rs.next()) {
1633                 int count = rs.getInt(1);
1634                 if (count == 1) {
1635                     found = true;
1636                 }
1637             }
1638             
1639         } catch (Exception ex) {
1640             log.log(Level.WARN, bundle.getString("ErrorCheckPolicyExists"), ex);
1641         } finally {
1642             DBUtils.safeClose(rs);
1643             DBUtils.safeClose(cmd);
1644             DBUtils.safeClose(con);
1645         }
1646         return found;
1647     }
1648 
1649     /**
1650      * Returns true if the proposed SLA configuration is valid
1651      *
1652      * @param outmsg
1653      * @param pol
1654      * @return
1655      */
1656     public static boolean ValidateSLAs(AtomicReference<String> outmsg, ServicePolicy pol) {
1657         if (outmsg == null) {
1658             outmsg = new AtomicReference<String>();
1659         }
1660         if (pol.getServiceLevelAggrements() == null
1661                 || pol.getServiceLevelAggrements().getSLA().isEmpty()) {
1662             return true;
1663         }
1664         boolean valid = true;
1665         for (int i = 0; i < pol.getServiceLevelAggrements().getSLA().size(); i++) {
1666             if (Utility.stringIsNullOrEmpty(pol.getServiceLevelAggrements().getSLA().get(i).getGuid())) {
1667                 outmsg.set("Each SLA must have a unique identifier, try UUID.randomUUID().toString() or Guid.newGuid().toString(). " + outmsg.get());
1668                 valid = false;
1669             }
1670             if (pol.getServiceLevelAggrements().getSLA().get(i).getRule() == null) {
1671                 outmsg.set("Each SLA must have a Rule. " + outmsg.get());
1672                 valid = false;
1673             } else {
1674                 //validate rules
1675                 //AtomicReference<String> ref = new AtomicReference<String>();
1676                 valid = valid && (validateRulesRecursive(pol, outmsg, pol.getServiceLevelAggrements().getSLA().get(i).getRule()));
1677             }
1678             if (pol.getServiceLevelAggrements().getSLA().get(i).getAction() == null
1679                     || pol.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction().isEmpty()) {
1680                 outmsg.set("Each SLA must have at least one Action. " + outmsg.get());
1681                 valid = false;
1682             } else {
1683                 valid = valid && validateActions(pol, outmsg, pol.getServiceLevelAggrements().getSLA().get(i).getAction().getSLAAction());
1684                 //validate Actions
1685             }
1686         }
1687         return valid;
1688     }
1689 
1690     /**
1691      * Returns true if the proposed SLA configuration is valid
1692      */
1693     private static boolean validateRulesRecursive(ServicePolicy pol, AtomicReference<String> ref, RuleBaseType rule) {
1694         if (rule instanceof SLARuleGeneric) {
1695 
1696             SLARuleGeneric r = (SLARuleGeneric) rule;
1697             if (Utility.stringIsNullOrEmpty(r.getClassName())) {
1698                 ref.set(ref.get() + " Rule class name is not defined");
1699                 return false;
1700             }
1701             try {
1702                 Class<SLARuleInterface> forName = (Class<SLARuleInterface>) Class.forName(r.getClassName());
1703                 SLARuleInterface newInstance = forName.newInstance();
1704                 if (!newInstance.GetAppliesTo().contains(pol.getPolicyType())) {
1705                     ref.set(ref.get() + " The specified Rule, class name=" + r.getClassName() + " does not apply to the policy type of " + pol.getPolicyType().value());
1706                     return false;
1707                 }
1708                 return newInstance.ValidateConfiguration(r.getParameterNameValue(), ref, pol);
1709             } catch (Exception ex) {
1710                 ref.set(ref.get() + " The specified Rule, class name=" + r.getClassName() + " could not be loaded, " + ex.getMessage());
1711                 return false;
1712             }
1713 
1714         } else if (rule instanceof AndOrNot) {
1715             AndOrNot aon = (AndOrNot) rule;
1716             switch (aon.getFlag()) {
1717                 case AND:
1718                     return validateRulesRecursive(pol, ref, aon.getLHS()) && validateRulesRecursive(pol, ref, aon.getRHS());
1719                 case NOT:
1720                     return !validateRulesRecursive(pol, ref, aon.getLHS());
1721                 case OR:
1722                     return validateRulesRecursive(pol, ref, aon.getLHS()) || validateRulesRecursive(pol, ref, aon.getRHS());
1723             }
1724         } else {
1725             ref.set(ref.get() + " Unknown rule type");
1726         }
1727         return false;
1728     }
1729 
1730     private static List<ServicePolicy> loadServicePoliciesWithFederation(Connection con) {
1731         SetupBundle();
1732          PreparedStatement comm = null;
1733          ResultSet results = null;
1734         try {
1735             List<ServicePolicy> l = new ArrayList<ServicePolicy>();
1736            
1737             comm = con.prepareStatement("Select * from ServicePolicies where hasfederation=true;");
1738             /////////////////////////////////////////////
1739             //get the policy for this service
1740             /////////////////////////////////////////////
1741 
1742             Unmarshaller um = Utility.getSerializationContext().createUnmarshaller();
1743             results = comm.executeQuery();
1744 
1745             while (results.next()) {
1746                 ServicePolicy ret = null;
1747 
1748                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
1749 
1750                 byte[] s = results.getBytes("xmlpolicy");
1751 
1752                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1753                 XMLInputFactory xf = XMLInputFactory.newInstance();
1754                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1755                 switch (pt) {
1756                     case MACHINE:
1757                         JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
1758                         if (foo == null || foo.getValue() == null) {
1759                             log.log(Level.WARN, bundle.getString("MachinePolicyNull"));
1760                         } else {
1761                             ret = foo.getValue();
1762                         }
1763                         break;
1764                     case PROCESS:
1765                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
1766                         if (foo3 == null || foo3.getValue() == null) {
1767                             log.log(Level.WARN, bundle.getString("ProcessPolicyNull"));
1768                         } else {
1769                             ret = foo3.getValue();
1770                         }
1771                         break;
1772                     case STATISTICAL:
1773                         JAXBElement<StatisticalServicePolicy> foo1 = (JAXBElement<StatisticalServicePolicy>) um.unmarshal(r, StatisticalServicePolicy.class);
1774                         if (foo1 == null || foo1.getValue() == null) {
1775                             log.log(Level.WARN, bundle.getString("BrokerPolicyNull"));
1776                         } else {
1777                             ret = foo1.getValue();
1778                         }
1779                         break;
1780                     case STATUS:
1781                         JAXBElement<StatusServicePolicy> foo2 = (JAXBElement<StatusServicePolicy>) um.unmarshal(r, StatusServicePolicy.class);
1782                         if (foo2 == null || foo2.getValue() == null) {
1783                             log.log(Level.WARN, bundle.getString("StatusPolicyNull"));
1784                         } else {
1785                             ret = foo2.getValue();
1786                         }
1787                         break;
1788                     case TRANSACTIONAL:
1789                         JAXBElement<TransactionalWebServicePolicy> foo4 = (JAXBElement<TransactionalWebServicePolicy>) um.unmarshal(r, TransactionalWebServicePolicy.class);
1790                         if (foo4 == null || foo4.getValue() == null) {
1791                             log.log(Level.WARN, bundle.getString("WSPolicyNull"));
1792                         } else {
1793                             ret = foo4.getValue();
1794                         }
1795                         break;
1796                 }
1797 
1798                 r.close();
1799                 bss.close();
1800 
1801                 l.add(ret);
1802 
1803             }
1804            
1805             return l;
1806         } catch (Exception ex) {
1807             log.log(Level.WARN, bundle.getString("ErrorLoadingPolicyForSLA"), ex);
1808         } finally {
1809             DBUtils.safeClose(results);
1810             DBUtils.safeClose(comm);
1811         }
1812         return new ArrayList<ServicePolicy>();
1813     }
1814 
1815     /**
1816      * used by Federation Scheduler for publication
1817      *
1818      * @return either an empty list, or a list containing service policies that
1819      * contain SLA's
1820      */
1821     public static List<ServicePolicy> LoadFederationServicePoliciesPooled() {
1822 
1823         SetupBundle();
1824         Connection con = Utility.getConfigurationDBConnection();
1825         List<ServicePolicy> r = null;
1826         try {
1827             r = loadServicePoliciesWithFederation(con);
1828         } catch (Exception ex) {
1829             log.log(Level.ERROR, bundle.getString("ErrorLoadingPolicy"), ex);
1830         } finally {
1831             DBUtils.safeClose(con);
1832         }
1833         if (r == null) {
1834             r = new ArrayList<ServicePolicy>();
1835         }
1836         return r;
1837 
1838     }
1839 
1840     /**
1841      * return true if valid
1842      *
1843      * @param pol
1844      * @param outmsg
1845      * @param action
1846      * @return
1847      */
1848     private static boolean validateActions(ServicePolicy pol, AtomicReference<String> ref, List<SLAAction> action) {
1849         for (int i = 0; i < action.size(); i++) {
1850             if (Utility.stringIsNullOrEmpty(action.get(i).getImplementingClassName())) {
1851                 ref.set(ref.get() + " action class name is not defined");
1852                 return false;
1853             }
1854             
1855             Connection con = Utility.getConfigurationDBConnection();
1856             PreparedStatement cmd=null;
1857             ResultSet rs=null;
1858             try{
1859                 //validate that the plugin is registered
1860                 cmd=con.prepareStatement("select * from plugins where classname = ? AND appliesto = ?");
1861                 cmd.setString(1, action.get(i).getImplementingClassName());
1862                 cmd.setString(2, "SLA_ACTION");
1863                 rs = cmd.executeQuery();
1864                 if (rs.next()){
1865                     //we are ok
1866                 } else {
1867                     ref.set(ref.get() + " The specified action, class name=" + action.get(i).getImplementingClassName() + " is not registered");
1868                     return false;
1869                 }
1870             }catch (Exception ex){
1871                 log.log(Level.WARN, null, ex);
1872                 
1873             } finally{
1874                 DBUtils.safeClose(rs);
1875                 DBUtils.safeClose(cmd);
1876                 DBUtils.safeClose(con);
1877             }
1878             try {
1879                 Class<SLAActionInterface> forName = (Class<SLAActionInterface>) Class.forName(action.get(i).getImplementingClassName());
1880                 SLAActionInterface newInstance = forName.newInstance();
1881                 if (!newInstance.GetAppliesTo().contains(pol.getPolicyType())) {
1882                     ref.set(ref.get() + " The specified action, class name=" + action.get(i).getImplementingClassName() + " does not apply to the policy type of " + pol.getPolicyType().value());
1883                     return false;
1884                 }
1885                 return newInstance.ValidateConfiguration(action.get(i).getParameterNameValue(), ref);
1886             } catch (Exception ex) {
1887                 ref.set(ref.get() + " The specified action, class name=" + action.get(i).getImplementingClassName() + " could not be loaded, " + ex.getMessage());
1888                 return false;
1889             }
1890 
1891         }
1892         return true;
1893     }
1894 
1895     /**
1896      * Handles each alert and calls the corresponding function to process the
1897      * alert
1898      *
1899      * @param alert
1900      */
1901     protected void DoAlerts(AlertContainer alert) {
1902         log.debug("Processing alert for " + alert.getModifiedurl() + " msg " + alert.getFaultMsg() + " class " + alert.getSlaActionBaseType().getImplementingClassName());
1903         Class c = null;
1904         try {
1905             c = Thread.currentThread().getContextClassLoader().loadClass(alert.getSlaActionBaseType().getImplementingClassName());
1906         } catch (ClassNotFoundException ex) {
1907             //ignore 
1908         }
1909         if (c == null) {
1910             try {
1911                 c = this.getClass().getClassLoader().loadClass(alert.getSlaActionBaseType().getImplementingClassName());
1912             } catch (ClassNotFoundException ex) {
1913                 //ignore 
1914             }
1915         }
1916         if (c == null) {
1917             try {
1918                 c = Class.forName(alert.getSlaActionBaseType().getImplementingClassName());
1919             } catch (ClassNotFoundException ex) {
1920                 //ignore 
1921             }
1922         }
1923         if (c == null) {
1924             log.error("Error to Load class for SLA Alert!!!" + alert.getSlaActionBaseType().getImplementingClassName());
1925         } else {
1926             try {
1927                 Object j = c.newInstance();
1928                 SLAActionInterface item = (SLAActionInterface) j;
1929                 item.ProcessAction(alert, alert.getSlaActionBaseType().getParameterNameValue());
1930             } catch (Exception ex) {
1931                 log.error("Error unable to process SLA Alert!!!", ex);
1932             }
1933         }
1934 
1935     }
1936 
1937     private static DriveInformation locateDriveRecord(List<DriveInformation> driveInformation, String partition) {
1938         if (driveInformation == null) {
1939             return null;
1940         }
1941         for (int i = 0; i < driveInformation.size(); i++) {
1942             if (partition.equalsIgnoreCase(driveInformation.get(i).getPartition())) {
1943                 return driveInformation.get(i);
1944             }
1945         }
1946         return null;
1947     }
1948 
1949     public static SecurityWrapper GetClassLevel(boolean pooled) {
1950         Connection con = null;
1951         SecurityWrapper c = new SecurityWrapper();
1952         if (pooled) {
1953             con = Utility.getConfigurationDBConnection();
1954         } else {
1955             con = Utility.getConfigurationDB_NONPOOLED_Connection();
1956         }
1957         PreparedStatement cmd =null;
1958         ResultSet rs = null;
1959         try {
1960              cmd = con.prepareStatement("select classification,caveat from globalpolicies;");
1961              rs = cmd.executeQuery();
1962             if (rs.next()) {
1963                 c.setCaveats(rs.getString("caveat"));
1964                 c.setClassification(ClassificationType.fromValue(rs.getString("classification")));
1965             }
1966             
1967         } catch (Exception ex) {
1968             log.log(Level.WARN,null, ex);
1969         } finally {
1970             DBUtils.safeClose(rs);
1971             DBUtils.safeClose(cmd);
1972             DBUtils.safeClose(con);
1973         }
1974         return c;
1975     }
1976 
1977     /**
1978      * Gets the current status of an item.
1979      *
1980      * @param pooled
1981      * @param policyurl
1982      * @param out_status NULL if status is unknown, true = runnning
1983      * @param out_timestamp NULL if status is unknown, else time since epoch
1984      * @param out_message
1985      * @since 6.2
1986      */
1987     public static void GetCurrentStatus(boolean pooled, String policyurl, AtomicReference< Boolean> out_status, AtomicReference< Long> out_timestamp, AtomicReference< String> out_message) {
1988         java.sql.Connection con = null;
1989         SetupBundle();
1990          PreparedStatement cmd =null;
1991         ResultSet rs = null;
1992         try {
1993             if (!pooled) {
1994                 con = Utility.getConfigurationDB_NONPOOLED_Connection();
1995 
1996             } else {
1997                 con = Utility.getConfigurationDBConnection();
1998             }
1999 
2000             cmd = con.prepareStatement("select * from status  where uri=?;");
2001             cmd.setString(1, policyurl);
2002             rs = cmd.executeQuery();
2003             if (rs.next()) {
2004                 out_timestamp.set(rs.getLong("utcdatetime"));
2005                 out_message.set(rs.getString("message"));
2006                 out_status.set(rs.getBoolean("status"));
2007             } else {
2008                 out_timestamp.set(null);
2009                 out_message.set(null);
2010                 out_status.set(null);
2011             }
2012            
2013         } catch (Exception ex) {
2014             log.log(Level.WARN, String.format(bundle.getString("ErrorUnableToUpdateStatus"), policyurl), ex);
2015         } finally {
2016             DBUtils.safeClose(rs);
2017             DBUtils.safeClose(cmd);
2018             DBUtils.safeClose(con);
2019         }
2020     }
2021 }