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.services.pcs.impl;
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.StringWriter;
24  import java.sql.*;
25  import java.util.*;
26  import java.util.concurrent.atomic.AtomicReference;
27  import javax.annotation.Resource;
28  import javax.jws.WebMethod;
29  import javax.jws.WebParam;
30  import javax.jws.WebResult;
31  import javax.jws.WebService;
32  import javax.jws.soap.SOAPBinding;
33  import javax.xml.bind.*;
34  import javax.xml.datatype.DatatypeConfigurationException;
35  import javax.xml.datatype.DatatypeFactory;
36  import java.util.Calendar;
37  import java.util.concurrent.BlockingQueue;
38  import java.util.concurrent.LinkedBlockingQueue;
39  import java.util.concurrent.ThreadPoolExecutor;
40  import java.util.concurrent.TimeUnit;
41  import javax.xml.stream.XMLInputFactory;
42  import javax.xml.stream.XMLStreamReader;
43  import javax.xml.ws.RequestWrapper;
44  import javax.xml.ws.ResponseWrapper;
45  import javax.xml.ws.WebServiceContext;
46  import org.apache.log4j.Level;
47  import org.miloss.fgsms.common.Logger;
48  ;
49  import org.miloss.fgsms.common.AuditLogger;
50  import org.miloss.fgsms.common.Constants;
51  import org.miloss.fgsms.common.DBSettingsLoader;
52  import org.miloss.fgsms.common.DBUtils;
53  import org.miloss.fgsms.common.IpAddressUtility;
54  import org.miloss.fgsms.common.UserIdentityUtil;
55  import org.miloss.fgsms.common.Utility;
56  import org.miloss.fgsms.plugins.PluginCommon;
57  import org.miloss.fgsms.plugins.federation.FederationInterface;
58  import org.miloss.fgsms.plugins.sla.SLAActionInterface;
59  import org.miloss.fgsms.plugins.sla.SLARuleInterface;
60  import org.miloss.fgsms.services.interfaces.common.*;
61  import org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableFaultCodes;
62  import org.miloss.fgsms.services.interfaces.policyconfiguration.*;
63  import org.miloss.fgsms.sla.AuxHelper;
64  import org.miloss.fgsms.sla.SLACommon;
65  import org.miloss.fgsms.sla.actions.EmailAlerter;
66  import org.miloss.fgsms.sla.actions.SLAActionRestart;
67  import us.gov.ic.ism.v2.ClassificationType;
68  
69  /**
70   * fgsms's Policy Configuration Service This web service provides one of the
71   * core functions of fgsms, managing service policies, access control and
72   * general configuration elements of the agents and fgsms itself. All methods
73   * require a classification level and process access control rules accept for
74   * GetGlobalPolicy, which actually contains little information other than the
75   * current configuration level.
76   *
77   * @author AO
78   */
79  
80  
81  @WebService(serviceName = "PolicyConfigurationService",
82          name = "PCS",
83          targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration" //wsdlLocation = "classpath:/PCS8.wsdl"
84  )
85  @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED, use = SOAPBinding.Use.LITERAL)
86  public class PCS4jBean implements PCS {
87  
88      private final static String name = "fgsms.PolicyConfigurationService";
89      protected final static Logger log = Logger.getLogger(name);
90      private static SecurityWrapper currentLevel;
91      private static Calendar started = null;
92      private static DatatypeFactory df = null;
93      static BlockingQueue<Runnable> alertQueue = new LinkedBlockingQueue<Runnable>();
94      private static ThreadPoolExecutor alertingThreadPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, alertQueue);
95  
96      private synchronized void init() throws DatatypeConfigurationException {
97  
98          if (df == null) {
99              df = DatatypeFactory.newInstance();
100         }
101         currentLevel = getCurrentOperatingClassificationLevel();
102         if (started == null) {
103             GregorianCalendar gcal = new GregorianCalendar();
104             gcal.setTimeInMillis(System.currentTimeMillis());
105             started = (gcal);
106         }
107         try {
108             jc = Utility.getSerializationContext();
109         } catch (Exception ex) {
110             log.log(Level.FATAL, "Couldn't initial the JAXB serialization context. Check for the presense of xercesImpl.jar");
111             throw new IllegalAccessError("can't create the JAXB Context, therefore I can't save or read from the database");
112         }
113     }
114 
115     public PCS4jBean() throws DatatypeConfigurationException {
116         init();
117     }
118 
119     /**
120      * constructor used for unit testing, do not remove
121      *
122      * @param ct
123      */
124     protected PCS4jBean(WebServiceContext ct) throws DatatypeConfigurationException {
125         this();
126         ctx = ct;
127     }
128     @Resource
129     private WebServiceContext ctx;
130 
131     /**
132      *
133      *
134      * GetServicePolicy returns a policy for a specific service
135      *
136      * Each policy has a type (Service Policy is abstract) ServicePolicy itself
137      * has a wide range of settings that are common to all service policy types.
138      * Concrete policies extend from ServicePolicy
139      *
140      * Default Data retension (dataTTL) = 30 days,set by the General Settings
141      * parameters All other defaults also come from General Settings collection
142      *
143      * Required Permission: <ul> <li> If the policy exists, Read for non-agent
144      * credentials, </il> <li> If the policy exists, agent credentials can view
145      * any policy</il> <li> If the policy doesn't exists, non-agent credentials
146      * will return a null policy</il> <li> If the policy doesn't exists, global
147      * administrator credentials will return a new policy. In this case, input
148      * parameters of domain, machine name, and policy type are required</il>
149      * <li> If the policy does not exist, agent credentials, then a new policy
150      * will be created with the default parameters. In this case, input
151      * parameters of domain, machine name, and policy type are required</il>
152      * </ul>
153      *
154      *
155      *
156      *
157      *
158      *
159      *
160      * @param request
161      * @return returns
162      * org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicyResponseMsg
163      * @throws ServiceUnavailableException
164      * @throws AccessDeniedException
165      */
166     @WebMethod(operationName = "GetServicePolicy", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetServicePolicy")
167     @WebResult(name = "GetServicePolicyResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
168     @RequestWrapper(localName = "GetServicePolicy", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetServicePolicy")
169     @ResponseWrapper(localName = "GetServicePolicyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetServicePolicyResponse")
170     public ServicePolicyResponseMsg getServicePolicy(
171             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") ServicePolicyRequestMsg request)
172             throws AccessDeniedException, ServiceUnavailableException {
173         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
174 
175         if (request == null) {
176             throw new IllegalArgumentException("Request is null");
177         }
178         if (Utility.stringIsNullOrEmpty(request.getURI())) {
179             throw new IllegalArgumentException("URI is null");
180         }
181         if ((request.getPolicytype() == null)) {
182             //   throw new IllegalArgumentException("As of RC6, agents now need to specify the Policy Type?");
183         }
184         Utility.validateClassification(request.getClassification());
185 
186         AuditLogger.logItem(this.getClass().getCanonicalName(), "getServicePolicy", currentUser, request.getURI(), (request.getClassification()), ctx.getMessageContext());
187 
188         ServicePolicyResponseMsg response = new ServicePolicyResponseMsg();
189         response.setClassification(currentLevel);
190 
191         //http/https only service url contains IP address, try to resolve it here to a hostname, if i can't resolve it, leave it as is
192         //  IpAddressUtility.modifyURL(request.getURI(), false);
193         response.setPolicy(getPolicyFromDB(IpAddressUtility.modifyURL(request.getURI(), true), (request.getClassification()), currentUser, request.getPolicytype(), request.getMachine(), request.getDomain(), true));
194         if (response.getPolicy() == null && (request.getPolicytype() == null || Utility.stringIsNullOrEmpty(request.getMachine()))) {
195             throw new IllegalArgumentException("When requesting a policy that doesn't exist already, you must specify the hostname of the machine it's running on and a policy type. If the hostname is not known, use 'unspecified'");
196         }
197 
198         return response;
199     }
200 
201     private SecurityWrapper getCurrentOperatingClassificationLevel() {
202         try {
203             SecurityWrapper t = getGlobalPolicyFromDB().getClassification();
204             log.log(Level.INFO, "PCS, current security classification is " + Utility.ICMClassificationToString(t.getClassification()) + " " + t.getCaveats());
205             return t;
206         } catch (Exception ex) {
207             log.log(Level.ERROR, "Unable to determine current classification level. Is the database available?", ex);
208         }
209         throw new IllegalAccessError();
210     }
211 
212     /**
213      *
214      *
215      * GetServicePolicy returns a list of service policies for all services that
216      * are
217      *
218      * configured to data publication to any federation target
219      *
220      *
221      *
222      * Note: Only information pretaining to uddi publication is returned,
223      *
224      * other data such as SLA or UserIdentification policies are not returned.
225      *
226      *
227      *
228      *
229      *
230      *
231      *
232      * @param request
233      * @return returns
234      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetUDDIDataPublishServicePoliciesResponseMsg
235      * @throws AccessDeniedException
236      * @throws ServiceUnavailableException
237      */
238     @WebMethod(operationName = "GetUDDIDataPublishServicePolicies", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetUDDIDataPublishServicePolicies")
239     @WebResult(name = "GetUDDIDataPublishServicePoliciesResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
240     @RequestWrapper(localName = "GetUDDIDataPublishServicePolicies", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetUDDIDataPublishServicePolicies")
241     @ResponseWrapper(localName = "GetUDDIDataPublishServicePoliciesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetUDDIDataPublishServicePoliciesResponse")
242     public GetUDDIDataPublishServicePoliciesResponseMsg getUDDIDataPublishServicePolicies(
243             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetUDDIDataPublishServicePoliciesRequestMsg request)
244             throws AccessDeniedException, ServiceUnavailableException {
245         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
246         if (request == null) {
247             throw new IllegalArgumentException("request is null");
248         }
249         Utility.validateClassification(request.getClassification());
250 
251         AuditLogger.logItem(this.getClass().getCanonicalName(), "getUDDIDataPublishServicePolicies", currentUser, "", (request.getClassification()), ctx.getMessageContext());
252         UserIdentityUtil.assertAgentRole(currentUser, "getUDDIDataPublishServicePolicies", (request.getClassification()), ctx);
253         //log.log(Level.INFO, "GetUDDIDataPublishServicePolicies " + currentUser);
254 
255         GetUDDIDataPublishServicePoliciesResponseMsg response = new GetUDDIDataPublishServicePoliciesResponseMsg();
256         ArrayOfServicePolicy list = getUDDIPoliciesFromDB(request.getClassification());
257         if (list != null) {
258             log.log(Level.INFO, "GetUDDIDataPublishServicePolicies returned " + list.getServicePolicy().size() + " policies");
259         } else {
260             log.log(Level.INFO, "GetUDDIDataPublishServicePolicies returned a null list!");
261         }
262         //good
263         response.setPolicies((list));
264         response.setClassification(currentLevel);
265         return response;
266     }
267 
268     /**
269      *
270      *
271      * Saves a service policy to the configuration database
272      *
273      * Any existing policy for this service is deleted and replaced with the
274      * parameter.
275      *
276      * User Permissions are not affected
277      *
278      * Required Permission: write
279      *
280      * Special Note: when setting the policy on an item contains SLAAction
281      * Restart or RunScript, Administrative permissions are required
282      *
283      *
284      *
285      *
286      *
287      *
288      *
289      * @param request
290      * @return returns
291      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePolicyResponseMsg
292      * @throws ServiceUnavailableException
293      * @throws AccessDeniedException
294      */
295     @WebMethod(operationName = "SetServicePolicy", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetServicePolicy")
296     @WebResult(name = "SetServicePolicyResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
297     @RequestWrapper(localName = "SetServicePolicy", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePolicy")
298     @ResponseWrapper(localName = "SetServicePolicyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePolicyResponse")
299     public SetServicePolicyResponseMsg setServicePolicy(
300             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetServicePolicyRequestMsg request)
301             throws AccessDeniedException, ServiceUnavailableException {
302         long now = System.currentTimeMillis();
303         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
304 
305         if (request == null) {
306             throw new IllegalArgumentException("request is null");
307         }
308         if (request.getPolicy() == null) {
309             throw new IllegalArgumentException("policy is null");
310         }
311         if (Utility.stringIsNullOrEmpty(request.getURL())) {
312             throw new IllegalArgumentException("URL is null");
313         }
314         if (Utility.stringIsNullOrEmpty(request.getPolicy().getURL())) {
315             throw new IllegalArgumentException("Policy URL is null");
316         }
317         if (!request.getURL().equals(request.getPolicy().getURL())) {
318             throw new IllegalArgumentException("URL mismatch!");
319         }
320 
321         log.trace("setServicePolicy trace 1 - " + (System.currentTimeMillis() - now));
322         Utility.validateClassification(request.getClassification());
323         log.trace("setServicePolicy trace 2 - " + (System.currentTimeMillis() - now));
324         AuditLogger.logItem(this.getClass().getCanonicalName(), "setServicePolicy", currentUser, request.getURL(), (request.getClassification()), ctx.getMessageContext());
325         log.trace("setServicePolicy trace 3 - " + (System.currentTimeMillis() - now));
326         UserIdentityUtil.assertWriteAccess(request.getURL(), currentUser, "setServicePolicy", (request.getClassification()), ctx);
327         log.trace("setServicePolicy trace 4 - " + (System.currentTimeMillis() - now));
328         if (request.getPolicy().getPolicyType() == null) {
329             throw new IllegalArgumentException("A policy type must be specified");
330         }
331 
332         validateSLAs(request.getPolicy());
333         log.trace("setServicePolicy trace 5 - " + (System.currentTimeMillis() - now));
334         validatePolicyByType(request.getPolicy());
335         log.trace("setServicePolicy trace 6 - " + (System.currentTimeMillis() - now));
336         ValidationTools.validateFederationPolicies(request.getPolicy().getFederationPolicyCollection());
337         log.trace("setServicePolicy trace 7 - " + (System.currentTimeMillis() - now));
338         encryptIfNeeded(request.getPolicy().getFederationPolicyCollection());
339         encryptIfNeeded(request.getPolicy());
340         writePolicytoDB(request.getPolicy(), request.getPolicy().getURL(), currentUser);
341 
342         SetServicePolicyResponseMsg response = new SetServicePolicyResponseMsg();
343         response.setStatus(true);
344         response.setClassification(getCurrentOperatingClassificationLevel());
345         log.trace("setServicePolicy trace 8 - " + (System.currentTimeMillis() - now));
346         return response;
347     }
348 
349     /**
350      *
351      *
352      * Sets the global policy values
353      *
354      * Required permission: global admin role
355      *
356      *
357      *
358      *
359      *
360      *
361      *
362      * @param request
363      * @return returns
364      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetGlobalPolicyResponseMsg
365      * @throws AccessDeniedException
366      * @throws ServiceUnavailableException
367      */
368     @WebMethod(operationName = "SetGlobalPolicy", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetGlobalPolicy")
369     @WebResult(name = "SetGlobalPolicyResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
370     @RequestWrapper(localName = "SetGlobalPolicy", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetGlobalPolicy")
371     @ResponseWrapper(localName = "SetGlobalPolicyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetGlobalPolicyResponse")
372     public SetGlobalPolicyResponseMsg setGlobalPolicy(
373             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetGlobalPolicyRequestMsg request)
374             throws AccessDeniedException, ServiceUnavailableException {
375         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
376 
377         if (request == null || request.getPolicy() == null) {
378             throw new IllegalArgumentException("requested policy is null");
379         }
380         Utility.validateClassification(request.getClassification());
381         AuditLogger.logItem(this.getClass().getCanonicalName(), "setGlobalPolicy", currentUser, "", (request.getClassification()), ctx.getMessageContext());
382         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "setGlobalPolicy", (request.getClassification()), ctx);
383         if (request.getPolicy().getPolicyRefreshRate() == null || request.getPolicy().getRecordedMessageCap() < 1) {
384             throw new IllegalArgumentException("the policy is invalid");
385         }
386 
387         Connection con = null;
388         PreparedStatement comm = null;
389         try {
390 
391             con = Utility.getConfigurationDBConnection();
392             GetGlobalPolicyResponseMsg currentSecPol = getGlobalPolicyFromDB();
393             comm = con.prepareStatement("BEGIN WORK;LOCK TABLE GlobalPolicies IN ACCESS EXCLUSIVE MODE;"
394                     + "DELETE FROM GlobalPolicies; INSERT INTO GlobalPolicies (PolicyRefreshRate, RecordedMessageCap, agentsenable, classification, caveat) "
395                     + "     VALUES (?, ?,?,?,?); COMMIT WORK;");
396 
397             if (request.getPolicy().getPolicyRefreshRate() == null) {
398                 comm.setLong(1, 3 * 60 * 1000); //3 minutes
399             } else {
400                 comm.setLong(1, Utility.durationToTimeInMS(request.getPolicy().getPolicyRefreshRate()));
401             }
402             /*
403              * if (request.getPolicy().getUDDIPublishRate() == null) {
404              * comm.setLong(2, 60 * 60 * 1000); //60 minutes } else {
405              * comm.setLong(2,
406              * Utility.durationToTimeInMS(request.getPolicy().getUDDIPublishRate()));
407              * }
408              */
409             comm.setInt(2, request.getPolicy().getRecordedMessageCap());
410             comm.setBoolean(3, request.getPolicy().isAgentsEnabled());
411             comm.setString(4, currentSecPol.getClassification().getClassification().value());
412             comm.setString(5, currentSecPol.getClassification().getCaveats());
413             comm.execute();
414 
415             SetGlobalPolicyResponseMsg r = new SetGlobalPolicyResponseMsg();
416             r.setClassification(this.getCurrentOperatingClassificationLevel());
417             return r;
418         } catch (Exception ex) {
419             log.log(Level.ERROR, "Error caught inserting global policy, attempting rolling back", ex);
420 
421             if (con != null) {
422                 PreparedStatement rollback = null;
423                 try {
424                     rollback = con.prepareStatement("ROLLBACK WORK;");
425                     rollback.execute();
426                     log.log(Level.INFO, "Error caught inserting global policy, rollback successful");
427                     rollback.close();
428                 } catch (Exception e) {
429                     log.log(Level.FATAL, "unable to rollback transaction, this can result in deadlocks!", e);
430                 } finally {
431                     DBUtils.safeClose(rollback);
432                 }
433             }
434             ServiceUnavailableException f = new ServiceUnavailableException("", null);
435             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
436             throw f;
437         } finally {
438             DBUtils.safeClose(comm);
439             DBUtils.safeClose(con);
440         }
441 
442     }
443 
444     /**
445      *
446      *
447      * requires the global policy values
448      *
449      * required permission: none
450      *
451      *
452      *
453      * <param name="request">can't be null, class level should be specified but
454      * can be null</param>
455      *
456      *
457      *
458      * @param request
459      * @return returns
460      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetGlobalPolicyResponseMsg
461      * @throws AccessDeniedException
462      * @throws ServiceUnavailableException
463      */
464     @WebMethod(operationName = "GetGlobalPolicy", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetGlobalPolicy")
465     @WebResult(name = "GetGlobalPolicyResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
466     @RequestWrapper(localName = "GetGlobalPolicy", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetGlobalPolicy")
467     @ResponseWrapper(localName = "GetGlobalPolicyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetGlobalPolicyResponse")
468     public GetGlobalPolicyResponseMsg getGlobalPolicy(
469             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetGlobalPolicyRequestMsg request)
470             throws AccessDeniedException, ServiceUnavailableException {
471 
472         if (request == null) {
473             throw new IllegalArgumentException("request is null");
474         }
475         //  Utility.validateClassification(request.getClassification());
476 
477         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
478 
479         AuditLogger.logItem(this.getClass().getCanonicalName(), "getGlobalPolicy", currentUser, "", (request.getClassification()), ctx.getMessageContext());
480 
481         return getGlobalPolicyFromDB();
482     }
483 
484     private static GetGlobalPolicyResponseMsg getGlobalPolicyFromDB() throws ServiceUnavailableException {
485         Connection con = Utility.getConfigurationDBConnection();
486         PreparedStatement comm = null;
487         ResultSet results = null;
488         GetGlobalPolicyResponseMsg response = new GetGlobalPolicyResponseMsg();
489         boolean foundPolicy = false;
490         try {
491 
492             response.setPolicy(new GlobalPolicy());
493             //we don't care about the request in this case
494 
495             comm = con.prepareStatement("Select * from GlobalPolicies;");
496 
497             /////////////////////////////////////////////
498             //get the global policy for data retension
499             /////////////////////////////////////////////
500             results = comm.executeQuery();
501 
502             if (results.next()) {
503                 response.getPolicy().setPolicyRefreshRate(df.newDuration(results.getLong("PolicyRefreshRate")));
504                 //moved this to settings list
505 
506                 //response.getPolicy().setUDDIPublishRate(fac.newDuration(results.getLong("UDDIPublishRate")));
507                 response.getPolicy().setRecordedMessageCap(results.getInt("RecordedMessageCap"));
508                 SecurityWrapper wrap = new SecurityWrapper(ClassificationType.fromValue(results.getString("classification")),
509                         results.getString("caveat"));
510                 response.setClassification(wrap);
511                 response.getPolicy().setAgentsEnabled(results.getBoolean("agentsenable"));
512                 currentLevel = response.getClassification();
513                 foundPolicy = true;
514             }
515         } catch (Exception ex) {
516             log.log(Level.ERROR, "error getting global policy", ex);
517         } finally {
518             DBUtils.safeClose(results);
519             DBUtils.safeClose(comm);
520 
521         }
522 
523         if (!foundPolicy) {
524             try {
525                 comm = con.prepareStatement("INSERT INTO GlobalPolicies (PolicyRefreshRate, RecordedMessageCap, classification, agentsenable, caveat) "
526                         + " VALUES (?, ?, ?, true, ?);");
527                 comm.setLong(1, 30 * 60 * 100);
528                 comm.setLong(2, 1024000);
529                 //comm.setLong(3, 1024000);
530                 comm.setString(3, "U");
531                 comm.setString(4, "");
532                 comm.execute();
533                 response.getPolicy().setRecordedMessageCap(1024000);
534                 //response.getPolicy().setUDDIPublishRate(fac.newDuration(30 * 60 * 100));
535                 //response.getPolicy().setUDDIPublishRate(fac.newDuration(0));
536                 response.getPolicy().setClassification(new SecurityWrapper(ClassificationType.U, "None"));
537                 response.getPolicy().setAgentsEnabled(true);
538             } catch (SQLException ex) {
539                 log.log(Level.FATAL, "error setting global policy", ex);
540                 response = null;
541             } finally {
542                 DBUtils.safeClose(results);
543                 DBUtils.safeClose(comm);
544                 DBUtils.safeClose(con);
545             }
546         }
547         DBUtils.safeClose(con);
548         if (response != null) {
549             KeyNameValueEnc d = DBSettingsLoader.GetPropertiesFromDB(true, "UddiPublisher", "Interval");
550             if (d != null && d.getKeyNameValue() != null) {
551                 try {
552                     response.getPolicy().setUDDIPublishRate(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
553                 } catch (Exception ex) {
554                     log.log(Level.DEBUG, "error setting global policy", ex);
555                     response.getPolicy().setUDDIPublishRate(df.newDuration(30 * 60 * 100));
556                 }
557             } else {
558                 response.getPolicy().setUDDIPublishRate(df.newDuration(30 * 60 * 100));
559             }
560             return response;
561         }
562         ServiceUnavailableException f = new ServiceUnavailableException("", null);
563         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
564         throw f;
565     }
566 
567     /**
568      *
569      *
570      * Deletes a service policy to the configuration database and optionally,
571      * performance data
572      *
573      * Required Permission: administer
574      *
575      *
576      *
577      *
578      *
579      *
580      *
581      * @param request
582      * @return returns
583      * org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteServicePolicyResponseMsg
584      * @throws AccessDeniedException
585      * @throws ServiceUnavailableException
586      */
587     @WebMethod(operationName = "DeleteServicePolicy", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/DeleteServicePolicy")
588     @WebResult(name = "DeleteServicePolicyResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
589     @RequestWrapper(localName = "DeleteServicePolicy", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteServicePolicy")
590     @ResponseWrapper(localName = "DeleteServicePolicyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteServicePolicyResponse")
591     public DeleteServicePolicyResponseMsg deleteServicePolicy(
592             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") DeleteServicePolicyRequestMsg request)
593             throws AccessDeniedException, ServiceUnavailableException {
594 
595         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
596 
597         if (request == null) {
598             throw new IllegalArgumentException("request is null");
599         }
600         if (Utility.stringIsNullOrEmpty(request.getURL())) {
601             throw new IllegalArgumentException("a URL must be specified");
602         }
603         Utility.validateClassification(request.getClassification());
604 
605         AuditLogger.logItem(this.getClass().getCanonicalName(), "deleteServicePolicy", currentUser, request.getURL(), (request.getClassification()), ctx.getMessageContext());
606         UserIdentityUtil.assertWriteAccess(request.getURL(), currentUser, "DeleteServicePolicy", (request.getClassification()), ctx);
607         deleteFromDB(request.getURL(), request.isDeletePerformanceData(), true);
608         if (request.isDeletePerformanceData()) {
609             deleteAvailabilityData(request.getURL());
610         }
611         deleteAllSLASubscriptions(request.getURL(), currentUser);
612 
613         DeleteServicePolicyResponseMsg response = new DeleteServicePolicyResponseMsg();
614         removeFromStatus(request.getURL());
615         ClearCredentialsRequestMsg rr = new ClearCredentialsRequestMsg();
616         rr.setClassification(request.getClassification());
617         rr.setUrl(request.getURL());
618         clearCredentials(rr);
619         response.setSuccess(true);
620         response.setClassification(getCurrentOperatingClassificationLevel());
621         return response;
622     }
623 
624     /**
625      *
626      *
627      * Sets the permissions on a particular service object
628      *
629      * Removes the current permission set and replaces it with the requested
630      * permission set
631      *
632      * Required Permission: administer
633      *
634      *
635      *
636      *
637      *
638      *
639      *
640      * @param request
641      * @return returns
642      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePermissionsResponseMsg
643      * @throws AccessDeniedException
644      * @throws ServiceUnavailableException
645      */
646     @WebMethod(operationName = "SetServicePermissions", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetServicePermissions")
647     @WebResult(name = "SetServicePermissionsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
648     @RequestWrapper(localName = "SetServicePermissions", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePermissions")
649     @ResponseWrapper(localName = "SetServicePermissionsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetServicePermissionsResponse")
650     public SetServicePermissionsResponseMsg setServicePermissions(
651             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetServicePermissionsRequestMsg request)
652             throws AccessDeniedException, ServiceUnavailableException {
653         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
654         //log.log(Level.INFO, "SetServicePermissions ", currentUser);
655 
656         if (request == null) {
657             throw new IllegalArgumentException("request");
658         }
659         Utility.validateClassification(request.getClassification());
660         if (Utility.stringIsNullOrEmpty(request.getURL())) {
661             throw new IllegalArgumentException("URL");
662         }
663         if (request.getRights() == null) {
664             throw new IllegalArgumentException("rights");
665         }
666 
667         validatePolicyExists(request.getURL());
668         AuditLogger.logItem(this.getClass().getCanonicalName(), "setServicePermissions", currentUser, request.getURL(), (request.getClassification()), ctx.getMessageContext());
669         UserIdentityUtil.assertAdministerAccess(request.getURL(), currentUser, "setServicePerimssions", (request.getClassification()), ctx);
670 
671         Connection con = Utility.getConfigurationDBConnection();
672         PreparedStatement comm = null;
673         try {
674             removePermissionsFromDB(request.getURL());
675         } catch (Exception ex) {
676             log.log(Level.ERROR, "error removing permissions from the db", ex);
677         }
678 
679         try {
680             for (int i = 0; i < request.getRights().getUserPermissionType().size(); i++) {
681                 try {
682                     comm = con.prepareStatement("INSERT INTO UserPermissions (Username,ObjectURI,ReadObject,WriteObject,AdministerObject,AuditObject) " + " VALUES (?, ?, ?, ?, ?, ?);");
683                     comm.setString(1, request.getRights().getUserPermissionType().get(i).getUser());
684                     comm.setString(2, request.getURL());
685                     switch (request.getRights().getUserPermissionType().get(i).getRight()) {
686                         case ADMINISTER:
687                             comm.setBoolean(3, false);
688                             comm.setBoolean(4, false);
689                             comm.setBoolean(5, true);
690                             comm.setBoolean(6, false);
691                             //   cmd.CommandText += "0,0,1,0)";
692                             break;
693                         case AUDIT:
694                             comm.setBoolean(3, false);
695                             comm.setBoolean(4, false);
696                             comm.setBoolean(5, false);
697                             comm.setBoolean(6, true);
698                             //   cmd.CommandText += "0,0,0,1)";
699                             break;
700                         case READ:
701                             comm.setBoolean(3, true);
702                             comm.setBoolean(4, false);
703                             comm.setBoolean(5, false);
704                             comm.setBoolean(6, false);
705                             // cmd.CommandText += "1,0,0,0)";
706                             break;
707                         case WRITE:
708                             comm.setBoolean(3, false);
709                             comm.setBoolean(4, true);
710                             comm.setBoolean(5, false);
711                             comm.setBoolean(6, false);
712                             //    cmd.CommandText += "0,1,0,0)";
713                             break;
714                     }
715                     comm.execute();
716                 } catch (SQLException ex) {
717                     log.log(Level.ERROR, "error setting service permissions", ex);
718                     ServiceUnavailableException f = new ServiceUnavailableException("", null);
719                     f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
720                     throw f;
721                 } finally {
722                     DBUtils.safeClose(comm);
723                 }
724             }
725         } catch (ServiceUnavailableException ex) {
726             throw ex;
727         } finally {
728             DBUtils.safeClose(con);
729         }
730 
731         SetServicePermissionsResponseMsg response = new SetServicePermissionsResponseMsg();
732         response.setClassification(getCurrentOperatingClassificationLevel());
733         return response;
734 
735     }
736 
737     /**
738      *
739      *
740      * Returns the permission set from a service object
741      *
742      * Required Permission: read
743      *
744      *
745      *
746      *
747      *
748      *
749      *
750      * @param request
751      * @return returns
752      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetServicePermissionsResponseMsg
753      * @throws AccessDeniedException
754      * @throws ServiceUnavailableException
755      */
756     @WebMethod(operationName = "GetServicePermissions", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetServicePermissions")
757     @WebResult(name = "GetServicePermissionsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
758     @RequestWrapper(localName = "GetServicePermissions", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetServicePermissions")
759     @ResponseWrapper(localName = "GetServicePermissionsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetServicePermissionsResponse")
760     public GetServicePermissionsResponseMsg getServicePermissions(
761             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetServicePermissionsRequestMsg request)
762             throws AccessDeniedException, ServiceUnavailableException {
763         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
764         if (request == null) {
765             throw new IllegalArgumentException("a message must be specified");
766         }
767         Utility.validateClassification(request.getClassification());
768 
769         GetServicePermissionsResponseMsg res = null;
770         AuditLogger.logItem(this.getClass().getCanonicalName(), "getServicePermissions", currentUser, "", (request.getClassification()), ctx.getMessageContext());
771         if (request.getURL() != null && !Utility.stringIsNullOrEmpty(request.getURL())) {
772             AuditLogger.logItem(this.getClass().getCanonicalName(), "getServicePermissions", currentUser, request.getURL(), (request.getClassification()), ctx.getMessageContext());
773             UserIdentityUtil.assertAuditAccess(request.getURL(), currentUser, "GetServicePermissionsURL", (request.getClassification()), ctx);
774             validatePolicyExists(request.getURL());
775             res = getServicePermissions(request.getURL(), null);
776         }
777         if (request.getUser() != null && !Utility.stringIsNullOrEmpty(request.getUser())) {
778             if ((currentUser.equalsIgnoreCase(request.getUser())) || (UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "GetServicePermissionsUSER", (request.getClassification()), ctx))) {
779                 AuditLogger.logItem(this.getClass().getCanonicalName(), "getServicePermissions", currentUser, request.getUser(), (request.getClassification()), ctx.getMessageContext());
780                 res = getServicePermissions(null, request.getUser());
781             }
782         }
783         if (res == null) {
784             throw new IllegalArgumentException("You  must specify a user or url");
785         }
786         return res;
787     }
788 
789     /**
790      *
791      *
792      * Returns a list of users with the global admin role
793      *
794      *
795      *
796      *
797      *
798      *
799      *
800      * @param request
801      * @return returns
802      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetAdministratorsResponseMsg
803      * @throws AccessDeniedException
804      * @throws ServiceUnavailableException
805      */
806     @WebMethod(operationName = "GetAdministrators", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetAdministrators")
807     @WebResult(name = "GetAdministratorsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
808     @RequestWrapper(localName = "GetAdministrators", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAdministrators")
809     @ResponseWrapper(localName = "GetAdministratorsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAdministratorsResponse")
810     public GetAdministratorsResponseMsg getAdministrators(
811             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetAdministratorsRequestMsg request)
812             throws AccessDeniedException, ServiceUnavailableException {
813         Connection con = null;
814         ResultSet results = null;
815         PreparedStatement comm = null;
816         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
817         if (request == null) {
818             throw new IllegalArgumentException("a request msg must be specified");
819         }
820         Utility.validateClassification(request.getClassification());
821 
822         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAdministrators", currentUser, "", (request.getClassification()), ctx.getMessageContext());
823         //log.log(Level.INFO, "getAdministrators " + currentUser);
824         //we don't care about the request in this case
825         GetAdministratorsResponseMsg response = new GetAdministratorsResponseMsg();
826         try {
827 
828             ArrayOfUserInfo list2 = new ArrayOfUserInfo();
829             con = Utility.getConfigurationDBConnection();
830             comm = con.prepareStatement("Select * from Users where rolecol='admin';");
831             /////////////////////////////////////////////
832             //get the global policy for data retension
833             /////////////////////////////////////////////
834             results = comm.executeQuery();
835             while (results.next()) {
836                 UserInfo u = new UserInfo();
837                 u.setUsername(results.getString("Username"));
838                 u.setRole("admin");
839                 if (!Utility.stringIsNullOrEmpty(results.getString("email"))) {
840                     u.getEmail().add(results.getString("email"));
841                 }
842                 if (!Utility.stringIsNullOrEmpty(results.getString("email1"))) {
843                     u.getEmail().add(results.getString("email1"));
844                 }
845                 if (!Utility.stringIsNullOrEmpty(results.getString("email2"))) {
846                     u.getEmail().add(results.getString("email2"));
847                 }
848                 if (!Utility.stringIsNullOrEmpty(results.getString("email3"))) {
849                     u.getEmail().add(results.getString("email3"));
850                 }
851                 u.setDisplayName((results.getString("DisplayName")));
852                 list2.getUserInfo().add(u);
853             }
854 
855             response.setUserList((list2));
856             response.setClassification(currentLevel);
857 
858             return response;
859         } catch (SQLException ex) {
860             log.log(Level.ERROR, "error setting fgsms admins", ex);
861             ServiceUnavailableException f = new ServiceUnavailableException("", null);
862             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
863             throw f;
864         } finally {
865             DBUtils.safeClose(results);
866             DBUtils.safeClose(comm);
867             DBUtils.safeClose(con);
868         }
869 
870     }
871 
872     /**
873      *
874      *
875      * Sets a list of users with the global admin role
876      *
877      * All previous entries are removed
878      *
879      *
880      *
881      *
882      *
883      *
884      *
885      * @param request
886      * @return returns
887      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetAdministratorResponseMsg
888      * @throws ServiceUnavailableException
889      * @throws AccessDeniedException
890      */
891     @WebMethod(operationName = "SetAdministrator", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetAdministrator")
892     @WebResult(name = "SetAdministratorResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
893     @RequestWrapper(localName = "SetAdministrator", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAdministrator")
894     @ResponseWrapper(localName = "SetAdministratorResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAdministratorResponse")
895     public SetAdministratorResponseMsg setAdministrator(
896             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetAdministratorRequestMsg request)
897             throws AccessDeniedException, ServiceUnavailableException {
898         Connection con = null;
899         PreparedStatement comm = null;
900 
901         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
902 
903         if (request == null) {
904             throw new IllegalArgumentException("request is null");
905         }
906         Utility.validateClassification(request.getClassification());
907 
908         AuditLogger.logItem(this.getClass().getCanonicalName(), "setAdministrator", currentUser, "", (request.getClassification()), ctx.getMessageContext());
909         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "setAdministrator", (request.getClassification()), ctx);
910         if (request.getUserList() == null) {
911             log.log(Level.ERROR, "userlist null");
912         }
913         if (request.getUserList() == null) {
914             log.log(Level.ERROR, "userlist value null");
915         }
916         if (request.getUserList().getUserInfo() == null) {
917             log.log(Level.ERROR, "getuserinfo null");
918         }
919         if (request.getUserList().getUserInfo().isEmpty()) {
920             log.log(Level.ERROR, "getuserinfo is empty");
921         }
922         if (request.getUserList() == null
923                 || request.getUserList().getUserInfo() == null
924                 || request.getUserList().getUserInfo().isEmpty()) {
925             throw new IllegalArgumentException("userlist is empty or null");
926         }
927         for (int i = 0; i < request.getUserList().getUserInfo().size(); i++) {
928             if (request.getUserList().getUserInfo().get(i).getEmail().size() > 4) {
929                 throw new IllegalArgumentException("a user has more than 4 email addresses defined. Only 4 are supported");
930             }
931         }
932 
933         con = Utility.getConfigurationDBConnection();
934         try {
935 
936             comm = con.prepareStatement("delete from Users where rolecol='admin';");
937             comm.execute();
938         } catch (SQLException ex) {
939             log.log(Level.ERROR, "error setting fgsms admins", ex);
940         } finally {
941             DBUtils.safeClose(comm);
942         }
943         /////////////////////////////////////////////
944         //get the global policy for data retension
945         /////////////////////////////////////////////
946         try {
947             for (int i = 0; i < request.getUserList().getUserInfo().size(); i++) {
948                 try {
949                     comm = con.prepareStatement("INSERT INTO Users (Username, DisplayName,Email, email1, email2, email3,rolecol) VALUES (?,?,?,?,?,?, 'admin');");
950                     comm.setString(1, request.getUserList().getUserInfo().get(i).getUsername());
951                     comm.setString(2, request.getUserList().getUserInfo().get(i).getDisplayName());
952                     if (request.getUserList().getUserInfo().get(i).getEmail().size() > 0) {
953                         comm.setString(3, request.getUserList().getUserInfo().get(i).getEmail().get(0));
954                     } else {
955                         comm.setNull(3, java.sql.Types.VARCHAR);
956                     }
957                     if (request.getUserList().getUserInfo().get(i).getEmail().size() > 1) {
958                         comm.setString(4, request.getUserList().getUserInfo().get(i).getEmail().get(1));
959                     } else {
960                         comm.setNull(4, java.sql.Types.VARCHAR);
961                     }
962 
963                     if (request.getUserList().getUserInfo().get(i).getEmail().size() > 2) {
964                         comm.setString(5, request.getUserList().getUserInfo().get(i).getEmail().get(2));
965                     } else {
966                         comm.setNull(5, java.sql.Types.VARCHAR);
967                     }
968                     if (request.getUserList().getUserInfo().get(i).getEmail().size() > 3) {
969                         comm.setString(6, request.getUserList().getUserInfo().get(i).getEmail().get(3));
970                     } else {
971                         comm.setNull(6, java.sql.Types.VARCHAR);
972                     }
973 
974                     comm.execute();
975                 } catch (SQLException ex) {
976                     log.log(Level.ERROR, "error setting fgsms admins", ex);
977                 } finally {
978                     DBUtils.safeClose(comm);
979 
980                 }
981             }
982             SetAdministratorResponseMsg ret = new SetAdministratorResponseMsg();
983             ret.setClassification(currentLevel);
984             return ret;
985         } catch (Exception ex) {
986             log.log(Level.ERROR, "error setting fgsms admins", ex);
987         } finally {
988             DBUtils.safeClose(comm);
989             DBUtils.safeClose(con);
990         }
991 
992         ServiceUnavailableException f = new ServiceUnavailableException("", null);
993         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
994         throw f;
995     }
996 
997     /**
998      * Gets the specified policy from postgres database
999      *
1000      * @param requestedURI
1001      * @param classification
1002      * @param currentUser
1003      * @param requestedPt must be specified
1004      * @param hostname used for policy creation
1005      * @param domain used for policy creation
1006      * @param create if true and the user has permissions to create a policy,
1007      * one will be made using the requested policytype
1008      * @return
1009      */
1010     private ServicePolicy getPolicyFromDB(final String requestedURI, final SecurityWrapper classification, final String currentUser, final PolicyType requestedPt, final String hostname, String domain, boolean create) {
1011         Connection con = null;
1012         PreparedStatement comm = null;
1013         ResultSet results = null;
1014         try {
1015             if (Utility.stringIsNullOrEmpty(requestedURI)) {
1016                 throw new IllegalArgumentException("requestedURI");
1017             }
1018 
1019             GetGlobalPolicyResponseMsg gp = getGlobalPolicyFromDB();
1020 
1021             con = Utility.getConfigurationDBConnection();
1022             comm = con.prepareStatement("Select * from ServicePolicies where URI=?;");
1023             comm.setString(1, requestedURI);
1024 
1025             /////////////////////////////////////////////
1026             //get the policy for this service
1027             /////////////////////////////////////////////
1028             ServicePolicy ret = null;
1029             boolean CapDefined = true;
1030 
1031             results = comm.executeQuery();
1032 
1033             if (results.next()) {
1034                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
1035                 Unmarshaller um = jc.createUnmarshaller();
1036                 byte[] s = results.getBytes("xmlpolicy");
1037 
1038                 //System.err.println(new String(s));
1039                 //System.out.println(new String(s));
1040                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1041                 //1 = reader
1042                 //2 = writer
1043                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
1044                 XMLInputFactory xf = XMLInputFactory.newInstance();
1045                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1046                 switch (pt) {
1047                     case MACHINE:
1048                         JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
1049                         if (foo == null || foo.getValue() == null) {
1050                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1051                         } else {
1052                             ret = foo.getValue();
1053                         }
1054                         break;
1055                     case PROCESS:
1056                         JAXBElement<ProcessPolicy> foo3 = (JAXBElement<ProcessPolicy>) um.unmarshal(r, ProcessPolicy.class);
1057                         if (foo3 == null || foo3.getValue() == null) {
1058                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1059                         } else {
1060                             ret = foo3.getValue();
1061                         }
1062                         break;
1063                     case STATISTICAL:
1064                         JAXBElement<StatisticalServicePolicy> foo1 = (JAXBElement<StatisticalServicePolicy>) um.unmarshal(r, StatisticalServicePolicy.class);
1065                         if (foo1 == null || foo1.getValue() == null) {
1066                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1067                         } else {
1068                             ret = foo1.getValue();
1069                         }
1070                         break;
1071                     case STATUS:
1072                         JAXBElement<StatusServicePolicy> foo2 = (JAXBElement<StatusServicePolicy>) um.unmarshal(r, StatusServicePolicy.class);
1073                         if (foo2 == null || foo2.getValue() == null) {
1074                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1075                         } else {
1076                             ret = foo2.getValue();
1077                         }
1078                         break;
1079                     case TRANSACTIONAL:
1080                         JAXBElement<TransactionalWebServicePolicy> foo4 = (JAXBElement<TransactionalWebServicePolicy>) um.unmarshal(r, TransactionalWebServicePolicy.class);
1081                         if (foo4 == null || foo4.getValue() == null) {
1082                             log.log(Level.WARN, "policy is unexpectedly null or empty");
1083                         } else {
1084                             ret = foo4.getValue();
1085                         }
1086                         break;
1087 
1088                 }
1089 
1090                 r.close();
1091                 bss.close();
1092 
1093                 if (results.next()) {
1094                     log.log(Level.ERROR, "Unable to determine the policy for service " + requestedURI
1095                             + " because more than one policy is defined for this service! This is an unexpected database error. "
1096                             + "Returning the default policy to the requestor. Please contact the developers and report this at https://github.com/mil-oss/fgsms");
1097 
1098                 }
1099             } else {
1100 
1101                 if (!create) {
1102                     comm.close();
1103                     con.close();
1104                     return null;
1105                 }
1106                 //policy does not exist, create it
1107                 if (create && requestedPt == null) {
1108                     throw new IllegalArgumentException("a policy type must be specified");
1109                 }
1110                 AuditLogger.logItem(this.getClass().getCanonicalName(), "Createpolicy", currentUser, requestedURI, classification, ctx.getMessageContext());
1111                 UserIdentityUtil.assertAdminOrAgentRole(currentUser, "GetPolicy then CreatePolicy", currentLevel, ctx);
1112                 //new to rc6 only
1113 
1114                 //set the default values
1115                 KeyNameValueEnc d = null;
1116                 switch (requestedPt) {
1117                     case MACHINE:
1118                         ret = new MachinePolicy();
1119                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Machine", "defaultRentention");
1120                         if (d != null && d.getKeyNameValue() != null) {
1121                             try {
1122                                 ret.setDataTTL(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
1123                                 ((MachinePolicy) ret).setRecordCPUusage(true);
1124                                 ((MachinePolicy) ret).setRecordMemoryUsage(true);
1125                             } catch (Exception ex) {
1126                                 log.log(Level.WARN, "Defaulting to 2592000000 for machine default retention.", ex);
1127                             }
1128                         } else {
1129                             ret.setDataTTL(df.newDuration(Long.parseLong("2592000000")));
1130                         }
1131                         break;
1132                     case PROCESS:
1133                         ret = new ProcessPolicy();
1134                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Process", "defaultRentention");
1135                         if (d != null && d.getKeyNameValue() != null) {
1136                             try {
1137                                 ret.setDataTTL(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
1138                                 ((ProcessPolicy) ret).setRecordCPUusage(true);
1139                                 ((ProcessPolicy) ret).setRecordMemoryUsage(true);
1140                                 ((ProcessPolicy) ret).setRecordOpenFileHandles(true);
1141                             } catch (Exception ex) {
1142                                 log.log(Level.WARN, "unable to parse .\"Policy.Process\", \"defaultRentention\"", ex);
1143                             }
1144                         } else {
1145                             ret.setDataTTL(df.newDuration(Long.parseLong("2592000000")));
1146                         }
1147                         break;
1148                     case STATISTICAL:
1149                         ret = new StatisticalServicePolicy();
1150                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Machine", "defaultRentention");
1151                         if (d != null && d.getKeyNameValue() != null) {
1152                             try {
1153                                 ret.setDataTTL(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
1154                             } catch (Exception ex) {
1155                                 log.log(Level.WARN, "unable to parse .\"Policy.Machine\", \"defaultRentention\"", ex);
1156                             }
1157                         } else {
1158                             ret.setDataTTL(df.newDuration(Long.parseLong("2592000000")));
1159                         }
1160                         break;
1161                     case STATUS:
1162                         ret = new StatusServicePolicy();
1163                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Status", "defaultRentention");
1164                         if (d != null && d.getKeyNameValue() != null) {
1165                             try {
1166                                 ret.setDataTTL(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
1167                             } catch (Exception ex) {
1168                                 log.log(Level.WARN, "Defaulting to 2592000000 for status default retention.", ex);
1169                             }
1170                         } else {
1171                             ret.setDataTTL(df.newDuration(Long.parseLong("2592000000")));
1172                         }
1173                         break;
1174                     case TRANSACTIONAL:
1175                         ret = new TransactionalWebServicePolicy();
1176 
1177                         ((TransactionalWebServicePolicy) ret).setBuellerEnabled(true);
1178                         ((TransactionalWebServicePolicy) ret).setAgentsEnabled(gp.getPolicy().isAgentsEnabled());
1179                         ((TransactionalWebServicePolicy) ret).setRecordedMessageCap(gp.getPolicy().getRecordedMessageCap());
1180 
1181                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Transactional", "defaultRecordRequest");
1182                         if (d != null && d.getKeyNameValue() != null) {
1183                             try {
1184                                 ((TransactionalWebServicePolicy) ret).setRecordRequestMessage(Boolean.parseBoolean(d.getKeyNameValue().getPropertyValue()));
1185                             } catch (Exception ex) {
1186                                 log.log(Level.WARN, "Unable to parse .\"Policy.Transactional\", \"defaultRecordRequest\"", ex);
1187                             }
1188                         } else {
1189                             ((TransactionalWebServicePolicy) ret).setRecordRequestMessage(false);
1190                         }
1191                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Transactional", "defaultRecordResponse");
1192                         if (d != null && d.getKeyNameValue() != null) {
1193                             try {
1194                                 ((TransactionalWebServicePolicy) ret).setRecordResponseMessage(Boolean.parseBoolean(d.getKeyNameValue().getPropertyValue()));
1195                             } catch (Exception ex) {
1196                                 log.log(Level.WARN, "Unable to parse .\"Policy.Transactional\", \"defaultRecordResponse\"", ex);
1197                             }
1198                         } else {
1199                             ((TransactionalWebServicePolicy) ret).setRecordResponseMessage(false);
1200                         }
1201 
1202                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Transactional", "defaultRecordFaults");
1203                         if (d != null && d.getKeyNameValue() != null) {
1204                             try {
1205                                 ((TransactionalWebServicePolicy) ret).setRecordFaultsOnly(Boolean.parseBoolean(d.getKeyNameValue().getPropertyValue()));
1206                             } catch (Exception ex) {
1207                                 log.log(Level.WARN, "Unable to parse .\"Policy.Transactional\", \"defaultRecordFaults\"", ex);
1208                             }
1209                         } else {
1210                             ((TransactionalWebServicePolicy) ret).setRecordFaultsOnly(false);
1211                         }
1212                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Transactional", "defaultRecordHeaders");
1213                         if (d != null && d.getKeyNameValue() != null) {
1214                             try {
1215                                 ((TransactionalWebServicePolicy) ret).setRecordHeaders(Boolean.parseBoolean(d.getKeyNameValue().getPropertyValue()));
1216                             } catch (Exception ex) {
1217                                 log.log(Level.WARN, "Unable to parse .\"Policy.Transactional\", \"defaultRecordHeaders\"", ex);
1218                             }
1219                         } else {
1220                             ((TransactionalWebServicePolicy) ret).setRecordHeaders(true);
1221                         }
1222 
1223                         d = DBSettingsLoader.GetPropertiesFromDB(true, "Policy.Transactional", "defaultRentention");
1224                         if (d != null && d.getKeyNameValue() != null) {
1225                             try {
1226                                 ret.setDataTTL(df.newDuration(Long.parseLong(d.getKeyNameValue().getPropertyValue())));
1227                             } catch (Exception ex) {
1228                                 log.log(Level.WARN, "Unable to parse .\"Policy.Transactional\", \"defaultRentention\"", ex);
1229                             }
1230                         } else {
1231                             ret.setDataTTL(df.newDuration(Long.parseLong("2592000000")));
1232                         }
1233                         break;
1234                 }
1235                 if (ret == null) {
1236                     throw new Exception("unhandled case, very expected");
1237                 }
1238 
1239                 ret.setDomainName(domain);
1240                 ret.setMachineName(hostname);
1241                 ret.setURL(requestedURI);
1242                 ret.setPolicyType(requestedPt);
1243 
1244                 Utility.addStatusChangeSLA(ret);
1245                 //RC6 add default settings if available
1246                 createPolicy(requestedURI, ret, currentUser, requestedPt);
1247                 alertingThreadPool.execute(new Runnable() {
1248                     @Override
1249                     public void run() {
1250                         SLACommon.AlertGlobalAdminsNewPolicyCreated(currentUser, requestedURI, true, requestedPt);
1251                     }
1252                 });
1253 
1254             }
1255 
1256             results.close();
1257             comm.close();
1258             if (ret == null) {
1259                 throw new Exception("unhandled case, very expected");
1260             }
1261             ret.setPolicyRefreshRate(gp.getPolicy().getPolicyRefreshRate());
1262             ret.setAgentsEnabled(gp.getPolicy().isAgentsEnabled());
1263 
1264             if (!CapDefined && ret instanceof TransactionalWebServicePolicy) {
1265                 ((TransactionalWebServicePolicy) ret).setRecordedMessageCap((gp.getPolicy().getRecordedMessageCap()));
1266             }
1267 
1268             ret.setURL(requestedURI);
1269 
1270             con.close();
1271             return ret;
1272         } catch (SQLException ex) {
1273             log.log(Level.DEBUG, "error retrieving policy from database, db error", ex);
1274             log.log(Level.ERROR, "error retrieving policy from database, db error" + ex.getMessage());
1275         } catch (Exception ex) {
1276             log.log(Level.DEBUG, "error retrieving policy from database, Exception", ex);
1277             log.log(Level.ERROR, "error retrieving policy from database, Exception" + ex.getMessage());
1278         } finally {
1279             DBUtils.safeClose(results);
1280             DBUtils.safeClose(comm);
1281             DBUtils.safeClose(con);
1282         }
1283         return null;
1284     }
1285 
1286     /**
1287      * returns the machine policy or null if it doesn't exist
1288      *
1289      * @param hostname
1290      * @return
1291      */
1292     private MachinePolicy getMachinePolicyFromDB(String hostname) {
1293         Connection con = null;
1294         PreparedStatement comm = null;
1295         ResultSet results = null;
1296         try {
1297             if (Utility.stringIsNullOrEmpty(hostname)) {
1298                 throw new IllegalArgumentException("hostname");
1299             }
1300 
1301             con = Utility.getConfigurationDBConnection();
1302             comm = con.prepareStatement("Select * from ServicePolicies where hostname=? and policytype=?;");
1303             comm.setString(1, hostname);
1304             comm.setInt(2, PolicyType.MACHINE.ordinal());
1305 
1306             /////////////////////////////////////////////
1307             //get the policy for this service
1308             /////////////////////////////////////////////
1309             MachinePolicy ret = null;
1310 
1311             results = comm.executeQuery();
1312 
1313             if (results.next()) {
1314 
1315                 Unmarshaller um = jc.createUnmarshaller();
1316                 byte[] s = results.getBytes("xmlpolicy");
1317 
1318                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1319                 //1 = reader
1320                 //2 = writer
1321                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
1322                 XMLInputFactory xf = XMLInputFactory.newInstance();
1323                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1324 
1325                 JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) um.unmarshal(r, MachinePolicy.class);
1326                 if (foo == null || foo.getValue() == null) {
1327                     log.log(Level.WARN, "policy is unexpectedly null or empty");
1328                 } else {
1329                     ret = foo.getValue();
1330                 }
1331                 r.close();
1332                 bss.close();
1333                 if (results.next()) {
1334                     log.log(Level.ERROR, "Unable to determine the policy for service " + hostname
1335                             + " because more than one policy is defined for this service! This is an unexpected database error. "
1336                             + "Returning the default policy to the requestor. Please contact the developers and report this at https://github.com/mil-oss/fgsms");
1337 
1338                 }
1339             }
1340             if (ret != null) {
1341                 GetGlobalPolicyResponseMsg gp = getGlobalPolicyFromDB();
1342                 ret.setAgentsEnabled(gp.getPolicy().isAgentsEnabled());
1343             }
1344             comm.close();
1345             con.close();
1346             return ret;
1347         } catch (Exception ex) {
1348             log.log(Level.ERROR, "error retrieving policy from database, DatatypeConfigurationException", ex);
1349         } finally {
1350             DBUtils.safeClose(results);
1351             DBUtils.safeClose(comm);
1352             DBUtils.safeClose(con);
1353         }
1354         return null;
1355 
1356     }
1357 
1358     /**
1359      *  /// /// This is used for the self registration of a web service via a
1360      * data collector ///
1361      *
1362      * @param requestedURI
1363      */
1364     private synchronized void createPolicy(String requestedURI, ServicePolicy sp, String username, PolicyType p) {
1365 
1366         if (Utility.stringIsNullOrEmpty(requestedURI)) {
1367             throw new IllegalArgumentException("requestedURI");
1368         }
1369         writePolicytoDB(sp, requestedURI, username);
1370     }
1371 
1372     /**
1373      * /// /// First removes any existing policy then writes the policy to the
1374      * db ///
1375      *
1376      * @param sp
1377      * @param string
1378      */
1379     private boolean writePolicytoDB(final ServicePolicy policy, final String URL, final String currentuser) {
1380         Connection con = null;
1381         PreparedStatement comm = null;
1382         long now = System.currentTimeMillis();
1383         try {
1384             if (policy == null) {
1385                 throw new IllegalArgumentException("policy");
1386 
1387             }
1388             if (Utility.stringIsNullOrEmpty(URL)) {
1389                 throw new IllegalArgumentException("URL");
1390 
1391             }
1392             log.trace("WritePolicytoDB 1 " + (System.currentTimeMillis() - now));
1393             //must be done BEFORE the new policy is written and the old one removed.
1394             validateExistingSLASubscriptions(policy, currentuser);
1395             log.trace("WritePolicytoDB 2 " + (System.currentTimeMillis() - now));
1396             boolean previouslyexisted = deleteFromDB(URL, false, false);
1397             if (!previouslyexisted) {
1398                 alertingThreadPool.execute(new Runnable() {
1399                     @Override
1400                     public void run() {
1401                         SLACommon.AlertGlobalAdminsNewPolicyCreated(currentuser, URL, true, policy.getPolicyType());
1402                     }
1403                 });
1404             }
1405             log.trace("WritePolicytoDB 3 " + (System.currentTimeMillis() - now));
1406 
1407             con = Utility.getConfigurationDBConnection();
1408 
1409             Connection p = null;
1410             PreparedStatement c2 = null;
1411             try {
1412                 p = Utility.getPerformanceDBConnection();
1413                 c2 = p.prepareStatement("INSERT INTO rawdatatally (URI)"
1414                         + "SELECT ? WHERE NOT EXISTS"
1415                         + "(SELECT uri FROM rawdatatally WHERE uri=?);");
1416                 c2.setString(1, URL);
1417                 c2.setString(2, URL);
1418                 c2.execute();
1419 
1420             } catch (Exception ex) {
1421                 log.log(Level.WARN, "Error inserting rawdatatally into the tally table. This is probably ignorable", ex);
1422             } finally {
1423                 DBUtils.safeClose(c2);
1424                 DBUtils.safeClose(p);
1425 
1426             }
1427 
1428             log.trace("WritePolicytoDB 4 " + (System.currentTimeMillis() - now));
1429 
1430             comm = con.prepareStatement("BEGIN WORK;LOCK TABLE servicepolicies IN SHARE ROW EXCLUSIVE MODE;"
1431                     + "INSERT INTO servicepolicies (URI, DataTTL, " //2
1432                     + " latitude, longitude, displayname, policytype, buellerenabled, hostname, domaincol, xmlpolicy, hassla, hasfederation, bucket, lastchanged, lastchangedby," //13
1433                     + "healthstatusenabled, parenturi )" //1
1434                     + " SELECT ?,?,?,?,?,  ?,?,?,?,?, ?,?,?, ?,?,?,? WHERE NOT EXISTS"
1435                     + " (SELECT uri FROM servicepolicies WHERE uri=?);" //1
1436                     + ""
1437                     + "COMMIT WORK;");
1438 
1439             comm.setString(1, URL);
1440             if (policy.getDataTTL() == null) {
1441                 comm.setLong(2, 30 * 24 * 60 * 60);
1442             } else {
1443                 comm.setLong(2, Utility.durationToTimeInMS(policy.getDataTTL()));
1444             }
1445             if (policy.getLocation() != null) {
1446                 comm.setDouble(3, policy.getLocation().getLatitude());
1447                 comm.setDouble(4, policy.getLocation().getLongitude());
1448             } else {
1449                 comm.setNull(3, Types.DOUBLE);
1450                 comm.setNull(4, Types.DOUBLE);
1451             }
1452             if (Utility.stringIsNullOrEmpty(policy.getDisplayName())) {
1453                 comm.setNull(5, java.sql.Types.VARCHAR);
1454             } else {
1455                 comm.setString(5, policy.getDisplayName());
1456             }
1457             comm.setInt(6, policy.getPolicyType().ordinal());
1458             if (policy instanceof TransactionalWebServicePolicy) {
1459                 TransactionalWebServicePolicy tp = (TransactionalWebServicePolicy) policy;
1460                 comm.setBoolean(7, tp.isBuellerEnabled());
1461             } else {
1462                 comm.setBoolean(7, false);
1463             }
1464 
1465             if (Utility.stringIsNullOrEmpty(policy.getMachineName())) {
1466                 comm.setString(8, UNSPECIFIED);
1467             } else {
1468                 comm.setString(8, policy.getMachineName());
1469             }
1470 
1471             if (Utility.stringIsNullOrEmpty(policy.getDomainName())) {
1472                 comm.setString(9, UNSPECIFIED);
1473             } else {
1474                 comm.setString(9, policy.getDomainName());
1475             }
1476             //xml
1477             log.trace("WritePolicytoDB 5 " + (System.currentTimeMillis() - now));
1478             StringWriter sw = new StringWriter();
1479             JAXB.marshal(policy, sw);
1480             log.trace("WritePolicytoDB 6 " + (System.currentTimeMillis() - now));
1481 
1482             String s = sw.toString();
1483             comm.setBytes(10, s.getBytes(Constants.CHARSET));
1484 
1485             if (policy.getServiceLevelAggrements() != null
1486                     && policy.getServiceLevelAggrements().getSLA() != null && !policy.getServiceLevelAggrements().getSLA().isEmpty()) {
1487                 comm.setBoolean(11, true);
1488             } else {
1489                 comm.setBoolean(11, false);
1490             }
1491             if (policy.getFederationPolicyCollection() != null && !policy.getFederationPolicyCollection().getFederationPolicy().isEmpty()) {
1492                 comm.setBoolean(12, true);
1493             } else {
1494                 comm.setBoolean(12, false);
1495             }
1496             if (Utility.stringIsNullOrEmpty(policy.getBucketCategory())) {
1497                 comm.setString(13, UNSPECIFIED);
1498             } else {
1499                 comm.setString(13, policy.getBucketCategory());
1500             }
1501             comm.setLong(14, System.currentTimeMillis());
1502             comm.setString(15, currentuser);
1503             if (policy instanceof TransactionalWebServicePolicy) {
1504                 TransactionalWebServicePolicy tp = (TransactionalWebServicePolicy) policy;
1505                 comm.setBoolean(16, tp.isHealthStatusEnabled());
1506             } else {
1507                 comm.setBoolean(16, false);
1508             }
1509             if (Utility.stringIsNullOrEmpty(policy.getParentObject())) {
1510                 comm.setNull(17, java.sql.Types.VARCHAR);
1511             } else {
1512                 comm.setString(17, policy.getParentObject());
1513             }
1514             comm.setString(18, URL);
1515 
1516             comm.execute();
1517             log.trace("WritePolicytoDB 7 " + (System.currentTimeMillis() - now));
1518             comm.close();
1519             con.close();
1520             log.trace("WritePolicytoDB 8 " + (System.currentTimeMillis() - now));
1521             return true;
1522         } catch (Exception ex) {
1523             log.log(Level.ERROR, "unexpected error writing policy to database, attempting rollback", ex);
1524             if (con != null) {
1525                 PreparedStatement cmd = null;
1526                 try {
1527                     cmd = con.prepareStatement("ROLLBACK WORK;");
1528                     cmd.execute();
1529 
1530                 } catch (Exception e) {
1531                     log.log(Level.ERROR, "unexpected error attempting rollback", e);
1532                 } finally {
1533                     DBUtils.safeClose(cmd);
1534                 }
1535             }
1536         } finally {
1537             DBUtils.safeClose(comm);
1538             DBUtils.safeClose(con);
1539             log.trace("WritePolicytoDB 9 " + (System.currentTimeMillis() - now));
1540         }
1541         return false;
1542     }
1543 
1544     /**
1545      * returns true only if the policy previously existed and was deleted
1546      *
1547      * @param URL
1548      * @param deletePerformanceData
1549      * @param deletePermissions
1550      * @return
1551      */
1552     private boolean deleteFromDB(String URL, boolean deletePerformanceData, boolean deletePermissions) {
1553 
1554         long now = System.currentTimeMillis();
1555         Connection con = null;
1556         Connection con2 = null;
1557         PreparedStatement comm = null;
1558         PreparedStatement comm2 = null;
1559         try {
1560             if (Utility.stringIsNullOrEmpty(URL)) {
1561                 throw new IllegalArgumentException("url");
1562             }
1563 
1564             log.trace("DeleteFromDB 1 " + (System.currentTimeMillis() - now));
1565             int r = 0;
1566             con = Utility.getConfigurationDBConnection();
1567             comm = con.prepareStatement(
1568                     "Delete from ServicePolicies where URI=?; ");
1569 
1570             comm.setString(1, URL);
1571             r = comm.executeUpdate();
1572             log.trace("DeleteFromDB 2 " + (System.currentTimeMillis() - now));
1573             comm.close();
1574             log.trace("DeleteFromDB 3 " + (System.currentTimeMillis() - now));
1575 
1576             if (deletePerformanceData) {
1577                 con2 = Utility.getPerformanceDBConnection();
1578                 comm2 = con2.prepareStatement(
1579                         "Delete from rawdata where uri=?;"
1580                         + "Delete from agg2 where uri=?;"
1581                         + "Delete from brokerrawdata where host=?;"
1582                         + "Delete from brokerhistory where host=?;"
1583                         + " Delete from actionlist where uri=?; "
1584                         + "Delete from slaviolations where uri=?; "
1585                         + "Delete from availability where uri=?;"
1586                         + "Delete from alternateurls where uri=?;"
1587                         + "Delete from rawdatatally where uri=?;"
1588                         + "Delete from rawdatanic where uri=?; "
1589                         + "Delete from rawdatamachineprocess where uri=?; "
1590                         + "Delete from rawdatadrives where uri=?; "
1591                         + "Delete from rawdatamachinesensor where uri=?; ");
1592                 comm2.setString(1, URL);
1593                 comm2.setString(2, URL);
1594                 comm2.setString(3, URL);
1595                 comm2.setString(4, URL);
1596                 comm2.setString(5, URL);
1597                 comm2.setString(6, URL);
1598                 comm2.setString(7, URL);
1599                 comm2.setString(8, URL);
1600                 comm2.setString(9, URL);
1601 
1602                 comm2.setString(10, URL);
1603                 comm2.setString(11, URL);
1604                 comm2.setString(12, URL);
1605                 comm2.setString(13, URL);
1606 //                comm2.setString(14, URL);
1607                 comm2.executeUpdate();
1608                 comm2.close();
1609                 con2.close();
1610 
1611             }
1612             log.trace("DeleteFromDB 4 " + (System.currentTimeMillis() - now));
1613             if (deletePermissions) {
1614                 comm = con.prepareStatement("Delete from UserPermissions where ObjectURI=?");
1615                 comm.setString(1, URL);
1616                 comm.execute();
1617                 comm.close();
1618             }
1619             log.trace("DeleteFromDB 5 " + (System.currentTimeMillis() - now));
1620             con.close();
1621 
1622             if (r > 0) {
1623                 return true;
1624             }
1625 
1626         } // end DeleteFromDB
1627         catch (Exception ex) {
1628             log.log(Level.ERROR, null, ex);
1629         } finally {
1630             DBUtils.safeClose(comm);
1631             DBUtils.safeClose(comm2);
1632             DBUtils.safeClose(con);
1633             DBUtils.safeClose(con2);
1634         }
1635         log.trace("DeleteFromDB 6 " + (System.currentTimeMillis() - now));
1636         return false;
1637 
1638     } // end DeleteFromDB
1639 
1640     /**
1641      * returns an array of service policy
1642      *
1643      * @param w
1644      * @return null if none found
1645      */
1646     private ArrayOfServicePolicy getUDDIPoliciesFromDB(SecurityWrapper w) {
1647         Connection con = Utility.getConfigurationDBConnection();
1648         PreparedStatement comm = null;
1649         ResultSet results = null;
1650         try {
1651             ArrayOfServicePolicy ret = new ArrayOfServicePolicy();
1652 
1653             comm = con.prepareStatement("SELECT * from servicepolicies where hasfederation=true;");
1654             results = comm.executeQuery();
1655             XMLInputFactory xf = XMLInputFactory.newInstance();
1656             while (results.next()) {
1657                 PolicyType pt = PolicyType.values()[results.getInt("policytype")];
1658                 Unmarshaller um = jc.createUnmarshaller();
1659                 byte[] s = results.getBytes("xmlpolicy");
1660                 ServicePolicy t = null;
1661                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
1662                 XMLStreamReader r = xf.createXMLStreamReader(bss);
1663 
1664                 Class type = null;
1665                 switch (pt) {
1666                     case MACHINE:
1667                         type = MachinePolicy.class;
1668                         break;
1669                     case PROCESS:
1670                         type = ProcessPolicy.class;
1671                         break;
1672                     case STATISTICAL:
1673                         type = StatisticalServicePolicy.class;
1674                         break;
1675                     case STATUS:
1676                         type = StatusServicePolicy.class;
1677                         break;
1678                     case TRANSACTIONAL:
1679                         type = TransactionalWebServicePolicy.class;
1680                         break;
1681                 }
1682                 t = (ServicePolicy) JAXB.unmarshal(bss, type);
1683                 if (t != null) {
1684                     ret.getServicePolicy().add(t);
1685                 }
1686             }
1687 
1688             return ret;
1689         } catch (Exception ex) {
1690             log.log(Level.ERROR, "Error retrieving Federation Policies for services ", ex);
1691         } finally {
1692             DBUtils.safeClose(results);
1693             DBUtils.safeClose(comm);
1694             DBUtils.safeClose(con);
1695         }
1696         return null;
1697 
1698     }
1699 
1700     //one param or the other
1701     private GetServicePermissionsResponseMsg getServicePermissions(String URL, String username) throws ServiceUnavailableException {
1702         Connection con = null;
1703         PreparedStatement comm = null;
1704         ResultSet dt = null;
1705         try {
1706             if (Utility.stringIsNullOrEmpty(URL) && Utility.stringIsNullOrEmpty(username)) {
1707                 throw new IllegalArgumentException("URL or username must be specified");
1708             }
1709 
1710             GetServicePermissionsResponseMsg res = new GetServicePermissionsResponseMsg();
1711             con = Utility.getConfigurationDBConnection();
1712             if (Utility.stringIsNullOrEmpty(URL)) {
1713                 comm = con.prepareStatement("Select * from UserPermissions where Username=?;");
1714                 comm.setString(1, username);
1715             } else {
1716                 validatePolicyExists(URL);
1717                 comm = con.prepareStatement("Select * from UserPermissions where ObjectURI=?;");
1718                 comm.setString(1, URL);
1719             }
1720             dt = comm.executeQuery();
1721 
1722             ArrayOfUserServicePermissionType res2 = new ArrayOfUserServicePermissionType();
1723             UserServicePermissionType temp = null;
1724             while (dt.next()) {
1725                 temp = new UserServicePermissionType();
1726                 temp.setURL(dt.getString("ObjectURI"));
1727                 temp.setUser(dt.getString("username"));
1728                 boolean read = dt.getBoolean("ReadObject");
1729                 boolean write = dt.getBoolean("WriteObject");
1730                 boolean audit = dt.getBoolean("AuditObject");
1731                 boolean admin = dt.getBoolean("AdministerObject");
1732                 if (admin) {
1733                     temp.setRight(RightEnum.ADMINISTER);
1734                 } else if (audit) {
1735                     temp.setRight(RightEnum.AUDIT);
1736                 } else if (write) {
1737                     temp.setRight(RightEnum.WRITE);
1738                 } else if (read) {
1739                     temp.setRight(RightEnum.READ);
1740                 }
1741                 res2.getUserServicePermissionType().add(temp);
1742             }
1743             res.setRights(res2);
1744 
1745             res.setClassification(getCurrentOperatingClassificationLevel());
1746             return res;
1747         } catch (Exception ex) {
1748             log.log(Level.ERROR, "GetServicePermissionsUser", ex);
1749             return null;
1750         } finally {
1751             DBUtils.safeClose(dt);
1752             DBUtils.safeClose(comm);
1753             DBUtils.safeClose(con);
1754         }
1755 
1756     }
1757 
1758     private void removePermissionsFromDB(String uRL) throws ServiceUnavailableException {
1759         Connection con = null;
1760         PreparedStatement comm = null;
1761         try {
1762             if (Utility.stringIsNullOrEmpty(uRL)) {
1763                 throw new IllegalArgumentException("url");
1764             }
1765             con = Utility.getConfigurationDBConnection();
1766             comm = con.prepareStatement("DELETE FROM UserPermissions where ObjectURI=?");
1767             comm.setString(1, uRL);
1768             comm.execute();
1769 
1770         } catch (SQLException ex) {
1771             log.log(Level.ERROR, "Error removing old permission set from database for service uri " + uRL, ex);
1772             ServiceUnavailableException f = new ServiceUnavailableException("", null);
1773             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1774             throw f;
1775         } finally {
1776 
1777             DBUtils.safeClose(comm);
1778             DBUtils.safeClose(con);
1779         }
1780 
1781     }
1782 
1783     private void deleteAvailabilityData(String uRL) throws ServiceUnavailableException {
1784         Connection con = null;
1785         PreparedStatement comm = null;
1786 
1787         try {
1788             if (Utility.stringIsNullOrEmpty(uRL)) {
1789                 throw new IllegalArgumentException("url");
1790             }
1791             con = Utility.getConfigurationDBConnection();
1792             comm = con.prepareStatement("DELETE FROM status where uri=?");
1793             comm.setString(1, uRL);
1794             comm.execute();
1795         } catch (SQLException ex) {
1796             log.log(Level.ERROR, "Error removing availability from database for service uri " + uRL, ex);
1797             ServiceUnavailableException f = new ServiceUnavailableException("", null);
1798             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1799             throw f;
1800         } finally {
1801             DBUtils.safeClose(comm);
1802             DBUtils.safeClose(con);
1803 
1804         }
1805         try {
1806 
1807             con = Utility.getPerformanceDBConnection();
1808             comm = con.prepareStatement("delete from availability where uri=?");
1809             comm.setString(1, uRL);
1810             comm.execute();
1811         } catch (SQLException ex) {
1812             log.log(Level.ERROR, "Error removing availability from database for service uri " + uRL, ex);
1813             ServiceUnavailableException f = new ServiceUnavailableException("", null);
1814             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1815             throw f;
1816         } finally {
1817             DBUtils.safeClose(comm);
1818             DBUtils.safeClose(con);
1819         }
1820 
1821     }
1822 
1823     /**
1824      *
1825      *
1826      * Elevate the security classification level of fgsms
1827      *
1828      *
1829      *
1830      *
1831      *
1832      *
1833      *
1834      * @param request
1835      * @return returns
1836      * org.miloss.fgsms.services.interfaces.policyconfiguration.ElevateSecurityLevelResponseMsg
1837      * @throws AccessDeniedException
1838      * @throws ServiceUnavailableException
1839      */
1840     @WebMethod(operationName = "ElevateSecurityLevel", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/ElevateSecurityLevel")
1841     @WebResult(name = "ElevateSecurityLevelResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
1842     @RequestWrapper(localName = "ElevateSecurityLevel", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.ElevateSecurityLevel")
1843     @ResponseWrapper(localName = "ElevateSecurityLevelResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.ElevateSecurityLevelResponse")
1844     public ElevateSecurityLevelResponseMsg elevateSecurityLevel(
1845             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") ElevateSecurityLevelRequestMsg request)
1846             throws AccessDeniedException, ServiceUnavailableException {
1847         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1848         if (request == null) {
1849             throw new IllegalArgumentException("request is null");
1850         }
1851         Utility.validateClassification(request.getClassification());
1852 
1853         SecurityWrapper current = this.getCurrentOperatingClassificationLevel();
1854         String cc = (current.getClassification().value()) + " " + current.getCaveats();
1855         AuditLogger.logItem(this.getClass().getCanonicalName(), "elevateSecurityLevel", currentUser, "current classification:"
1856                 + cc + " requested level: " + (request.getClassification()), cc, ctx.getMessageContext());
1857 
1858         ElevateSecurityLevelResponseMsg res = new ElevateSecurityLevelResponseMsg();
1859         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "elevateSecurityLevel", current, ctx);
1860         /*
1861          * if
1862          * (request.getClassification().getClassification().compareTo(ClassificationType.U)
1863          * current) < 0) { throw new IllegalArgumentException(); }
1864          */
1865         //if we are current higher than confidential
1866         if (current.getClassification() != ClassificationType.U && current.getClassification() != ClassificationType.NU
1867                 && current.getClassification() != ClassificationType.NC && current.getClassification() != ClassificationType.C) {
1868             if (request.getClassification().getClassification() == ClassificationType.C
1869                     || request.getClassification().getClassification() == ClassificationType.NU
1870                     || request.getClassification().getClassification() == ClassificationType.NC
1871                     || request.getClassification().getClassification() == ClassificationType.U) {
1872                 AccessDeniedException ad = new AccessDeniedException("Currently classified, cannot declassify this system.", null);
1873                 AuditLogger.logItem(this.getClass().getCanonicalName(), "elevateSecurityLevel", currentUser, "current classification:"
1874                         + cc + " requested level: " + (request.getClassification()) + " DENY", cc, ctx.getMessageContext());
1875                 throw ad;
1876             }
1877         }
1878         Connection con = Utility.getConfigurationDBConnection();
1879         PreparedStatement prepareStatement = null;
1880         try {
1881 
1882             prepareStatement = con.prepareStatement("UPDATE globalpolicies  SET classification=?, caveat=?;");
1883             prepareStatement.setString(1, request.getClassification().getClassification().value());
1884             prepareStatement.setString(2, request.getClassification().getCaveats());
1885             prepareStatement.execute();
1886             res.setClassification(request.getClassification());
1887 
1888             return res;
1889         } catch (Exception ex) {
1890             log.log(Level.ERROR, "error elevating security level", ex);
1891 
1892         } finally {
1893             if (prepareStatement != null) {
1894                 try {
1895                     prepareStatement.close();
1896                 } catch (Exception ex) {
1897                     log.log(Level.DEBUG, "", ex);
1898                 }
1899             }
1900             if (con != null) {
1901                 try {
1902 
1903                     con.close();
1904                 } catch (Exception ex) {
1905                     log.log(Level.DEBUG, "", ex);
1906                 }
1907             }
1908         }
1909         ServiceUnavailableException f = new ServiceUnavailableException("", null);
1910         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1911         throw f;
1912     }
1913 
1914     /**
1915      *
1916      *
1917      * Get my email address
1918      *
1919      *
1920      *
1921      *
1922      *
1923      * @param request
1924      * @return returns
1925      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetMyEmailAddressResponseMsg
1926      * @throws AccessDeniedException
1927      * @throws ServiceUnavailableException
1928      */
1929     @WebMethod(operationName = "GetMyEmailAddress", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetMyEmailAddress")
1930     @WebResult(name = "GetMyEmailAddressResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
1931     @RequestWrapper(localName = "GetMyEmailAddress", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMyEmailAddress")
1932     @ResponseWrapper(localName = "GetMyEmailAddressResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMyEmailAddressResponse")
1933     public GetMyEmailAddressResponseMsg getMyEmailAddress(
1934             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetMyEmailAddressRequestMsg request)
1935             throws AccessDeniedException, ServiceUnavailableException {
1936 
1937         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1938 
1939         if (request == null) {
1940             throw new IllegalArgumentException("requested is null");
1941         }
1942         Utility.validateClassification(request.getClassification());
1943 
1944         AuditLogger.logItem(this.getClass().getCanonicalName(), "getMyEmailAddress", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1945 
1946         GetMyEmailAddressResponseMsg res = new GetMyEmailAddressResponseMsg();
1947         res.setClassification(getCurrentOperatingClassificationLevel());
1948 
1949         if (currentUser.equalsIgnoreCase("anonymous")) {
1950             return res;
1951         }
1952         Connection con = Utility.getConfigurationDBConnection();
1953         PreparedStatement comm = null;
1954         ResultSet rs = null;
1955         try {
1956 
1957             comm = con.prepareStatement("select email,email1,email2,email3 from users where username=?;");
1958             comm.setString(1, currentUser);
1959             rs = comm.executeQuery();
1960             if (rs.next()) {
1961                 //res.setEmail(rs.getString(1));
1962                 if (!Utility.stringIsNullOrEmpty(rs.getString("email"))) {
1963                     res.getEmail().add(rs.getString("email"));
1964                 }
1965                 if (!Utility.stringIsNullOrEmpty(rs.getString("email1"))) {
1966                     res.getEmail().add(rs.getString("email1"));
1967                 }
1968                 if (!Utility.stringIsNullOrEmpty(rs.getString("email2"))) {
1969                     res.getEmail().add(rs.getString("email2"));
1970                 }
1971                 if (!Utility.stringIsNullOrEmpty(rs.getString("email3"))) {
1972                     res.getEmail().add(rs.getString("email3"));
1973                 }
1974             }
1975 
1976             return res;
1977         } catch (SQLException ex) {
1978             log.log(Level.ERROR, null, ex);
1979             ServiceUnavailableException f = new ServiceUnavailableException("", null);
1980             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1981             throw f;
1982         } catch (Exception ex) {
1983             log.log(Level.ERROR, null, ex);
1984             ServiceUnavailableException f = new ServiceUnavailableException("", null);
1985             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
1986             throw f;
1987         } finally {
1988             if (rs != null) {
1989                 try {
1990                     rs.close();
1991                 } catch (Exception ex) {
1992                     log.log(Level.DEBUG, "", ex);
1993                 }
1994             }
1995             if (comm != null) {
1996                 try {
1997                     comm.close();
1998                 } catch (Exception ex) {
1999                     log.log(Level.DEBUG, "", ex);
2000                 }
2001             }
2002             if (con != null) {
2003                 try {
2004                     con.close();
2005                 } catch (Exception ex) {
2006                     log.log(Level.DEBUG, "", ex);
2007                 }
2008             }
2009         }
2010     }
2011 
2012     /**
2013      *
2014      *
2015      * sets my email address
2016      *
2017      *
2018      *
2019      *
2020      *
2021      * @param request
2022      * @return returns
2023      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetMyEmailAddressResponseMsg
2024      * @throws AccessDeniedException
2025      * @throws ServiceUnavailableException
2026      */
2027     @WebMethod(operationName = "SetMyEmailAddress", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetMyEmailAddress")
2028     @WebResult(name = "SetMyEmailAddressResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2029     @RequestWrapper(localName = "SetMyEmailAddress", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetMyEmailAddress")
2030     @ResponseWrapper(localName = "SetMyEmailAddressResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetMyEmailAddressResponse")
2031     public SetMyEmailAddressResponseMsg setMyEmailAddress(
2032             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetMyEmailAddressRequestMsg request)
2033             throws AccessDeniedException, ServiceUnavailableException {
2034         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2035         if (request == null) {
2036             throw new IllegalArgumentException("requested is null");
2037         }
2038         Utility.validateClassification(request.getClassification());
2039         AuditLogger.logItem(this.getClass().getCanonicalName(), "setMyEmailAddress", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2040 
2041         SetMyEmailAddressResponseMsg res = new SetMyEmailAddressResponseMsg();
2042         res.setClassification(getCurrentOperatingClassificationLevel());
2043 
2044         if (currentUser.equalsIgnoreCase("anonymous")) {
2045             return res;
2046         }
2047         Connection con = Utility.getConfigurationDBConnection();
2048         PreparedStatement prepareStatement = null;
2049         try {
2050 
2051             prepareStatement = con.prepareStatement("BEGIN WORK;"
2052                     + ";LOCK TABLE users IN ACCESS EXCLUSIVE MODE;"
2053                     + "INSERT INTO users (username)    SELECT  ?  WHERE NOT EXISTS"
2054                     + "(Select username from users where username=?);"
2055                     + "UPDATE users   SET email=?, email1=?, email2=?, email3=? WHERE username=?;"
2056                     + "COMMIT WORK;");
2057             prepareStatement.setString(1, currentUser);
2058             prepareStatement.setString(2, currentUser);
2059             if (request.getEmail().size() > 0) {
2060                 prepareStatement.setString(3, request.getEmail().get(0));
2061             } else {
2062                 prepareStatement.setNull(3, java.sql.Types.VARCHAR);
2063             }
2064 
2065             if (request.getEmail().size() > 1) {
2066                 prepareStatement.setString(4, request.getEmail().get(1));
2067             } else {
2068                 prepareStatement.setNull(4, java.sql.Types.VARCHAR);
2069             }
2070 
2071             if (request.getEmail().size() > 2) {
2072                 prepareStatement.setString(5, request.getEmail().get(2));
2073             } else {
2074                 prepareStatement.setNull(5, java.sql.Types.VARCHAR);
2075             }
2076 
2077             if (request.getEmail().size() > 3) {
2078                 prepareStatement.setString(6, request.getEmail().get(3));
2079             } else {
2080                 prepareStatement.setNull(6, java.sql.Types.VARCHAR);
2081             }
2082 
2083             prepareStatement.setString(7, currentUser);
2084             prepareStatement.execute();
2085 
2086             prepareStatement.close();
2087 
2088             return res;
2089         } catch (SQLException ex) {
2090             log.log(Level.ERROR, "error inserting user recorded to the database, attempting rollback", ex);
2091             PreparedStatement cmd = null;
2092             try {
2093                 cmd = con.prepareStatement("ROLLBACK WORK;");
2094                 cmd.execute();
2095             } catch (Exception e) {
2096                 log.log(Level.ERROR, "error attempting rollback", e);
2097             } finally {
2098                 if (cmd != null) {
2099                     try {
2100                         cmd.close();
2101                     } catch (Exception ex1) {
2102                         log.log(Level.DEBUG, "", ex);
2103                     }
2104                 }
2105             }
2106         } finally {
2107             if (prepareStatement != null) {
2108                 try {
2109                     prepareStatement.close();
2110                 } catch (SQLException ex) {
2111                     log.log(Level.DEBUG, "", ex);
2112                 }
2113             }
2114             try {
2115                 if (con != null && !con.isClosed()) {
2116                     con.close();
2117                 }
2118             } catch (Exception ex) {
2119                 log.log(Level.DEBUG, "", ex);
2120             }
2121         }
2122         ServiceUnavailableException f = new ServiceUnavailableException("", null);
2123         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2124         throw f;
2125     }
2126 
2127     /**
2128      *
2129      *
2130      * sets a list of SLAs that I am subscribed to
2131      *
2132      *
2133      *
2134      *
2135      *
2136      * @param request
2137      * @return returns
2138      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetAlertRegistrationsResponseMsg
2139      * @throws AccessDeniedException
2140      * @throws ServiceUnavailableException
2141      */
2142     @WebMethod(operationName = "SetAlertRegistrations", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetAlertRegistrations")
2143     @WebResult(name = "SetAlertRegistrationsResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2144     @RequestWrapper(localName = "SetAlertRegistrations", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAlertRegistrations")
2145     @ResponseWrapper(localName = "SetAlertRegistrationsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAlertRegistrationsResponse")
2146     public SetAlertRegistrationsResponseMsg setAlertRegistrations(
2147             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetAlertRegistrationsRequestMsg request)
2148             throws AccessDeniedException, ServiceUnavailableException {
2149         Connection con = null;
2150         try {
2151             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2152 
2153             if (request == null) {
2154                 throw new IllegalArgumentException("requested is null");
2155             }
2156             Utility.validateClassification(request.getClassification());
2157 
2158             AuditLogger.logItem(this.getClass().getCanonicalName(), "getAlertRegistrations", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2159 
2160             SetAlertRegistrationsResponseMsg res = new SetAlertRegistrationsResponseMsg();
2161             res.setClassification(getCurrentOperatingClassificationLevel());
2162 
2163             if (currentUser.equalsIgnoreCase("anonymous")) {
2164                 return res;
2165             }
2166 
2167             List<String> problemids = new ArrayList<String>();
2168             boolean ok = true;
2169             for (int i = 0; i < request.getItems().size(); i++) {
2170                 ServicePolicy p = SLACommon.LoadPolicyPooled(request.getItems().get(i).getServiceUri());//, request.getClassification(), currentUser, PolicyType.TRANSACTIONAL, null, null, false);
2171                 if (p == null) {
2172                     ok = false;
2173                     problemids.add(request.getItems().get(i).getServiceUri() + " " + request.getItems().get(i).getSLAID());
2174                     break;
2175                 } else {
2176                     boolean localok = false;
2177                     if (p.getServiceLevelAggrements() != null) {
2178                         for (int k = 0; k < p.getServiceLevelAggrements().getSLA().size(); k++) {
2179                             if (p.getServiceLevelAggrements().getSLA().get(k).getGuid().equalsIgnoreCase(request.getItems().get(i).getSLAID())) {
2180                                 if (containsEmailAction(p.getServiceLevelAggrements().getSLA().get(k))) {
2181                                     localok = true;
2182                                 }
2183                                 break;
2184                             }
2185                         }
2186                     }
2187                     if (!localok) {
2188                         ok = false;
2189                         problemids.add(request.getItems().get(i).getServiceUri() + " " + request.getItems().get(i).getSLAID());
2190                         break;
2191                     }
2192                 }
2193             }
2194             if (!ok) {
2195                 throw new IllegalArgumentException("All requested SLA subscription IDs must be already defined in an existing service policy and have SLA Email actions defined. Faulting items: " + Utility.listStringtoString(problemids));
2196             }
2197             con = Utility.getConfigurationDBConnection();
2198             //insert the new data
2199             PreparedStatement comm = con.prepareStatement("delete from slasub where username=?;");
2200             comm.setString(1, currentUser);
2201             comm.execute();
2202             comm.close();
2203             for (int i = 0; i < request.getItems().size(); i++) {
2204                 comm = con.prepareStatement("INSERT INTO slasub (slaid, username, uri)  VALUES (?, ? ,?);");
2205                 comm.setString(1, request.getItems().get(i).getSLAID());
2206                 comm.setString(2, currentUser);
2207                 comm.setString(3, request.getItems().get(i).getServiceUri());
2208                 comm.execute();
2209                 comm.close();
2210             }
2211             List<String> email = new ArrayList<String>();
2212             comm = con.prepareStatement("select email, email1, email2,email3 from users where username=?;");
2213             comm.setString(1, currentUser);
2214             ResultSet rs = comm.executeQuery();
2215             while (rs.next()) {
2216                 if (!Utility.stringIsNullOrEmpty(rs.getString(1))) {
2217                     if (!Utility.stringIsNullOrEmpty(rs.getString(1).trim())) {
2218                         email.add(rs.getString(1).trim());
2219                     }
2220                 }
2221             }
2222             rs.close();
2223             comm.close();
2224             con.close();
2225             SLACommon.AlertUserSLASubscribed(currentUser, email, request, true);
2226             return res;
2227         } catch (SQLException ex) {
2228             log.log(Level.ERROR, null, ex);
2229             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2230             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2231             throw f;
2232         } finally {
2233             try {
2234                 if (con != null && !con.isClosed()) {
2235                     con.close();
2236                 }
2237             } catch (Exception ex) {
2238             }
2239         }
2240     }
2241 
2242     /**
2243      *
2244      *
2245      * returns a list of SLAs that I am subscribed to
2246      *
2247      *
2248      *
2249      *
2250      *
2251      * @param request
2252      * @return returns
2253      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetAlertRegistrationsResponseMsg
2254      * @throws AccessDeniedException
2255      * @throws ServiceUnavailableException
2256      */
2257     @WebMethod(operationName = "GetAlertRegistrations", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetAlertRegistrations")
2258     @WebResult(name = "GetAlertRegistrationsResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2259     @RequestWrapper(localName = "GetAlertRegistrations", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAlertRegistrations")
2260     @ResponseWrapper(localName = "GetAlertRegistrationsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAlertRegistrationsResponse")
2261     @Override
2262     public GetAlertRegistrationsResponseMsg getAlertRegistrations(
2263             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetAlertRegistrationsRequestMsg request)
2264             throws AccessDeniedException, ServiceUnavailableException {
2265         Connection con = null;
2266         try {
2267             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2268             if (request == null) {
2269                 throw new IllegalArgumentException("requested is null");
2270             }
2271             AuditLogger.logItem(this.getClass().getCanonicalName(), "getAlertRegistrations", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2272 
2273             Utility.validateClassification(request.getClassification());
2274 
2275             GetAlertRegistrationsResponseMsg res = new GetAlertRegistrationsResponseMsg();
2276             res.setClassification(getCurrentOperatingClassificationLevel());
2277 
2278             if (currentUser.equalsIgnoreCase("anonymous")) {
2279                 return res;
2280             }
2281 
2282             con = Utility.getConfigurationDBConnection();
2283             PreparedStatement comm = con.prepareStatement("select * from slasub  where username=?;");
2284             comm.setString(1, currentUser);
2285             ResultSet rs = comm.executeQuery();
2286             while (rs.next()) {
2287                 SLAregistration re = new SLAregistration();
2288                 re.setSLAID(rs.getString("slaid"));
2289                 re.setServiceUri(rs.getString("uri"));
2290                 res.getItems().add(re);
2291             }
2292             rs.close();
2293             comm.close();
2294             con.close();
2295             return res;
2296         } catch (SQLException ex) {
2297             log.log(Level.ERROR, null, ex);
2298             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2299             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2300             throw f;
2301         } finally {
2302             try {
2303                 if (con != null && !con.isClosed()) {
2304                     con.close();
2305                 }
2306             } catch (Exception ex) {
2307             }
2308         }
2309     }
2310 
2311     /**
2312      *
2313      *
2314      * returns a list of all SLAs that the current user can subscribe to
2315      *
2316      *
2317      *
2318      *
2319      *
2320      *
2321      * @param request
2322      * @return returns
2323      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetAvailableAlertRegistrationsResponseMsg
2324      * @throws AccessDeniedException
2325      * @throws ServiceUnavailableException
2326      */
2327     @WebMethod(operationName = "GetAvailableAlertRegistrations", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetAvailableAlertRegistrations")
2328     @WebResult(name = "GetAvailableAlertRegistrationsResponseMsg", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2329     @RequestWrapper(localName = "GetAvailableAlertRegistrations", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAvailableAlertRegistrations")
2330     @ResponseWrapper(localName = "GetAvailableAlertRegistrationsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAvailableAlertRegistrationsResponse")
2331     public GetAvailableAlertRegistrationsResponseMsg getAvailableAlertRegistrations(
2332             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetAvailableAlertRegistrationsRequestMsg request)
2333             throws AccessDeniedException, ServiceUnavailableException {
2334         Connection con = null;
2335         PreparedStatement comm = null;
2336         ResultSet rs=null;
2337         try {
2338             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2339 
2340             if (request == null) {
2341                 throw new IllegalArgumentException("requested is null");
2342             }
2343 
2344             AuditLogger.logItem(this.getClass().getCanonicalName(), "getAlertRegistrations", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2345 
2346             Utility.validateClassification(request.getClassification());
2347             GetAvailableAlertRegistrationsResponseMsg res = new GetAvailableAlertRegistrationsResponseMsg();
2348             res.setClassification(getCurrentOperatingClassificationLevel());
2349 
2350             if (currentUser.equalsIgnoreCase("anonymous")) {
2351                 throw new IllegalArgumentException("Not supported for anonymous users");
2352             }
2353             con = Utility.getConfigurationDBConnection();
2354             HashMap svc = new HashMap();
2355             
2356             if (UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "getAvailableAlertRegistrations", currentLevel, ctx)) {
2357                 //get all services with an sla
2358                 comm = con.prepareStatement("select uri from servicepolicies where hassla=true order by uri desc;");
2359             } else {
2360                 //join on sla2 on userpermissions
2361                 comm = con.prepareStatement("select uri from servicepolicies, userpermissions where userpermissions.objecturi=servicepolicies.uri and username=? and "
2362                         + "(auditobject=true OR administerobject=true OR writeobject=true or readobject=true)  and  hassla=true order by uri desc;");
2363                 comm.setString(1, currentUser);
2364             }
2365             rs = comm.executeQuery();
2366             while (rs.next()) {
2367                 if (!svc.containsKey(rs.getString(1))) {
2368                     svc.put(rs.getString(1), "");
2369                 }
2370             }
2371             Iterator it = svc.keySet().iterator();
2372             while (it.hasNext()) {
2373                 //for (int i = 0; i < svc.size(); i++) {
2374                 ServicePolicy pol = this.getPolicyFromDB((String) it.next(), currentLevel, currentUser, null, null, null, false);
2375                 if (pol != null) {
2376                     if (Utility.hasEmailSLA(pol)) {
2377                         res.getServicePolicy().add(pol);
2378                     }
2379                 }
2380             }
2381             //load all policies from the list
2382             //check before adding to result set if an "emailaction" is an option
2383 
2384             return res;
2385         } catch (SQLException ex) {
2386             log.log(Level.ERROR, null, ex);
2387             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2388             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2389             throw f;
2390         } finally {
2391             DBUtils.safeClose(rs);
2392             DBUtils.safeClose(comm);
2393             DBUtils.safeClose(con);
2394         }
2395     }
2396 
2397     /**
2398      * validates that a policy exists, no changes are made if it does not
2399      *
2400      * @param uRL
2401      * @throws ServiceUnavailableException
2402      */
2403     private void validatePolicyExists(String uRL) throws ServiceUnavailableException {
2404         if (Utility.stringIsNullOrEmpty(uRL)) {
2405             throw new IllegalArgumentException("No url provided");
2406         }
2407         Connection con = null;
2408         try {
2409 
2410             con = Utility.getConfigurationDBConnection();
2411             PreparedStatement prepareStatement = con.prepareStatement("select * from servicepolicies where uri=?");
2412             prepareStatement.setString(1, uRL);
2413             ResultSet rs = prepareStatement.executeQuery();
2414             boolean ok = false;
2415             if (rs.next()) {
2416                 ok = true;
2417             }
2418             rs.close();
2419             prepareStatement.close();
2420             con.close();
2421             if (!ok) {
2422                 throw new IllegalArgumentException("The specified service is not registered");
2423             }
2424         } catch (SQLException ex) {
2425             log.log(Level.ERROR, "could find the policy for " + uRL + " due to an error", ex);
2426             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2427             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2428             throw f;
2429         } finally {
2430             try {
2431                 con.close();
2432             } catch (Exception ex) {
2433                 log.log(Level.DEBUG, "", ex);
2434             }
2435         }
2436 
2437     }
2438 
2439     /**
2440      * validates user identification parameters
2441      *
2442      * @param policy
2443      */
2444     private void validatePolicyByType(ServicePolicy policy) throws ServiceUnavailableException {
2445         if (policy == null || policy.getPolicyType() == null) {
2446             throw new IllegalArgumentException("null policy or policy type");
2447         }
2448         if (policy instanceof TransactionalWebServicePolicy) {
2449             TransactionalWebServicePolicy p = (TransactionalWebServicePolicy) policy;
2450 
2451             if (p.getUserIdentification() != null && !p.getUserIdentification().getUserIdentity().isEmpty()) {
2452                 for (int i = 0; i < p.getUserIdentification().getUserIdentity().size(); i++) {
2453                     if (p.getUserIdentification().getUserIdentity().get(i).isUseHttpHeader() != null
2454                             && p.getUserIdentification().getUserIdentity().get(i).isUseHttpHeader()
2455                             && (p.getUserIdentification().getUserIdentity().get(i).getHttpHeaderName() == null
2456                             || Utility.stringIsNullOrEmpty(p.getUserIdentification().getUserIdentity().get(i).getHttpHeaderName()))) {
2457                         throw new IllegalArgumentException("when specifying an http header as a user identity, the header name must be set");
2458                     }
2459                 }
2460             }
2461         }
2462 
2463         if (!Utility.stringIsNullOrEmpty(policy.getParentObject())) {
2464             this.validatePolicyExists(policy.getParentObject());
2465         }
2466     }
2467     private JAXBContext jc = null;
2468 
2469     private boolean containsEmailAction(SLA get) {
2470         if (get == null) {
2471             return false;
2472         }
2473         if (get.getAction() == null) {
2474             return false;
2475         }
2476         if (get.getAction().getSLAAction().isEmpty()) {
2477             return false;
2478         }
2479         for (int i = 0; i < get.getAction().getSLAAction().size(); i++) {
2480             if (get.getAction().getSLAAction().get(i).getImplementingClassName().equals(EmailAlerter.class.getCanonicalName())) {
2481                 return true;
2482             }
2483         }
2484         return false;
2485 
2486     }
2487 
2488     /**
2489      * Call before the new policy is written and before the old one is deleted
2490      * if the policy was set and an sla was removed, remove all SLA
2491      * subscriptions that were signed to that person and alert the person that
2492      * the SLA no longer exists
2493      *
2494      */
2495     private void validateExistingSLASubscriptions(ServicePolicy policy, String currentUser) {
2496         //get all existing slasubscriptions for the url
2497         //compare with new sla list
2498         //generate list of slasubscriptions for slaids that no longer exist
2499         //  for each item, remove sla and alert
2500         Connection config = null;
2501         PreparedStatement com = null;
2502         ResultSet rs = null;
2503         try {
2504 
2505             config = Utility.getConfigurationDBConnection();
2506             com = config.prepareStatement(
2507                     "SELECT \"slaid\", users.username as uid, email,email1,email2,email3  "
2508                     + "FROM slasub, users "
2509                     + "where slasub.username=users.username "
2510                     //+ "and sla2.id=slasub.slaid "
2511                     + "and slasub.uri=?");
2512 
2513             List<SLASubscriptionInfo> existingslas = new ArrayList<SLASubscriptionInfo>();
2514             //exist
2515             com.setString(1, policy.getURL());
2516             rs = com.executeQuery();
2517             while (rs.next()) {
2518                 SLASubscriptionInfo st = new SLASubscriptionInfo();
2519 
2520                 String id = rs.getString("slaid");
2521                 String subscribersUsername = rs.getString("uid");
2522                 String subscribersEmail = rs.getString("email");
2523                 st.id = id;
2524                 st.username = subscribersUsername;
2525                 st.email = new ArrayList<String>();
2526                 if (!Utility.stringIsNullOrEmpty(subscribersEmail)) {
2527                     st.email.add(subscribersEmail.trim());
2528                 }
2529                 subscribersEmail = rs.getString("email1");
2530                 if (!Utility.stringIsNullOrEmpty(subscribersEmail)) {
2531                     st.email.add(subscribersEmail.trim());
2532                 }
2533                 subscribersEmail = rs.getString("email2");
2534                 if (!Utility.stringIsNullOrEmpty(subscribersEmail)) {
2535                     st.email.add(subscribersEmail.trim());
2536                 }
2537                 subscribersEmail = rs.getString("email3");
2538                 if (!Utility.stringIsNullOrEmpty(subscribersEmail)) {
2539                     st.email.add(subscribersEmail.trim());
2540                 }
2541                 //
2542                 existingslas.add(st);
2543             }
2544 
2545             for (int i = 0; i < existingslas.size(); i++) {
2546                 if (notContainsSLAid(policy, existingslas.get(i).id)) {
2547                     deleteSLASubscription(existingslas.get(i).id);
2548                     SLACommon.AlertUserSLADeleted(currentUser, existingslas.get(i).username, existingslas.get(i).email, policy.getURL(), existingslas.get(i).id, true);
2549                 }
2550             }
2551 
2552         } catch (SQLException ex) {
2553             log.log(Level.ERROR, null, ex);
2554         } finally {
2555             if (rs != null) {
2556                 try {
2557                     rs.close();
2558                 } catch (Exception ex) {
2559                     log.log(Level.DEBUG, "", ex);
2560                 }
2561             }
2562             if (com != null) {
2563                 try {
2564                     com.close();
2565 
2566                 } catch (Exception ex) {
2567                     log.log(Level.DEBUG, "", ex);
2568                 }
2569             }
2570 
2571             if (config != null) {
2572                 try {
2573                     config.close();
2574                 } catch (Exception ex) {
2575                     log.log(Level.DEBUG, "", ex);
2576                 }
2577             }
2578         }
2579     }
2580 
2581     private boolean notContainsSLAid(ServicePolicy policy, String id) {
2582         if (policy == null) {
2583             throw new IllegalArgumentException("policy is null");
2584         }
2585         if (policy.getServiceLevelAggrements() == null || policy.getServiceLevelAggrements().getSLA().isEmpty()) {
2586             return true;
2587         }
2588         for (int i = 0; i < policy.getServiceLevelAggrements().getSLA().size(); i++) {
2589             if (policy.getServiceLevelAggrements().getSLA().get(i).getGuid().equalsIgnoreCase(id)) {
2590                 return false;
2591             }
2592         }
2593         return true;
2594     }
2595 
2596     private void deleteSLASubscription(String id) {
2597         Connection config = null;
2598         PreparedStatement com = null;
2599         try {
2600             config = Utility.getConfigurationDBConnection();
2601             com = config.prepareStatement("delete  FROM slasub where slaid=?");
2602             com.setString(1, id);
2603             com.executeUpdate();
2604         } catch (SQLException ex) {
2605             log.log(Level.WARN, "error caught removing sla subscription", ex);
2606         } finally {
2607             if (com != null) {
2608                 try {
2609                     com.close();
2610                 } catch (Exception ex) {
2611                     log.log(Level.DEBUG, "", ex);
2612                 }
2613             }
2614             if (config != null) {
2615                 try {
2616                     config.close();
2617                 } catch (Exception ex) {
2618                     log.log(Level.DEBUG, "", ex);
2619                 }
2620             }
2621         }
2622     }
2623 
2624     /**
2625      *
2626      *
2627      * returns a list of all user principles with the agent role, these are the
2628      * service level users that are allowed to request and set new service
2629      * policies and to add data to fgsms via the DCS
2630      *
2631      *
2632      *
2633      *
2634      *
2635      * @param request
2636      * @return returns
2637      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentPrinicplesResponseMsg
2638      * @throws AccessDeniedException
2639      * @throws ServiceUnavailableException
2640      */
2641     @WebMethod(operationName = "GetAgentPrinicples", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetAgentPrinicples")
2642     @WebResult(name = "GetAgentPrinicplesResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2643     @RequestWrapper(localName = "GetAgentPrinicples", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentPrinicples")
2644     @ResponseWrapper(localName = "GetAgentPrinicplesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentPrinicplesResponse")
2645     public GetAgentPrinicplesResponseMsg getAgentPrinicples(
2646             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetAgentPrinicplesRequestMsg request)
2647             throws AccessDeniedException, ServiceUnavailableException {
2648         Connection con = null;
2649         PreparedStatement comm = null;
2650         ResultSet results = null;
2651         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2652         if (request == null) {
2653             throw new IllegalArgumentException("request is null");
2654         }
2655         Utility.validateClassification(request.getClassification());
2656 
2657         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAdministrators", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2658         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getAgentPrinicples", currentLevel, ctx);
2659 
2660         try {
2661             //log.log(Level.INFO, "getAdministrators " + currentUser);
2662             //we don't care about the request in this case
2663             GetAgentPrinicplesResponseMsg response = new GetAgentPrinicplesResponseMsg();
2664             ArrayOfUserInfo list2 = new ArrayOfUserInfo();
2665             con = Utility.getConfigurationDBConnection();
2666             comm = con.prepareStatement("Select * from Users where rolecol='agent';");
2667             /////////////////////////////////////////////
2668             //get the global policy for data retension
2669             /////////////////////////////////////////////
2670             results = comm.executeQuery();
2671             while (results.next()) {
2672                 UserInfo u = new UserInfo();
2673                 u.setUsername(results.getString("Username"));
2674                 u.setRole("agent");
2675                 u.setDisplayName((results.getString("DisplayName")));
2676                 list2.getUserInfo().add(u);
2677             }
2678             response.setClassification(currentLevel);
2679             response.setUserList((list2));
2680 
2681             return response;
2682         } catch (SQLException ex) {
2683             log.log(Level.ERROR, "error setting fgsms admins", ex);
2684             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2685             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2686             throw f;
2687         } catch (Exception ex) {
2688             log.log(Level.ERROR, "error setting fgsms admins", ex);
2689             ServiceUnavailableException f = new ServiceUnavailableException("", null);
2690             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2691             throw f;
2692         } finally {
2693             DBUtils.safeClose(results);
2694             DBUtils.safeClose(comm);
2695             DBUtils.safeClose(con);
2696         }
2697     }
2698 
2699     /**
2700      *
2701      *
2702      * seta list of all user principles with the agent role, these are the
2703      * service level users that are allowed to request and set new service
2704      * policies and to add data to fgsms via the DCS all previous records are
2705      * replaced
2706      *
2707      *
2708      *
2709      *
2710      *
2711      * @param request
2712      * @return returns
2713      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetAgentPrinicplesResponseMsg
2714      * @throws AccessDeniedException
2715      * @throws ServiceUnavailableException
2716      */
2717     @WebMethod(operationName = "SetAgentPrinicples", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetAgentPrinicples")
2718     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2719     @RequestWrapper(localName = "SetAgentPrinicples", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAgentPrinicples")
2720     @ResponseWrapper(localName = "SetAgentPrinicplesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetAgentPrinicplesResponse")
2721     public SetAgentPrinicplesResponseMsg setAgentPrinicples(
2722             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetAgentPrinicplesRequestMsg request)
2723             throws AccessDeniedException, ServiceUnavailableException {
2724         Connection con = null;
2725         try {
2726             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2727             if (request == null) {
2728                 throw new IllegalArgumentException("request is null");
2729             }
2730             Utility.validateClassification(request.getClassification());
2731 
2732             AuditLogger.logItem(this.getClass().getCanonicalName(), "setAgentPrinicples", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2733 //            log.log(Level.INFO, "setAdministrator " + currentUser);
2734             UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "setAgentPrinicples", (request.getClassification()), ctx);
2735 
2736             if (request.getUserList() == null) {
2737                 log.log(Level.ERROR, "userlist null");
2738             }
2739             if (request.getUserList().getUserInfo() == null) {
2740                 log.log(Level.ERROR, "getuserinfo null");
2741             }
2742             if (request.getUserList().getUserInfo().isEmpty()) {
2743                 log.log(Level.ERROR, "getuserinfo is empty");
2744             }
2745             if (request.getUserList() == null
2746                     || request.getUserList().getUserInfo() == null
2747                     || request.getUserList().getUserInfo().isEmpty()) {
2748                 throw new IllegalArgumentException("userlist is empty or null");
2749             }
2750             con = Utility.getConfigurationDBConnection();
2751             PreparedStatement comm = con.prepareStatement("delete from Users where rolecol='agent';");
2752             comm.execute();
2753             /////////////////////////////////////////////
2754             //get the global policy for data retension
2755             /////////////////////////////////////////////
2756             for (int i = 0; i < request.getUserList().getUserInfo().size(); i++) {
2757                 comm = con.prepareStatement("INSERT INTO Users (Username, DisplayName,rolecol) VALUES (?,?,'agent');");
2758                 comm.setString(1, request.getUserList().getUserInfo().get(i).getUsername());
2759                 comm.setString(2, request.getUserList().getUserInfo().get(i).getDisplayName());
2760 
2761                 comm.execute();
2762             }
2763             comm.close();
2764             con.close();
2765             SetAgentPrinicplesResponseMsg ret = new SetAgentPrinicplesResponseMsg();
2766             ret.setClassification(currentLevel);
2767             return ret;
2768         } catch (SQLException ex) {
2769             log.log(Level.ERROR, "error setting fgsms admins", ex);
2770         } finally {
2771             DBUtils.safeClose(con);
2772         }
2773         ServiceUnavailableException f = new ServiceUnavailableException("", null);
2774         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2775         throw f;
2776     }
2777 
2778     /**
2779      * validates the SLAs included within a policy match the type of policy
2780      *
2781      * @param pol
2782      */
2783     private void validateSLAs(ServicePolicy pol) {
2784         if (pol == null) {
2785             return;
2786         }
2787         if (pol.getServiceLevelAggrements() == null || pol.getServiceLevelAggrements().getSLA().isEmpty()) {
2788             return;
2789         }
2790         AtomicReference<String> outmsg = new AtomicReference<String>();
2791         boolean isvalid = SLACommon.ValidateSLAs(outmsg, pol);
2792 
2793         //special case for access control on SLA Restart Action, admin required
2794         this.validateRestartRunScriptAsGlobalAdministrator(pol.getServiceLevelAggrements());
2795 
2796         if (!isvalid) {
2797             throw new IllegalArgumentException(outmsg.get());
2798         }
2799 
2800     }
2801 
2802     /**
2803      *
2804      *
2805      * gets mail settings that are used to deliver email for SLA alerts
2806      *
2807      *
2808      *
2809      *
2810      *
2811      *
2812      *
2813      * @param request
2814      * @return returns
2815      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetMailSettingsResponseMsg
2816      * @throws AccessDeniedException
2817      * @throws ServiceUnavailableException
2818      */
2819     @WebMethod(operationName = "GetMailSettings", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetMailSettings")
2820     @WebResult(name = "GetMailSettingsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2821     @RequestWrapper(localName = "GetMailSettings", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMailSettings")
2822     @ResponseWrapper(localName = "GetMailSettingsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMailSettingsResponse")
2823     public GetMailSettingsResponseMsg getMailSettings(
2824             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetMailSettingsRequestMsg request)
2825             throws AccessDeniedException, ServiceUnavailableException {
2826 
2827         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2828         if (request == null) {
2829             throw new IllegalArgumentException("request is null");
2830         }
2831         Utility.validateClassification(request.getClassification());
2832 
2833         AuditLogger.logItem(this.getClass().getCanonicalName(), "getMailSettings", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2834 //            log.log(Level.INFO, "setAdministrator " + currentUser);
2835         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMailSettings", (request.getClassification()), ctx);
2836 
2837         Connection con = null;
2838         PreparedStatement comm = null;
2839         ResultSet rs = null;
2840         try {
2841 
2842             GetMailSettingsResponseMsg response = new GetMailSettingsResponseMsg();
2843 
2844             con = Utility.getConfigurationDBConnection();
2845             comm = con.prepareStatement("select * from mail;");
2846             rs = comm.executeQuery();
2847             while (rs.next()) {
2848                 PropertiesList e = new PropertiesList();
2849                 e.setPropertyName(rs.getString("property"));
2850                 e.setPropertyValue(rs.getString("valuecol"));
2851                 response.getPropertiesList().add(e);
2852             }
2853 
2854             response.setClassification(currentLevel);
2855 
2856             return response;
2857         } catch (SQLException ex) {
2858             log.log(Level.ERROR, "error setting fgsms email settings", ex);
2859         } finally {
2860             DBUtils.safeClose(rs);
2861             DBUtils.safeClose(comm);
2862             DBUtils.safeClose(con);
2863         }
2864         ServiceUnavailableException f = new ServiceUnavailableException("", null);
2865         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2866         throw f;
2867 
2868     }
2869 
2870     /**
2871      *
2872      *
2873      * sets a list of all settings that are used for SLA email alerts requires
2874      * global admin rights
2875      *
2876      *
2877      *
2878      *
2879      *
2880      * @param request
2881      * @return returns
2882      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetMailSettingsResponseMsg
2883      * @throws AccessDeniedException
2884      * @throws ServiceUnavailableException
2885      */
2886     @WebMethod(operationName = "SetMailSettings", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetMailSettings")
2887     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
2888     @RequestWrapper(localName = "SetMailSettings", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetMailSettings")
2889     @ResponseWrapper(localName = "SetMailSettingsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetMailSettingsResponse")
2890     public SetMailSettingsResponseMsg setMailSettings(
2891             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetMailSettingsRequestMsg request)
2892             throws AccessDeniedException, ServiceUnavailableException {
2893         Connection con = null;
2894         PreparedStatement comm = null;
2895         try {
2896             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2897 
2898             if (request == null) {
2899                 throw new IllegalArgumentException("request is null");
2900             }
2901 
2902             Utility.validateClassification(request.getClassification());
2903 
2904             AuditLogger.logItem(this.getClass().getCanonicalName(), "setMailSettings", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2905 //            log.log(Level.INFO, "setAdministrator " + currentUser);
2906             UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "setMailSettings", (request.getClassification()), ctx);
2907 
2908             if (request.getPropertiesList() == null) {
2909                 log.log(Level.ERROR, "property list is null");
2910                 throw new IllegalArgumentException("request is null");
2911             }
2912             if (request.getPropertiesList() == null || request.getPropertiesList().isEmpty()) {
2913                 throw new IllegalArgumentException("request is null");
2914             }
2915             validateEmailSettings(request.getPropertiesList());
2916 
2917             con = Utility.getConfigurationDBConnection();
2918             StringBuilder sb = new StringBuilder();
2919 
2920             //Findbugs and other tools like it will flag this as potential sql injection
2921             //which it is not. move along...
2922             for (int i = 0; i < request.getPropertiesList().size(); i++) {
2923                 sb = sb.append("(?,?),");
2924             }
2925             String insert = sb.toString();
2926             insert = insert.substring(0, insert.length() - 1);
2927 
2928             comm = con.prepareStatement(
2929                     "DELETE FROM mail; INSERT INTO mail (property, valuecol) values "
2930                     + insert + "; ");
2931 
2932             for (int i = 0; i < request.getPropertiesList().size(); i++) {
2933                 //comm = con.prepareStatement("INSERT INTO Users (Username, DisplayName,Email,rolecol) VALUES (?,?,?,'agent');");
2934                 comm.setString((i * 2) + 1, Utility.truncate(request.getPropertiesList().get(i).getPropertyName(), 128));
2935                 comm.setString((i * 2) + 2, Utility.truncate(request.getPropertiesList().get(i).getPropertyValue(), 128));
2936             }
2937             comm.execute();
2938 
2939             SetMailSettingsResponseMsg ret = new SetMailSettingsResponseMsg();
2940             ret.setClassification(currentLevel);
2941             return ret;
2942         } catch (SQLException ex) {
2943             log.log(Level.ERROR, "error setting fgsms email settings", ex);
2944         } finally {
2945             DBUtils.safeClose(comm);
2946             DBUtils.safeClose(con);
2947         }
2948         ServiceUnavailableException f = new ServiceUnavailableException("", null);
2949         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2950         throw f;
2951     }
2952 
2953     private void validateEmailSettings(List<PropertiesList> propertiesList) {
2954         boolean founddefaultReplyAddress = false;
2955         boolean foundfgsmsgui = false;
2956         boolean foundMailhost = false;
2957         for (int i = 0; i < propertiesList.size(); i++) {
2958             if (propertiesList.get(i).getPropertyName().equalsIgnoreCase("fgsms.GUI.URL")) {
2959                 foundfgsmsgui = true;
2960             }
2961             if (propertiesList.get(i).getPropertyName().equalsIgnoreCase("defaultReplyAddress")) {
2962                 founddefaultReplyAddress = true;
2963             }
2964             if (propertiesList.get(i).getPropertyName().equalsIgnoreCase("mail.smtp.host")) {
2965                 foundMailhost = true;
2966             }
2967         }
2968         if (foundMailhost && foundfgsmsgui && founddefaultReplyAddress) {
2969             return;
2970         }
2971         throw new IllegalArgumentException("The properties list is missing one of (fgsms.GUI.URL, defaultReplyAddress, mail.smtp.host)");
2972     }
2973 
2974     private void deleteAllSLASubscriptions(final String uRL, final String currentUser) {
2975         Connection con = null;
2976         PreparedStatement com = null;
2977         ResultSet rs = null;
2978         try {
2979             con = Utility.getConfigurationDBConnection();
2980             com = con.prepareStatement(
2981                     "SELECT \"slaid\", users.username as uid, email,email1,email2,email3  "
2982                     + "FROM slasub, users "
2983                     + "where slasub.username=users.username "
2984                     + "and uri=?");
2985             com.setString(1, uRL);
2986             rs = com.executeQuery();
2987 
2988             while (rs.next()) {
2989                 final String id = rs.getString("slaid");
2990                 final String subscribersUsername = rs.getString("uid");
2991 
2992                 //idstodelete.add(id);
2993                 deleteSLASubscription(id);
2994                 final List<String> subscribersEmail = new ArrayList<String>();
2995                 String emaill = rs.getString("email");
2996                 if (!Utility.stringIsNullOrEmpty(emaill)) {
2997                     subscribersEmail.add(emaill.trim());
2998                 }
2999                 emaill = rs.getString("email1");
3000                 if (!Utility.stringIsNullOrEmpty(emaill)) {
3001                     subscribersEmail.add(emaill.trim());
3002                 }
3003                 emaill = rs.getString("email2");
3004                 if (!Utility.stringIsNullOrEmpty(emaill)) {
3005                     subscribersEmail.add(emaill.trim());
3006                 }
3007                 emaill = rs.getString("email3");
3008                 if (!Utility.stringIsNullOrEmpty(emaill)) {
3009                     subscribersEmail.add(emaill.trim());
3010                 }
3011 
3012                 alertingThreadPool.execute(new Runnable() {
3013                     @Override
3014                     public void run() {
3015                         SLACommon.AlertUserSLADeleted(currentUser, subscribersUsername, subscribersEmail, uRL, id, true);
3016                     }
3017                 });
3018 
3019             }
3020 
3021         } catch (Exception ex) {
3022             log.log(Level.WARN, "error caught deleting sla subscriptions", ex);
3023         } finally {
3024             DBUtils.safeClose(rs);
3025             DBUtils.safeClose(com);
3026             DBUtils.safeClose(con);
3027         }
3028 
3029         con = Utility.getConfigurationDBConnection();
3030         try {
3031             com = con.prepareStatement("delete from slasub where uri=?;");
3032             com.setString(1, uRL);
3033             com.execute();
3034         } catch (Exception ex) {
3035             log.log(Level.WARN, "error caught deleting sla subscriptions", ex);
3036         } finally {
3037             DBUtils.safeClose(com);
3038             DBUtils.safeClose(con);
3039         }
3040 
3041     }
3042 
3043     private void removeFromStatus(String uRL) {
3044         Connection config = null;
3045         PreparedStatement com = null;
3046         try {
3047             config = Utility.getConfigurationDBConnection();
3048             com = config.prepareStatement("delete from status where uri=?");
3049             com.setString(1, uRL);
3050             com.execute();;
3051 
3052         } catch (Exception ex) {
3053             log.log(Level.WARN, "trouble remove data from the status table.", ex);
3054         } finally {
3055             if (com != null) {
3056                 try {
3057                     com.close();
3058                 } catch (Exception ex) {
3059                     log.log(Level.DEBUG, "", ex);
3060                 }
3061             }
3062             if (config != null) {
3063                 try {
3064                     config.close();
3065                 } catch (Exception ex) {
3066                     log.log(Level.DEBUG, "", ex);
3067                 }
3068             }
3069         }
3070     }
3071 
3072     /**
3073      * sets a list of all settings that are used for fgsmss services requires
3074      * global admin rights or agent As of RC6
3075      *
3076      *
3077      * @param request
3078      * @return returns
3079      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetGeneralSettingsResponseMsg
3080      * @throws AccessDeniedException
3081      * @throws ServiceUnavailableException
3082      */
3083     @WebMethod(operationName = "GetGeneralSettings", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetGeneralSettings")
3084     @WebResult(name = "GetGeneralSettingsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3085     @RequestWrapper(localName = "GetGeneralSettings", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetGeneralSettings")
3086     @ResponseWrapper(localName = "GetGeneralSettingsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetGeneralSettingsResponse")
3087     public GetGeneralSettingsResponseMsg getGeneralSettings(
3088             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetGeneralSettingsRequestMsg request)
3089             throws AccessDeniedException, ServiceUnavailableException {
3090         Connection con = null;
3091         PreparedStatement comm = null;
3092         ResultSet rs = null;
3093         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3094         if (request == null) {
3095             throw new IllegalArgumentException("request is null");
3096         }
3097         Utility.validateClassification(request.getClassification());
3098         AuditLogger.logItem(this.getClass().getCanonicalName(), "getGeneralSettings", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3099         UserIdentityUtil.assertAdminOrAgentRole(currentUser, "getGeneralSettings", (request.getClassification()), ctx);
3100 
3101         try {
3102 
3103             con = Utility.getConfigurationDBConnection();
3104             if (Utility.stringIsNullOrEmpty(request.getKeyvalue())) {
3105                 comm = con.prepareStatement("select * from settings order by keycol asc;");
3106             } else {
3107                 comm = con.prepareStatement("select * from settings where keycol=?  order by namecol asc;");
3108                 comm.setString(1, request.getKeyvalue());
3109             }
3110             GetGeneralSettingsResponseMsg response = new GetGeneralSettingsResponseMsg();
3111 
3112             rs = comm.executeQuery();
3113             while (rs.next()) {
3114                 KeyNameValue e = new KeyNameValue();
3115                 e.setPropertyKey(rs.getString("keycol"));
3116                 e.setPropertyName(rs.getString("namecol"));
3117                 e.setPropertyValue(new String(rs.getBytes("valuecol"), Constants.CHARSET));
3118                 response.getKeyNameValue().add(e);
3119             }
3120 
3121             response.setClassification(currentLevel);
3122 
3123             return response;
3124         } catch (SQLException ex) {
3125             log.log(Level.ERROR, "error getting general settings", ex);
3126             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3127             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
3128             throw f;
3129         } catch (Exception ex) {
3130             log.log(Level.ERROR, "error getting general settings", ex);
3131             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3132             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3133             throw f;
3134         } finally {
3135             DBUtils.safeClose(rs);
3136             DBUtils.safeClose(comm);
3137             DBUtils.safeClose(con);
3138         }
3139 
3140     }
3141 
3142     /**
3143      *
3144      *
3145      * set 1 or more specific settings, previous values are overwritten, values
3146      * not specified in the request, if present, remain represent requires
3147      * global admin rights As of RC6
3148      *
3149      *
3150      *
3151      *
3152      *
3153      * @param request
3154      * @return returns
3155      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetGeneralSettingsResponseMsg
3156      * @throws AccessDeniedException
3157      * @throws ServiceUnavailableException
3158      */
3159     @WebMethod(operationName = "SetGeneralSettings", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetGeneralSettings")
3160     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3161     @RequestWrapper(localName = "SetGeneralSettings", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetGeneralSettings")
3162     @ResponseWrapper(localName = "SetGeneralSettingsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetGeneralSettingsResponse")
3163     public SetGeneralSettingsResponseMsg setGeneralSettings(
3164             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetGeneralSettingsRequestMsg request)
3165             throws AccessDeniedException, ServiceUnavailableException {
3166         Connection con = null;
3167         PreparedStatement comm = null;
3168         try {
3169             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3170             if (request == null) {
3171                 throw new IllegalArgumentException("request is null");
3172             }
3173             if (request.getKeyNameValueEnc().isEmpty()) {
3174                 throw new IllegalArgumentException("at least one setting must be specified");
3175             }
3176             for (int i = 0; i < request.getKeyNameValueEnc().size(); i++) {
3177                 if (request.getKeyNameValueEnc().get(i).getKeyNameValue() == null) {
3178                     throw new IllegalArgumentException("no value specified for item " + i);
3179                 }
3180                 if (Utility.stringIsNullOrEmpty(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyKey())
3181                         || Utility.stringIsNullOrEmpty(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyName())
3182                         || Utility.stringIsNullOrEmpty(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyValue())) {
3183                     throw new IllegalArgumentException("no parameter specified for either the key, name or value of item " + i);
3184                 }
3185             }
3186             Utility.validateClassification(request.getClassification());
3187             AuditLogger.logItem(this.getClass().getCanonicalName(), "setGeneralSettings", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3188             UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "setGeneralSettings", (request.getClassification()), ctx);
3189 
3190             con = Utility.getConfigurationDBConnection();
3191             for (int i = 0; i < request.getKeyNameValueEnc().size(); i++) {
3192                 comm = con.prepareStatement("delete from settings where keycol=? and namecol=?; "
3193                         + "INSERT INTO settings(keycol, namecol, valuecol, isencrypted)    VALUES (?, ?, ?, ?);");
3194                 comm.setString(1, Utility.truncate(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyKey().trim(), 128));
3195                 comm.setString(2, Utility.truncate(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyName().trim(), 128));
3196                 comm.setString(3, Utility.truncate(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyKey().trim(), 128));
3197                 comm.setString(4, Utility.truncate(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyName().trim(), 128));
3198                 if (request.getKeyNameValueEnc().get(i).isShouldEncrypt()) {
3199                     comm.setBytes(5, Utility.EN(request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyValue().trim()).getBytes(Constants.CHARSET));
3200                     comm.setBoolean(6, true);
3201                 } else {
3202                     comm.setBytes(5, request.getKeyNameValueEnc().get(i).getKeyNameValue().getPropertyValue().trim().getBytes(Constants.CHARSET));
3203                     comm.setBoolean(6, false);
3204                 }
3205                 comm.execute();
3206                 comm.close();
3207             }
3208 
3209             con.close();
3210             SetGeneralSettingsResponseMsg response = new SetGeneralSettingsResponseMsg();
3211             response.setClassification(currentLevel);
3212             return response;
3213         } catch (SQLException ex) {
3214             log.log(Level.ERROR, "error setting general settings", ex);
3215             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3216             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
3217             throw f;
3218         } catch (IllegalArgumentException ex) {
3219             throw ex;
3220         } catch (Exception ex) {
3221             log.log(Level.ERROR, "error setting general settings", ex);
3222             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3223             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3224             throw f;
3225         } finally {
3226 
3227             if (comm != null) {
3228                 try {
3229                     comm.close();
3230                 } catch (Exception ex) {
3231                     log.log(Level.DEBUG, "", ex);
3232                 }
3233             }
3234             if (con != null) {
3235                 try {
3236                     con.close();
3237                 } catch (Exception ex) {
3238                     log.log(Level.DEBUG, "", ex);
3239                 }
3240             }
3241         }
3242 
3243     }
3244 
3245     /**
3246      *
3247      *
3248      * removes 1 or more specific settings, previous values are discarded
3249      * requires global admin rights As of RC6
3250      *
3251      *
3252      *
3253      *
3254      *
3255      * @param request
3256      * @return returns
3257      * org.miloss.fgsms.services.interfaces.policyconfiguration.RemoveGeneralSettingsResponseMsg
3258      * @throws AccessDeniedException
3259      * @throws ServiceUnavailableException
3260      */
3261     @WebMethod(operationName = "RemoveGeneralSettings", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/RemoveGeneralSettings")
3262     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3263     @RequestWrapper(localName = "RemoveGeneralSettings", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.RemoveGeneralSettings")
3264     @ResponseWrapper(localName = "RemoveGeneralSettingsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.RemoveGeneralSettingsResponse")
3265     public RemoveGeneralSettingsResponseMsg removeGeneralSettings(
3266             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") RemoveGeneralSettingsRequestMsg request)
3267             throws AccessDeniedException, ServiceUnavailableException {
3268 
3269         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3270         if (request == null) {
3271             throw new IllegalArgumentException("request is null");
3272         }
3273         if (request.getKeyNameValue().isEmpty()) {
3274             throw new IllegalArgumentException("you must specify at least one item to remove");
3275         }
3276         for (int i = 0; i < request.getKeyNameValue().size(); i++) {
3277             if (request.getKeyNameValue().get(i) == null) {
3278                 throw new IllegalArgumentException("you must specify at least one item to remove for parameter " + i);
3279             }
3280             if (Utility.stringIsNullOrEmpty(request.getKeyNameValue().get(i).getPropertyKey()) || Utility.stringIsNullOrEmpty(request.getKeyNameValue().get(i).getPropertyName())) {
3281                 throw new IllegalArgumentException("you must specify a key and name for parameter " + i);
3282             }
3283         }
3284         Utility.validateClassification(request.getClassification());
3285 
3286         AuditLogger.logItem(this.getClass().getCanonicalName(), "removeGeneralSettings", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3287         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "removeGeneralSettings", (request.getClassification()), ctx);
3288 
3289         Connection con = null;
3290         PreparedStatement comm = null;
3291         try {
3292 
3293             con = Utility.getConfigurationDBConnection();
3294             for (int i = 0; i < request.getKeyNameValue().size(); i++) {
3295                 try {
3296                     comm = con.prepareStatement("delete from settings where keycol=? and namecol=?;");
3297                     comm.setString(1, request.getKeyNameValue().get(i).getPropertyKey());
3298                     comm.setString(2, request.getKeyNameValue().get(i).getPropertyName());
3299                     comm.execute();
3300                     comm.close();
3301                 } catch (Exception ex) {
3302                     throw ex;
3303                 } finally {
3304                     DBUtils.safeClose(comm);
3305                 }
3306             }
3307 
3308             RemoveGeneralSettingsResponseMsg response = new RemoveGeneralSettingsResponseMsg();
3309             response.setClassification(currentLevel);
3310             return response;
3311         } catch (SQLException ex) {
3312             log.log(Level.ERROR, "error removeGeneralSettings" + ex.getMessage());
3313             log.log(Level.DEBUG, "error removeGeneralSettings", ex);
3314             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3315             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
3316             throw f;
3317         } catch (Exception ex) {
3318             log.log(Level.ERROR, "error removeGeneralSettings" + ex.getMessage());
3319             log.log(Level.DEBUG, "error removeGeneralSettings", ex);
3320             ServiceUnavailableException f = new ServiceUnavailableException("", null);
3321             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3322             throw f;
3323         } finally {
3324             DBUtils.safeClose(comm);
3325             DBUtils.safeClose(con);
3326 
3327         }
3328 
3329     }
3330 
3331     /**
3332      *
3333      *
3334      * sets authentication credentials for a specific service, typically used
3335      * for connecting and obtaining status information only requires write
3336      * access permissions to the specified url As of RC6
3337      *
3338      *
3339      *
3340      *
3341      *
3342      * @param request
3343      * @return returns
3344      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetCredentialsResponseMsg
3345      * @throws AccessDeniedException
3346      * @throws ServiceUnavailableException
3347      */
3348     @WebMethod(operationName = "SetCredentials", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetCredentials")
3349     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3350     @RequestWrapper(localName = "SetCredentials", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetCredentials")
3351     @ResponseWrapper(localName = "SetCredentialsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetCredentialsResponse")
3352     public SetCredentialsResponseMsg setCredentials(
3353             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetCredentialsRequestMsg request)
3354             throws AccessDeniedException, ServiceUnavailableException {
3355         Connection con = null;
3356         PreparedStatement comm = null;
3357         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3358         if (request == null) {
3359             throw new IllegalArgumentException("request is null");
3360         }
3361         Utility.validateClassification(request.getClassification());
3362         if (Utility.stringIsNullOrEmpty(request.getUrl())) {
3363             throw new IllegalArgumentException("url is null");
3364         }
3365         if (Utility.stringIsNullOrEmpty(request.getUsername())) {
3366             throw new IllegalArgumentException("username is null");
3367         }
3368         if (Utility.stringIsNullOrEmpty(request.getPassword())) {
3369             throw new IllegalArgumentException("usernname or password is null");
3370         }
3371         if (request.getStyle() == null) {
3372             request.setStyle(TransportAuthenticationStyle.NA);
3373         }
3374         AuditLogger.logItem(this.getClass().getCanonicalName(), "setCredentials", currentUser, request.getUrl(), (request.getClassification()), ctx.getMessageContext());
3375         UserIdentityUtil.assertWriteAccess(request.getUrl(), currentUser, "setCredentials", (request.getClassification()), ctx);
3376         ServicePolicy policyFromDB = getPolicyFromDB(request.getUrl(), currentLevel, currentUser, null, null, null, false);
3377         if (policyFromDB == null) {
3378             throw new IllegalArgumentException("url is not a registered service");
3379         }
3380 
3381         try {
3382 
3383             con = Utility.getConfigurationDBConnection();
3384 
3385             comm = con.prepareStatement("delete from bueller where uri=?; "
3386                     + "INSERT INTO bueller(            uri, username, pwdcol, authtype)    VALUES (?, ?, ?, ?); ");
3387             comm.setString(1, request.getUrl());
3388             comm.setString(2, request.getUrl());
3389             comm.setString(3, request.getUsername());
3390 
3391             if (request.isPasswordEncrypted()) {
3392                 comm.setBytes(4, request.getPassword().getBytes(Constants.CHARSET));
3393             } else {
3394                 comm.setBytes(4, Utility.EN(request.getPassword()).getBytes(Constants.CHARSET));
3395             }
3396 
3397             comm.setInt(5, request.getStyle().ordinal());
3398             comm.execute();
3399 
3400             SetCredentialsResponseMsg response = new SetCredentialsResponseMsg();
3401             response.setClassification(currentLevel);
3402             return response;
3403         } catch (Exception ex) {
3404             log.log(Level.ERROR, "error setting setting credentials settings", ex);
3405         } finally {
3406             DBUtils.safeClose(comm);
3407             DBUtils.safeClose(con);
3408         }
3409         ServiceUnavailableException f = new ServiceUnavailableException("", null);
3410         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3411         throw f;
3412 
3413     }
3414 
3415     /**
3416      *
3417      *
3418      * removes authentication credentials for a specific service, typically used
3419      * for connecting and obtaining status information only requires write
3420      * access permissions to the specified url As of RC6
3421      *
3422      *
3423      *
3424      *
3425      *
3426      * @param request
3427      * @return returns
3428      * org.miloss.fgsms.services.interfaces.policyconfiguration.ClearCredentialsResponseMsg
3429      * @throws AccessDeniedException
3430      * @throws ServiceUnavailableException
3431      */
3432     @WebMethod(operationName = "ClearCredentials", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/ClearCredentials")
3433     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3434     @RequestWrapper(localName = "ClearCredentials", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.ClearCredentials")
3435     @ResponseWrapper(localName = "ClearCredentialsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.ClearCredentialsResponse")
3436     public ClearCredentialsResponseMsg clearCredentials(
3437             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") ClearCredentialsRequestMsg request)
3438             throws AccessDeniedException, ServiceUnavailableException {
3439         Connection con = null;
3440         PreparedStatement comm = null;
3441         try {
3442             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3443             if (request == null) {
3444                 throw new IllegalArgumentException("request is null");
3445             }
3446             Utility.validateClassification(request.getClassification());
3447             if (Utility.stringIsNullOrEmpty(request.getUrl())) {
3448                 throw new IllegalArgumentException("url is null");
3449             }
3450 
3451             AuditLogger.logItem(this.getClass().getCanonicalName(), "clearCredentials", currentUser, request.getUrl(), (request.getClassification()), ctx.getMessageContext());
3452             UserIdentityUtil.assertWriteAccess(request.getUrl(), currentUser, "clearCredentials", (request.getClassification()), ctx);
3453 
3454             con = Utility.getConfigurationDBConnection();
3455 
3456             comm = con.prepareStatement("delete from bueller where uri=?; ");
3457             comm.setString(1, request.getUrl());
3458             comm.execute();
3459             comm.close();
3460             con.close();
3461             ClearCredentialsResponseMsg response = new ClearCredentialsResponseMsg();
3462             response.setClassification(currentLevel);
3463             return response;
3464         } catch (SQLException ex) {
3465             log.log(Level.ERROR, "error setting  clearing credentials", ex);
3466         } finally {
3467             DBUtils.safeClose(comm);
3468             DBUtils.safeClose(con);
3469         }
3470         ServiceUnavailableException f = new ServiceUnavailableException("", null);
3471         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3472         throw f;
3473 
3474     }
3475     public static final String UNSPECIFIED = "unspecified";
3476 
3477     /**
3478      *
3479      *
3480      * provides infrastructure information, a list of all domains associated
3481      * with this fgsms instance As of RC6
3482      *
3483      *
3484      * @param request
3485      * @return returns
3486      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetDomainListResponseMsg
3487      * @throws AccessDeniedException
3488      * @throws ServiceUnavailableException
3489      */
3490     @WebMethod(operationName = "GetDomainList", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetDomainList")
3491     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3492     @RequestWrapper(localName = "GetDomainList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetDomainList")
3493     @ResponseWrapper(localName = "GetDomainListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetDomainListResponse")
3494     public GetDomainListResponseMsg getDomainList(
3495             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetDomainListRequestMsg request)
3496             throws AccessDeniedException, ServiceUnavailableException {
3497         Connection con = null;
3498         PreparedStatement comm = null;
3499         ResultSet rs = null;
3500 
3501         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3502         if (request == null) {
3503             throw new IllegalArgumentException("request is null");
3504         }
3505         Utility.validateClassification(request.getClassification());
3506         GetDomainListResponseMsg response = new GetDomainListResponseMsg();
3507         AuditLogger.logItem(this.getClass().getCanonicalName(), "getDomainList", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3508         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getDomainList", (request.getClassification()), ctx);
3509 
3510         try {
3511 
3512             con = Utility.getConfigurationDBConnection();
3513 
3514             comm = con.prepareStatement("select domaincol from servicepolicies group by domaincol; ");
3515             rs = comm.executeQuery();
3516             while (rs.next()) {
3517                 response.getDomains().add(rs.getString(1));
3518             }
3519 
3520             response.setClassification(currentLevel);
3521             return response;
3522         } catch (SQLException ex) {
3523             log.log(Level.ERROR, "error getting  getDomainList", ex);
3524         } finally {
3525             DBUtils.safeClose(rs);
3526             DBUtils.safeClose(comm);
3527             DBUtils.safeClose(con);
3528         }
3529         ServiceUnavailableException f = new ServiceUnavailableException("", null);
3530         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3531         throw f;
3532     }
3533 
3534     /**
3535      *
3536      *
3537      * provides infrastructure information, a list of all known hostnames
3538      * associated with this fgsms instance As of RC6
3539      *
3540      *
3541      *
3542      *
3543      *
3544      * @param request
3545      * @return returns
3546      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetMachinesByDomainResponseMsg
3547      * @throws ServiceUnavailableException
3548      * @throws AccessDeniedException
3549      */
3550     @WebMethod(operationName = "GetMachinesByDomain", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetMachinesByDomain")
3551     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3552     @RequestWrapper(localName = "GetMachinesByDomain", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMachinesByDomain")
3553     @ResponseWrapper(localName = "GetMachinesByDomainResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMachinesByDomainResponse")
3554     public GetMachinesByDomainResponseMsg getMachinesByDomain(
3555             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetMachinesByDomainRequestMsg request)
3556             throws AccessDeniedException, ServiceUnavailableException {
3557         Connection con = null;
3558         PreparedStatement comm = null;
3559         ResultSet rs = null;
3560         try {
3561             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3562             if (request == null) {
3563                 throw new IllegalArgumentException("request is null");
3564             }
3565             Utility.validateClassification(request.getClassification());
3566             if (Utility.stringIsNullOrEmpty(request.getDomain())) {
3567                 throw new IllegalArgumentException("a domain must be specified, or 'unspecified' must be given");
3568             }
3569             GetMachinesByDomainResponseMsg response = new GetMachinesByDomainResponseMsg();
3570             AuditLogger.logItem(this.getClass().getCanonicalName(), "getMachinesByDomain", currentUser, request.getDomain(), (request.getClassification()), ctx.getMessageContext());
3571             UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMachinesByDomain", (request.getClassification()), ctx);
3572 
3573             con = Utility.getConfigurationDBConnection();
3574 
3575             comm = con.prepareStatement("select hostname from servicepolicies where domaincol=? group by hostname; ");
3576             comm.setString(1, request.getDomain());
3577             rs = comm.executeQuery();
3578             while (rs.next()) {
3579                 response.getHostname().add(rs.getString(1));
3580             }
3581 
3582             response.setClassification(currentLevel);
3583             return response;
3584         } catch (SQLException ex) {
3585             log.log(Level.ERROR, "error getting  getMachinesByDomain", ex);
3586         } finally {
3587             DBUtils.safeClose(rs);
3588             DBUtils.safeClose(comm);
3589             DBUtils.safeClose(con);
3590         }
3591         ServiceUnavailableException f = new ServiceUnavailableException("", null);
3592         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3593         throw f;
3594     }
3595 
3596     /**
3597      *
3598      *
3599      * provides infrastructure information, a list of all known processes
3600      * associated with a given hostname requires global admin rights As of RC6
3601      *
3602      *
3603      *
3604      *
3605      *
3606      *
3607      * @param request
3608      * @return returns
3609      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetProcessesListByMachineResponseMsg
3610      * @throws ServiceUnavailableException
3611      * @throws AccessDeniedException
3612      */
3613     @WebMethod(operationName = "GetProcessesListByMachine", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetProcessesListByMachine")
3614     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3615     @RequestWrapper(localName = "GetProcessesListByMachine", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetProcessesListByMachine")
3616     @ResponseWrapper(localName = "GetProcessesListByMachineResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetProcessesListByMachineResponse")
3617     public GetProcessesListByMachineResponseMsg getProcessesListByMachine(
3618             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetProcessesListByMachineRequestMsg request)
3619             throws AccessDeniedException, ServiceUnavailableException {
3620 
3621         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3622         if (request == null) {
3623             throw new IllegalArgumentException("request is null");
3624         }
3625         Utility.validateClassification(request.getClassification());
3626 
3627         if (Utility.stringIsNullOrEmpty(request.getHostname())) {
3628             throw new IllegalArgumentException("a hostname must be specified");
3629         }
3630         AuditLogger.logItem(this.getClass().getCanonicalName(), "getProcessesListByMachine", currentUser, request.getHostname(), (request.getClassification()), ctx.getMessageContext());
3631         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getProcessesListByMachine", (request.getClassification()), ctx);
3632 
3633         try {
3634             return getMachineInfo(request.getHostname());
3635 
3636         } catch (Exception ex) {
3637             log.log(Level.ERROR, "error getting  getDomainList", ex);
3638         }
3639         ServiceUnavailableException f = new ServiceUnavailableException("", null);
3640         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3641         throw f;
3642     }
3643 
3644     /**
3645      * loads the last known configuration for a given machine
3646      *
3647      * @param hostname
3648      * @return
3649      */
3650     private GetProcessesListByMachineResponseMsg getMachineInfo(String hostname) throws Exception {
3651         Connection con = null;
3652         PreparedStatement comm = null;
3653         ResultSet rs = null;
3654         try {
3655 
3656             GetProcessesListByMachineResponseMsg response = new GetProcessesListByMachineResponseMsg();
3657 
3658             con = Utility.getConfigurationDBConnection();
3659 
3660             comm = con.prepareStatement("select * from machineinfo where hostname=?;");
3661             comm.setString(1, hostname);
3662             rs = comm.executeQuery();
3663             if (rs.next()) {
3664                 GregorianCalendar gcal = new GregorianCalendar();
3665                 gcal.setTimeInMillis(rs.getLong("lastchanged"));
3666                 response.setLastupdateat((gcal));
3667                 Unmarshaller u = jc.createUnmarshaller();
3668                 byte[] s = rs.getBytes("xmlcol");
3669 
3670                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
3671                 //1 = reader
3672                 //2 = writer
3673                 //                XMLStreamReaderImpl r = new XMLStreamReaderImpl(bss, new PropertyManager(1));
3674                 XMLInputFactory xf = XMLInputFactory.newInstance();
3675                 XMLStreamReader r = xf.createXMLStreamReader(bss);
3676 
3677                 JAXBElement<SetProcessListByMachineRequestMsg> foo = (JAXBElement<SetProcessListByMachineRequestMsg>) u.unmarshal(r, SetProcessListByMachineRequestMsg.class);
3678                 if (foo == null || foo.getValue() == null) {
3679                     log.log(Level.WARN, "xml is unexpectedly null or empty");
3680                 } else {
3681                     response.setMachineInformation(foo.getValue().getMachineInformation());
3682                     response.getProcessName().addAll(foo.getValue().getServices());
3683                 }
3684             }
3685             response.setClassification(currentLevel);
3686 
3687             return response;
3688         } catch (Exception ex) {
3689             throw ex;
3690         } finally {
3691             DBUtils.safeClose(rs);
3692             DBUtils.safeClose(comm);
3693             DBUtils.safeClose(con);
3694         }
3695     }
3696 
3697     /**
3698      *
3699      *
3700      * provides infrastructure information, a list of all known processes
3701      * associated with a given hostname requires agent rights As of RC6
3702      *
3703      *
3704      *
3705      *
3706      *
3707      *
3708      * @param request
3709      * @return returns
3710      * org.miloss.fgsms.services.interfaces.policyconfiguration.SetProcessListByMachineResponseMsg
3711      * @throws ServiceUnavailableException
3712      * @throws AccessDeniedException
3713      */
3714     @WebMethod(operationName = "SetProcessListByMachine", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/SetProcessListByMachine")
3715     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3716     @RequestWrapper(localName = "SetProcessListByMachine", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetProcessListByMachine")
3717     @ResponseWrapper(localName = "SetProcessListByMachineResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.SetProcessListByMachineResponse")
3718     public SetProcessListByMachineResponseMsg setProcessListByMachine(
3719             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") SetProcessListByMachineRequestMsg request)
3720             throws AccessDeniedException, ServiceUnavailableException {
3721 
3722         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3723         if (request == null) {
3724             throw new IllegalArgumentException("request is null");
3725         }
3726         Utility.validateClassification(request.getClassification());
3727         if (request.getMachineInformation() == null) {
3728             throw new IllegalArgumentException("a machine information must be specified, or 'unspecified' must be given");
3729         }
3730         if (Utility.stringIsNullOrEmpty(request.getMachineInformation().getHostname())) {
3731             throw new IllegalArgumentException("a hostname must be specified");
3732         }
3733         if (Utility.stringIsNullOrEmpty(request.getMachineInformation().getDomain())) {
3734             throw new IllegalArgumentException("a hostname must be specified");
3735         }
3736         Connection con = null;
3737         PreparedStatement comm = null;
3738         try {
3739             SetProcessListByMachineResponseMsg response = new SetProcessListByMachineResponseMsg();
3740             AuditLogger.logItem(this.getClass().getCanonicalName(), "setProcessListByMachine", currentUser, request.getMachineInformation().getHostname(), (request.getClassification()), ctx.getMessageContext());
3741             UserIdentityUtil.assertAgentRole(currentUser, "setProcessListByMachine", (request.getClassification()), ctx);
3742 
3743             con = Utility.getConfigurationDBConnection();
3744             //Marshaller m = null;
3745 
3746             //m = jc.createMarshaller();
3747             comm = con.prepareStatement(""
3748                     + "delete from machineinfo where hostname=?; "
3749                     + "INSERT INTO machineinfo(  xmlcol, hostname, domaincol, lastchanged)    "
3750                     + "VALUES (?, ?, ?, ?);");
3751             comm.setString(1, request.getMachineInformation().getHostname());
3752             StringWriter sw = new StringWriter();
3753             JAXB.marshal(request, sw);
3754             //m.marshal(request, sw);
3755             comm.setBytes(2, sw.toString().getBytes(Constants.CHARSET));
3756             comm.setString(3, request.getMachineInformation().getHostname());
3757             comm.setString(4, request.getMachineInformation().getDomain());
3758             comm.setLong(5, System.currentTimeMillis());
3759             comm.execute();
3760 
3761             try {
3762                 response.setClassification(currentLevel);
3763 
3764                 response.setMachinePolicy((MachinePolicy) getPolicyFromDB("urn:" + request.getMachineInformation().getHostname().toLowerCase() + ":system", currentLevel, currentUser, PolicyType.MACHINE, request.getMachineInformation().getHostname().toLowerCase(),
3765                         request.getMachineInformation().getDomain().toLowerCase(), true));
3766                 AuxHelper.TryUpdateStatus(true, "urn:" + request.getMachineInformation().getHostname().toLowerCase() + ":system", "online", true, PolicyType.MACHINE, request.getMachineInformation().getDomain(), request.getMachineInformation().getHostname());
3767                 response.getProcessPolicy().addAll(SLACommon.LoadProcessPoliciesPooledByHostname(request.getMachineInformation().getHostname()));
3768                 //     response.setCheckingFrequency(df.newDuration(1000*60*30));
3769                 KeyNameValueEnc s = DBSettingsLoader.GetPropertiesFromDB(true, "Agents.Process", "ReportingFrequency");
3770                 if (s != null && s.getKeyNameValue() != null) {
3771                     try {
3772                         long l = Long.parseLong(s.getKeyNameValue().getPropertyValue());
3773                         response.setReportingFrequency(df.newDuration(l));
3774                     } catch (Exception ex) {
3775                         response.setReportingFrequency(df.newDuration(1000 * 30));
3776                     }
3777                 } else {
3778                     response.setReportingFrequency(df.newDuration(1000 * 30));
3779                 }
3780 
3781             } catch (ClassCastException cs) {
3782                 log.log(Level.WARN, "error caught, this can mean that either service policy urls have collided or that something went haywire.", cs);
3783                 throw cs;
3784             } catch (Exception ex) {
3785                 log.log(Level.WARN, "error caught", ex);
3786                 throw ex;
3787             }
3788 
3789             if (!agents.containsKey(request.getAgentType())) {
3790                 agents.put(request.getAgentType(), true);
3791                 Connection config = Utility.getConfigurationDBConnection();
3792                 PreparedStatement com = null;
3793                 try {
3794                     com = config.prepareStatement("INSERT INTO agents(agenttype)  VALUES (?)");
3795                     com.setString(1, request.getAgentType());
3796                     com.execute();
3797                     log.log(Level.DEBUG, "PCS DEBUG adding agent type");
3798                 } catch (Exception ex) {
3799                     log.log(Level.DEBUG, "PCS DEBUG adding agent type FAILED");
3800                 } finally {
3801                     DBUtils.safeClose(com);
3802                     DBUtils.safeClose(config);
3803                 }
3804             }
3805 
3806             return response;
3807         } catch (Exception ex) {
3808             log.log(Level.ERROR, "error getting  setting the current machine information", ex);
3809         } finally {
3810 
3811             DBUtils.safeClose(comm);
3812             DBUtils.safeClose(con);
3813         }
3814         ServiceUnavailableException f = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
3815         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3816         throw f;
3817 
3818     }
3819     private static HashMap agents = new HashMap();
3820 
3821     /**
3822      *
3823      *
3824      * provides infrastructure information, a list of all known processes
3825      * associated with a given hostname requires agent rights As of RC6
3826      *
3827      *
3828      *
3829      *
3830      *
3831      *
3832      * @param request
3833      * @return returns
3834      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetMonitoredItemsByMachineResponseMsg
3835      * @throws AccessDeniedException
3836      * @throws ServiceUnavailableException
3837      */
3838     @WebMethod(operationName = "GetMonitoredItemsByMachine", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetMonitoredItemsByMachine")
3839     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3840     @RequestWrapper(localName = "GetMonitoredItemsByMachine", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMonitoredItemsByMachine")
3841     @ResponseWrapper(localName = "GetMonitoredItemsByMachineResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetMonitoredItemsByMachineResponse")
3842     public GetMonitoredItemsByMachineResponseMsg getMonitoredItemsByMachine(
3843             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetMonitoredItemsByMachineRequestMsg request)
3844             throws AccessDeniedException, ServiceUnavailableException {
3845         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3846         if (request == null) {
3847             throw new IllegalArgumentException("request is null");
3848         }
3849         Utility.validateClassification(request.getClassification());
3850         if (Utility.stringIsNullOrEmpty(request.getHostname())) {
3851             throw new IllegalArgumentException("a hostname must be specified");
3852         }
3853         GetMonitoredItemsByMachineResponseMsg response = new GetMonitoredItemsByMachineResponseMsg();
3854         AuditLogger.logItem(this.getClass().getCanonicalName(), "GetMonitoredItemsByMachineResponseMsg", currentUser, request.getHostname(), (request.getClassification()), ctx.getMessageContext());
3855         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "GetMonitoredItemsByMachineResponseMsg", (request.getClassification()), ctx);
3856 
3857         try {
3858             response.setClassification(currentLevel);
3859             response.setMachinePolicy(getMachinePolicyFromDB(request.getHostname()));
3860             response.getProcessPolicy().addAll(SLACommon.LoadProcessPoliciesPooledByHostname(request.getHostname()));
3861         } catch (Exception ex) {
3862             log.log(Level.WARN, "error caught", ex);
3863             ServiceUnavailableException f = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
3864             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3865             throw f;
3866         }
3867 
3868         return response;
3869     }
3870 
3871     /**
3872      * Get the operating status of this service
3873      *
3874      * @param request
3875      * @return returns
3876      * org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponseMessage
3877      */
3878     @WebMethod(operationName = "GetOperatingStatus", action = "urn:org:miloss:fgsms:services:interfaces:opStatusService/GetOperatingStatus")
3879     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common")
3880     @RequestWrapper(localName = "GetOperatingStatus", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common", className = "org.miloss.fgsms.services.interfaces.common.GetOperatingStatus")
3881     @ResponseWrapper(localName = "GetOperatingStatusResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common", className = "org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponse")
3882     public GetOperatingStatusResponseMessage getOperatingStatus(
3883             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common") GetOperatingStatusRequestMessage request) {
3884         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3885 
3886         Utility.validateClassification(request.getClassification());
3887         AuditLogger.logItem(this.getClass().getCanonicalName(), "getOperatingStatus", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3888 
3889         GetOperatingStatusResponseMessage res = new GetOperatingStatusResponseMessage();
3890 
3891         res.setClassification(request.getClassification());
3892         res.setVersionInfo(new GetOperatingStatusResponseMessage.VersionInfo());
3893         res.getVersionInfo().setVersionData(org.miloss.fgsms.common.Constants.Version);
3894         res.getVersionInfo().setVersionSource(org.miloss.fgsms.common.Constants.class.getCanonicalName());
3895         res.setStartedAt(started);
3896         boolean ok = true;
3897         Connection con = Utility.getConfigurationDBConnection();
3898         Connection con2 = Utility.getPerformanceDBConnection();
3899         PreparedStatement prepareStatement = null;
3900         PreparedStatement prepareStatement2 = null;
3901         try {
3902             prepareStatement = con.prepareStatement("select 1=1;");
3903             prepareStatement.execute();
3904 
3905             prepareStatement2 = con2.prepareStatement("select 1=1;");
3906             prepareStatement2.execute();
3907             res.setStatusMessage("OK");
3908         } catch (Exception ex) {
3909             ok = false;
3910             res.setStatusMessage("One or more of the database connections is available");
3911         } finally {
3912             DBUtils.safeClose(prepareStatement);
3913             DBUtils.safeClose(prepareStatement2);
3914             DBUtils.safeClose(con);
3915             DBUtils.safeClose(con2);
3916         }
3917 
3918         res.setStatus(ok);
3919         return res;
3920     }
3921 
3922     /**
3923      *
3924      *
3925      * returns a list of all administrative action for an agent to perform by
3926      * machine. Only applies to machine policy items, requires agent or global
3927      * administrative rights.
3928      *
3929      * As of 6.3
3930      *
3931      *
3932      *
3933      *
3934      *
3935      *
3936      * @param request
3937      * @return returns
3938      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentActionsByMachineResponseMsg
3939      * @throws ServiceUnavailableException
3940      * @throws AccessDeniedException
3941      */
3942     //@WebMethod(operationName = "GetAgentActionsByMachine", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetAgentActionsByMachine")
3943     //@WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
3944     //@RequestWrapper(localName = "GetAgentActionsByMachine", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentActionsByMachine")
3945     //@ResponseWrapper(localName = "GetAgentActionsByMachineResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetAgentActionsByMachineResponse")
3946     public GetAgentActionsByMachineResponseMsg getAgentActionsByMachine(
3947             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetAgentActionsByMachineRequestMsg request)
3948             throws AccessDeniedException, ServiceUnavailableException {
3949         return new GetAgentActionsByMachineResponseMsg();
3950         /*
3951          String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3952          if (request == null) {
3953          throw new IllegalArgumentException("request is null");
3954          }
3955          Utility.validateClassification(request.getClassification());
3956          if (Utility.stringIsNullOrEmpty(request.getHostname()) && Utility.stringIsNullOrEmpty(request.getUri())) {
3957          throw new IllegalArgumentException("a hostname or policy URI must be specified but not both");
3958          }
3959          if (!Utility.stringIsNullOrEmpty(request.getHostname()) && !Utility.stringIsNullOrEmpty(request.getUri())) {
3960          throw new IllegalArgumentException("a hostname or policy URI must be specified but not both");
3961          }
3962          GetAgentActionsByMachineResponseMsg response = new GetAgentActionsByMachineResponseMsg();
3963          AuditLogger.logItem(this.getClass().getCanonicalName(), "getAgentActionsByMachine", currentUser, request.getHostname(), (request.getClassification()), ctx.getMessageContext());
3964          UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getAgentActionsByMachine", (request.getClassification()), ctx);
3965 
3966          try {
3967          response.setClassification(currentLevel);
3968          if (!Utility.stringIsNullOrEmpty(request.getHostname())) {
3969          response.getAgentActions().addAll(GetAgentActionsByHostname(request.getHostname(), UserIdentityUtil.isTrustedAgent(currentUser, "getAgentActionsByMachine", request.getClassification(), ctx)));
3970          } else {
3971          response.getAgentActions().addAll(GetAgentActionsByPolicyURI(request.getUri(), UserIdentityUtil.isTrustedAgent(currentUser, "getAgentActionsByMachine", request.getClassification(), ctx)));
3972          }
3973          } catch (Exception ex) {
3974          log.log(Level.WARN, "error caught", ex);
3975          }
3976 
3977          return response;*/
3978     }
3979 
3980     /**
3981      *
3982      *
3983      * updates a administrative action for an agent to perform. Only applies to
3984      * machine policy items, requires agent rights.
3985      *
3986      * As of 6.3
3987      *
3988      *
3989      *
3990      *
3991      *
3992      *
3993      * @param request
3994      * @return returns
3995      * org.miloss.fgsms.services.interfaces.policyconfiguration.UpdateAgentActionResponseMsg
3996      * @throws ServiceUnavailableException
3997      * @throws AccessDeniedException
3998      */
3999     @WebMethod(operationName = "UpdateAgentAction", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/UpdateAgentAction")
4000     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
4001     @RequestWrapper(localName = "UpdateAgentAction", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.UpdateAgentAction")
4002     @ResponseWrapper(localName = "UpdateAgentActionResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.UpdateAgentActionResponse")
4003     public UpdateAgentActionResponseMsg updateAgentAction(
4004             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") UpdateAgentActionRequestMsg request)
4005             throws AccessDeniedException, ServiceUnavailableException {
4006         return null;
4007     }
4008 
4009     /**
4010      *
4011      *
4012      * deletes a list of administrative action for an agent to perform. Only
4013      * applies to machine policy items, requires global administrative rights.
4014      * actions must be in the completed state
4015      *
4016      * As of 6.3
4017      *
4018      *
4019      *
4020      *
4021      *
4022      *
4023      * @param request
4024      * @return returns
4025      * org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteAgentActionsResponseMsg
4026      * @throws ServiceUnavailableException
4027      * @throws AccessDeniedException
4028      */
4029     @WebMethod(operationName = "DeleteAgentActions", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/DeleteAgentActions")
4030     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
4031     @RequestWrapper(localName = "DeleteAgentActions", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteAgentActions")
4032     @ResponseWrapper(localName = "DeleteAgentActionsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.DeleteAgentActionsResponse")
4033     public DeleteAgentActionsResponseMsg deleteAgentActions(
4034             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") DeleteAgentActionsRequestMsg request)
4035             throws AccessDeniedException, ServiceUnavailableException {
4036         return null;
4037     }
4038 
4039     /**
4040      *
4041      *
4042      * creates a new administrative action for an agent to perform. Only applies
4043      * to machine policy items, requires global administrative rights
4044      *
4045      * As of 6.3
4046      *
4047      *
4048      *
4049      *
4050      *
4051      *
4052      * @param request
4053      * @return returns
4054      * org.miloss.fgsms.services.interfaces.policyconfiguration.CreateAgentActionResponseMsg
4055      * @throws ServiceUnavailableException
4056      * @throws AccessDeniedException
4057      */
4058     @WebMethod(operationName = "CreateAgentAction", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/CreateAgentAction")
4059     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
4060     @RequestWrapper(localName = "CreateAgentAction", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.CreateAgentAction")
4061     @ResponseWrapper(localName = "CreateAgentActionResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.CreateAgentActionResponse")
4062     public CreateAgentActionResponseMsg createAgentAction(
4063             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") CreateAgentActionRequestMsg request)
4064             throws AccessDeniedException, ServiceUnavailableException {
4065         return null;
4066     }
4067 
4068     /*    private List<AgentAction> GetAgentActionsByHostname(String hostname, boolean isagent) {
4069      }
4070 
4071      private List<AgentAction> GetAgentActionsByPolicyURI(String uri, boolean isagent) {
4072      Connection con = Utility.getConfigurationDBConnection();
4073      PreparedStatement cmd = con.prepareStatement("select * from agentmailbox where uri=?; ");
4074      cmd.setString(1, uri);
4075      ResultSet rs = cmd.executeQuery();
4076      while (rs.next()) {
4077      AgentAction a = new AgentAction();
4078      }
4079 
4080 
4081      }*/
4082     /**
4083      * Registers the existence of a new plugin. Note: this does not actually
4084      * copy files to the server(s) Permissions: global administrators only
4085      *
4086      * @param request
4087      * @return returns
4088      * org.miloss.fgsms.services.interfaces.policyconfiguration.RegisterPluginResponseMsg
4089      * @throws AccessDeniedException
4090      * @throws ServiceUnavailableException
4091      */
4092     @WebMethod(operationName = "RegisterPlugin", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/RegisterPlugin")
4093     @WebResult(name = "registerPluginResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters")
4094     @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
4095     public RegisterPluginResponse registerPlugin(
4096             @WebParam(name = "registerPlugin", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters") RegisterPlugin parameters)
4097             throws AccessDeniedException, ServiceUnavailableException {
4098         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
4099         if (parameters == null) {
4100             throw new IllegalArgumentException("request is null");
4101         }
4102         RegisterPluginRequestMsg request = parameters.getRequest();
4103         if (request == null) {
4104             throw new IllegalArgumentException("request is null");
4105         }
4106         if (request.getPlugin().isEmpty()) {
4107             throw new IllegalArgumentException("no plugins were specified");
4108         }
4109         Utility.validateClassification(request.getClassification());
4110         AuditLogger.logItem(this.getClass().getCanonicalName(), "registerPlugin", currentUser, "", (request.getClassification()), ctx.getMessageContext());
4111         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "registerPlugin", request.getClassification(), ctx);
4112         boolean registered = false;
4113 
4114         for (int i = 0; i < request.getPlugin().size(); i++) {
4115             if (Utility.stringIsNullOrEmpty(request.getPlugin().get(i).getClassname())) {
4116                 throw new IllegalArgumentException("plugin[" + i + "].classname is null");
4117             }
4118             //validate that the class name is a valid class name
4119             if (!ValidationTools.isValidPackageName(request.getPlugin().get(i).getClassname())) {
4120                 throw new IllegalArgumentException("plugin[" + i + "].classname is invalid");
4121             }
4122 
4123             if (Utility.stringIsNullOrEmpty(request.getPlugin().get(i).getPlugintype())) {
4124                 throw new IllegalArgumentException("plugin[" + i + "].type is null");
4125             }
4126 
4127             //first check to see if its already registered
4128             Connection con = Utility.getConfigurationDBConnection();
4129             PreparedStatement prepareStatement = null;
4130             ResultSet rs = null;
4131             try {
4132 
4133                 prepareStatement = con.prepareStatement("select * from plugins where classname=? and appliesto=?");
4134                 prepareStatement.setString(1, request.getPlugin().get(i).getClassname());
4135                 prepareStatement.setString(2, request.getPlugin().get(i).getPlugintype().toUpperCase());
4136                 rs = prepareStatement.executeQuery();
4137                 if (rs.next()) {
4138                     registered = true;
4139                 }
4140 
4141             } catch (Exception ex) {
4142                 log.error(ex);
4143             } finally {
4144                 DBUtils.safeClose(rs);
4145                 DBUtils.safeClose(prepareStatement);
4146                 DBUtils.safeClose(con);
4147 
4148             }
4149         }
4150         if (registered) {
4151             throw new IllegalArgumentException("one of more plugins are already registered");
4152         }
4153 
4154         for (int i = 0; i < request.getPlugin().size(); i++) {
4155             //create an instance of the plugin
4156             String displayname = null;
4157 
4158             try {
4159                 Class c = Class.forName(request.getPlugin().get(i).getClassname());
4160                 Object j = c.newInstance();
4161                 //FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
4162                 if (request.getPlugin().get(i).getPlugintype().equalsIgnoreCase("SLA_ACTION")) {
4163                     SLAActionInterface sla = (SLAActionInterface) j;
4164 
4165                     displayname = (sla.GetDisplayName());
4166 
4167                 } else if (request.getPlugin().get(i).getPlugintype().equalsIgnoreCase("SLA_RULE")) {
4168                     SLARuleInterface sla = (SLARuleInterface) j;
4169                     displayname = (sla.GetDisplayName());
4170 
4171                 } else if (request.getPlugin().get(i).getPlugintype().equalsIgnoreCase("FEDERATION_PUBLISH")) {
4172                     FederationInterface sla = (FederationInterface) j;
4173                     displayname = (sla.GetDisplayName());
4174 
4175                 } else {
4176                     throw new IllegalArgumentException("plugin[" + i + "].classname doesn't implement a known plugin interface type");
4177                 }
4178 
4179             } catch (InstantiationException ex) {
4180                 log.error("unable to load plugin " + request.getPlugin().get(i).getClassname(), ex);
4181                 throw new IllegalArgumentException("plugin is invalid");
4182             } catch (IllegalAccessException ex) {
4183                 log.error("unable to load plugin " + request.getPlugin().get(i).getClassname(), ex);
4184                 throw new IllegalArgumentException("plugin is invalid");
4185             } catch (ClassNotFoundException ex) {
4186                 log.error("unable to load plugin " + request.getPlugin().get(i).getClassname(), ex);
4187                 throw new IllegalArgumentException("plugin is invalid");
4188             } catch (Exception ex) {
4189                 log.error("The implementation for " + request.getPlugin().get(i).getClassname() + " is faulty and threw and exception. Please contact the developer for resolution", ex);
4190                 throw new IllegalArgumentException("plugin is invalid");
4191             }
4192             //pull data from it
4193 
4194             //insert into database
4195             Connection con = Utility.getConfigurationDBConnection();
4196             PreparedStatement prepareStatement = null;
4197             try {
4198                 prepareStatement = con.prepareStatement("INSERT INTO plugins(            classname, displayname, appliesto)    VALUES (?, ?, ?);");
4199                 prepareStatement.setString(1, request.getPlugin().get(i).getClassname());
4200                 prepareStatement.setString(2, displayname);
4201                 prepareStatement.setString(3, request.getPlugin().get(i).getPlugintype().toUpperCase());
4202                 prepareStatement.execute();
4203             } catch (Exception ex) {
4204 
4205                 ServiceUnavailableException f = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
4206                 f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
4207                 throw f;
4208 
4209             } finally {
4210                 DBUtils.safeClose(prepareStatement);
4211                 DBUtils.safeClose(con);
4212 
4213             }
4214         }
4215         //return success
4216         RegisterPluginResponseMsg res = new RegisterPluginResponseMsg();
4217         res.setClassification(getCurrentOperatingClassificationLevel());
4218 
4219         RegisterPluginResponse r = new RegisterPluginResponse();
4220         r.setResponse(res);
4221         return r;
4222     }
4223 
4224     /**
4225      * Unregisters the existence of a plugin. Plugins cannot be unregistered if
4226      * they are currently referenced from an existing policy. Note: this does
4227      * not actually remove files to the server(s) Permissions: global
4228      * administrators only
4229      *
4230      * @param request
4231      * @return returns
4232      * org.miloss.fgsms.services.interfaces.policyconfiguration.UnregisterPluginResponseMsg
4233      * @throws AccessDeniedException
4234      * @throws ServiceUnavailableException
4235      */
4236     @WebMethod(operationName = "UnregisterPlugin", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/UnregisterPlugin")
4237     @WebResult(name = "unregisterPluginResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters")
4238     @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
4239     public UnregisterPluginResponse unregisterPlugin(
4240             @WebParam(name = "unregisterPlugin", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters") UnregisterPlugin parameter) throws AccessDeniedException, ServiceUnavailableException {
4241 
4242         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
4243         if (parameter == null) {
4244             throw new IllegalArgumentException("request is null");
4245         }
4246         UnregisterPluginRequestMsg request = parameter.getRequest();
4247         if (request == null) {
4248             throw new IllegalArgumentException("request is null");
4249         }
4250         Utility.validateClassification(request.getClassification());
4251         AuditLogger.logItem(this.getClass().getCanonicalName(), "unregisterPlugin", currentUser, "", (request.getClassification()), ctx.getMessageContext());
4252         for (int i = 0; i < request.getPlugin().size(); i++) {
4253             if (Utility.stringIsNullOrEmpty(request.getPlugin().get(i).getClassname())) {
4254                 throw new IllegalArgumentException("plugin[" + i + "].classname is null");
4255             }
4256             if (Utility.stringIsNullOrEmpty(request.getPlugin().get(i).getPlugintype())) {
4257                 throw new IllegalArgumentException("plugin[" + i + "].type is null");
4258             }
4259         }
4260 
4261         UnregisterPluginResponseMsg res = new UnregisterPluginResponseMsg();
4262         res.setClassification(getCurrentOperatingClassificationLevel());
4263 
4264         boolean used = false;
4265         List<String> users_filtered = new ArrayList<String>();
4266         int usercount = 0;
4267         //check to see if its used
4268 
4269         List<ServicePolicy> sps = SLACommon.LoadServicePoliciesPooled();
4270         for (int i = 0; i < sps.size(); i++) {
4271             if (sps.get(i).getServiceLevelAggrements() != null
4272                     && sps.get(i).getServiceLevelAggrements().getSLA() != null) {
4273                 for (int k = 0; k < sps.get(i).getServiceLevelAggrements().getSLA().size(); k++) {
4274                     for (int x = 0; x < request.getPlugin().size(); x++) {
4275                         if (request.getPlugin().get(x).getPlugintype().equalsIgnoreCase("SLA_ACTION")) {
4276                             if (sps.get(i).getServiceLevelAggrements().getSLA().get(k).getAction() != null) {
4277                                 for (int j = 0; j < sps.get(i).getServiceLevelAggrements().getSLA().get(k).getAction().getSLAAction().size(); j++) {
4278                                     if (sps.get(i).getServiceLevelAggrements().getSLA().get(k).getAction().getSLAAction().get(j).getImplementingClassName().equalsIgnoreCase(
4279                                             request.getPlugin().get(x).getClassname())) {
4280                                         usercount++;
4281                                         if (UserIdentityUtil.hasReadAccess(currentUser, "unregisterPlugin", sps.get(i).getURL(), request.getClassification(), ctx)) {
4282                                             users_filtered.add(sps.get(i).getURL());
4283                                         }
4284                                         used = true;
4285                                     }
4286                                 }
4287                             }
4288                         } else if (request.getPlugin().get(x).getPlugintype().equalsIgnoreCase("SLA_RULE")) {
4289                             //TODO
4290                         } else if (request.getPlugin().get(x).getPlugintype().equalsIgnoreCase("SLA_FEDERATION")) {
4291                             //TODO
4292                         }
4293                     }
4294                 }
4295             }
4296         }
4297 
4298         if (used) {
4299             throw new IllegalArgumentException("Unable to unregister plugin, it is currently referenced from " + usercount + " service policies. Those service policies are "
4300                     + Utility.listStringtoString(users_filtered) + ". Note: this list may be filtered based on access control rules");
4301         }
4302         //remove it from db
4303         Connection con = Utility.getConfigurationDBConnection();
4304         PreparedStatement prepareStatement = null;
4305         int x = 0;
4306         try {
4307             for (int z = 0; z < request.getPlugin().size(); z++) {
4308                 try {
4309                     prepareStatement = con.prepareStatement("delete from plugins where appliesto=? and classname=?");
4310                     prepareStatement.setString(1, request.getPlugin().get(z).getPlugintype().toUpperCase());
4311                     prepareStatement.setString(2, request.getPlugin().get(z).getClassname());
4312                     x = prepareStatement.executeUpdate();
4313                 } catch (Exception ex) {
4314                     log.error(ex);
4315                     ServiceUnavailableException f = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
4316                     f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
4317                     throw f;
4318 
4319                 } finally {
4320                     DBUtils.safeClose(prepareStatement);
4321                 }
4322             }
4323 
4324         } catch (Exception ex) {
4325             log.error(ex);
4326             ServiceUnavailableException f = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
4327             f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
4328             throw f;
4329 
4330         } finally {
4331             DBUtils.safeClose(prepareStatement);
4332             DBUtils.safeClose(con);
4333 
4334         }
4335         if (x == 0) {
4336             log.fatal("DELETION from database failed! PCS unregisterPlugin!");
4337         }
4338         UnregisterPluginResponse unregisterPluginResponse = new UnregisterPluginResponse();
4339         unregisterPluginResponse.setResponse(res);
4340         return unregisterPluginResponse;
4341     }
4342 
4343     /**
4344      * Gets the current plugin list Permissions: All authenticated users
4345      *
4346      * @param request
4347      * @return returns
4348      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetPluginListResponseMsg
4349      * @throws AccessDeniedException
4350      * @throws ServiceUnavailableException
4351      */
4352     @WebMethod(operationName = "GetPluginList", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetPluginList")
4353     @WebResult(name = "getPluginListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters")
4354     @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
4355     public GetPluginListResponse getPluginList(
4356             @WebParam(name = "getPluginList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters") GetPluginList parameters) {
4357         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
4358         if (parameters == null) {
4359             throw new IllegalArgumentException("request is null");
4360         }
4361         GetPluginListRequestMsg request = parameters.getRequest();
4362         if (request == null) {
4363             throw new IllegalArgumentException("request is null");
4364         }
4365 
4366         Utility.validateClassification(request.getClassification());
4367         AuditLogger.logItem(this.getClass().getCanonicalName(), "getPluginList", currentUser, "", (request.getClassification()), ctx.getMessageContext());
4368 
4369         GetPluginListResponse r = new GetPluginListResponse();
4370 
4371         GetPluginListResponseMsg res = new GetPluginListResponseMsg();
4372         r.setResponse(res);
4373         res.setClassification(getCurrentOperatingClassificationLevel());
4374         Connection con = Utility.getConfigurationDBConnection();
4375         PreparedStatement prepareStatement = null;
4376         ResultSet rs = null;
4377         try {
4378             if (Utility.stringIsNullOrEmpty(request.getPlugintype())) {
4379                 prepareStatement = con.prepareStatement("select * from plugins");
4380             } else {
4381                 prepareStatement = con.prepareStatement("select * from plugins where appliesto=?");
4382                 prepareStatement.setString(1, request.getPlugintype().toUpperCase());
4383             }
4384             rs = prepareStatement.executeQuery();
4385             while (rs.next()) {
4386                 Class<PluginCommon> rule = (Class<PluginCommon>) Class.forName(rs.getString("classname"));
4387                 PluginCommon newInstance = rule.newInstance();
4388                 if (request.getOptionalPolicyTypeFilter() != null) {
4389                     try {
4390                         if (Utility.containsPolicyType(rule.newInstance().GetAppliesTo(), request.getOptionalPolicyTypeFilter())) {
4391                             res.getPlugins().add(Utility.newPlugin(rs.getString("classname"), newInstance.GetDisplayName(), rs.getString("appliesto")));
4392                         }
4393                     } catch (Exception ex) {
4394                         log.log(Level.ERROR, "problem creating instance of plugin" + rs.getString("classname"), ex);
4395                     }
4396                 } else {
4397                     res.getPlugins().add(Utility.newPlugin(rs.getString("classname"), newInstance.GetDisplayName(), rs.getString("appliesto")));
4398                 }
4399             }
4400 
4401         } catch (Exception ex) {
4402             log.error(ex);
4403         } finally {
4404             DBUtils.safeClose(rs);
4405             DBUtils.safeClose(prepareStatement);
4406             DBUtils.safeClose(con);
4407         }
4408         return r;
4409     }
4410 
4411     /**
4412      * Gets detailed information about a plugin, since 6.3 Permissions: all
4413      * authenticated users
4414      *
4415      * @param request
4416      * @return returns
4417      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetPluginInformationResponseMsg
4418      * @throws ServiceUnavailableException
4419      * @throws AccessDeniedException
4420      */
4421     @WebMethod(operationName = "GetPluginInformation", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetPluginInformation")
4422     @WebResult(name = "getPluginInformationResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters")
4423     @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
4424     public GetPluginInformationResponse getPluginInformation(
4425             @WebParam(name = "getPluginInformation", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", partName = "parameters") GetPluginInformation parameters)
4426             throws AccessDeniedException, ServiceUnavailableException {
4427 
4428         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
4429         if (parameters == null) {
4430             throw new IllegalArgumentException("request is null");
4431         }
4432         GetPluginInformationRequestMsg request = parameters.getRequest();
4433         if (request == null) {
4434             throw new IllegalArgumentException("request is null");
4435         }
4436         if (request.getGetPluginInformationRequestWrapper() == null) {
4437             throw new IllegalArgumentException("request is null");
4438         }
4439 
4440         Utility.validateClassification(request.getGetPluginInformationRequestWrapper().getClassification());
4441         AuditLogger.logItem(this.getClass().getCanonicalName(), "getPluginInformation", currentUser, "", (request.getGetPluginInformationRequestWrapper().getClassification()), ctx.getMessageContext());
4442 
4443         if (request.getGetPluginInformationRequestWrapper().getPlugin() == null) {
4444             throw new IllegalArgumentException("request is null");
4445         }
4446         //    for (int i = 0; i < request.getPlugin().size(); i++) {
4447         if (Utility.stringIsNullOrEmpty(request.getGetPluginInformationRequestWrapper().getPlugin().getClassname())) {
4448             throw new IllegalArgumentException("plugin[" + "].classname is empty");
4449         }
4450         if (Utility.stringIsNullOrEmpty(request.getGetPluginInformationRequestWrapper().getPlugin().getPlugintype())) {
4451             throw new IllegalArgumentException("plugin[" + "].plugintype is empty");
4452         }
4453         //  }
4454 
4455         GetPluginInformationResponse r = new GetPluginInformationResponse();
4456 
4457         GetPluginInformationResponseMsg res = new GetPluginInformationResponseMsg();
4458 
4459         res.setClassification(getCurrentOperatingClassificationLevel());
4460         //first, confirm that the requested plugin is registered
4461         boolean registered = false;
4462         Connection con = Utility.getConfigurationDBConnection();
4463         PreparedStatement prepareStatement = null;
4464         ResultSet rs = null;
4465         try {
4466             prepareStatement = con.prepareStatement("select * from plugins where classname=? and appliesto=?");
4467             prepareStatement.setString(1, request.getGetPluginInformationRequestWrapper().getPlugin().getClassname());
4468             prepareStatement.setString(2, request.getGetPluginInformationRequestWrapper().getPlugin().getPlugintype());
4469             rs = prepareStatement.executeQuery();
4470             if (rs.next()) {
4471                 registered = true;
4472             }
4473         } catch (Exception ex) {
4474             log.error(ex);
4475         } finally {
4476             DBUtils.safeClose(rs);
4477             DBUtils.safeClose(prepareStatement);
4478             DBUtils.safeClose(con);
4479         }
4480         if (registered) {
4481             try {
4482                 Class c = Class.forName(request.getGetPluginInformationRequestWrapper().getPlugin().getClassname());
4483                 Object j = c.newInstance();
4484                 if (request.getGetPluginInformationRequestWrapper().getPlugin().getPlugintype().equalsIgnoreCase("SLA_ACTION")) {
4485                     SLAActionInterface sla = (SLAActionInterface) j;
4486                     //res.setPlugintype(request.getPlugin().getPlugintype().toUpperCase());
4487                     res.setDisplayName(sla.GetDisplayName());
4488                     res.setHelp(sla.GetHtmlFormattedHelp());
4489                     res.getRequiredParameter().addAll(sla.GetRequiredParameters());
4490                     res.getOptionalParameter().addAll(sla.GetOptionalParameters());
4491 
4492                 }
4493                 //FEDERATION_PUBLISH,SLA_RULE,SLA_ACTION
4494                 if (request.getGetPluginInformationRequestWrapper().getPlugin().getPlugintype().equalsIgnoreCase("SLA_RULE")) {
4495                     SLARuleInterface sla = (SLARuleInterface) j;
4496                     // res.setPlugintype(request.getPlugin().getPlugintype().toUpperCase());
4497                     res.setDisplayName(sla.GetDisplayName());
4498                     res.setHelp(sla.GetHtmlFormattedHelp());
4499                     res.getRequiredParameter().addAll(sla.GetRequiredParameters());
4500                     res.getOptionalParameter().addAll(sla.GetOptionalParameters());
4501 
4502                 }
4503                 if (request.getGetPluginInformationRequestWrapper().getPlugin().getPlugintype().equalsIgnoreCase("FEDERATION_PUBLISH")) {
4504                     FederationInterface sla = (FederationInterface) j;
4505                     //    res.setPlugintype(request.getPlugin().getPlugintype().toUpperCase());
4506                     res.setDisplayName(sla.GetDisplayName());
4507                     res.setHelp(sla.GetHtmlFormattedHelp());
4508                     res.getRequiredParameter().addAll(sla.GetRequiredParameters());
4509                     res.getOptionalParameter().addAll(sla.GetOptionalParameters());
4510 
4511                 }
4512             } catch (InstantiationException ex) {
4513                 log.error("unable to load plugin " + request.getGetPluginInformationRequestWrapper().getPlugin().getClassname(), ex);
4514             } catch (IllegalAccessException ex) {
4515                 log.error("unable to load plugin " + request.getGetPluginInformationRequestWrapper().getPlugin().getClassname(), ex);
4516             } catch (ClassNotFoundException ex) {
4517                 log.error("unable to load plugin " + request.getGetPluginInformationRequestWrapper().getPlugin().getClassname(), ex);
4518             } catch (Exception ex) {
4519                 log.error("The implementation for " + request.getGetPluginInformationRequestWrapper().getPlugin().getClassname() + " is faulty and threw and exception. Please contact the developer for resolution", ex);
4520             }
4521         }
4522         r.setResponse(res);
4523         return r;
4524     }
4525 
4526     private void validateRestartRunScriptAsGlobalAdministrator(ArrayOfSLA serviceLevelAggrements) {
4527         if (serviceLevelAggrements == null) {
4528             return;
4529         }
4530 
4531         for (int i = 0; i < serviceLevelAggrements.getSLA().size(); i++) {
4532             for (int x = 0; x < serviceLevelAggrements.getSLA().get(i).getAction().getSLAAction().size(); x++) {
4533                 if (serviceLevelAggrements.getSLA().get(i).getAction().getSLAAction().get(x).getImplementingClassName().equalsIgnoreCase(SLAActionRestart.class.getCanonicalName())) {
4534                     UserIdentityUtil.assertGlobalAdministratorRole(UserIdentityUtil.getFirstIdentityToString(ctx), "ValidateRestartRunScriptAsGlobalAdministrator", currentLevel, ctx);
4535                 }
4536             }
4537         }
4538     }
4539 
4540     /**
4541      * Gets Html Formatted display of a given instance of a plugin, since 6.3
4542      *
4543      * @param request
4544      * @return returns
4545      * org.miloss.fgsms.services.interfaces.policyconfiguration.GetPluginHtmlFormattedDisplayResponseMsg
4546      * @throws AccessDeniedException
4547      * @throws ServiceUnavailableException
4548      */
4549     @WebMethod(operationName = "GetPluginHtmlFormattedDisplay", action = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration/policyConfigurationService/GetPluginHtmlFormattedDisplay")
4550     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration")
4551     @RequestWrapper(localName = "GetPluginHtmlFormattedDisplay", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetPluginHtmlFormattedDisplay")
4552     @ResponseWrapper(localName = "GetPluginHtmlFormattedDisplayResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration", className = "org.miloss.fgsms.services.interfaces.policyconfiguration.GetPluginHtmlFormattedDisplayResponse")
4553     public GetPluginHtmlFormattedDisplayResponseMsg getPluginHtmlFormattedDisplay(
4554             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:policyConfiguration") GetPluginHtmlFormattedDisplayRequestMsg request)
4555             throws AccessDeniedException, ServiceUnavailableException {
4556         throw new UnsupportedOperationException("Not supported yet.");
4557     }
4558 
4559     private void encryptIfNeeded(ServicePolicy policy) {
4560         if (policy == null) {
4561             return;
4562         }
4563         if (policy.getServiceLevelAggrements() == null) {
4564             return;
4565         }
4566         for (int i = 0; i < policy.getServiceLevelAggrements().getSLA().size(); i++) {
4567             SLA get = policy.getServiceLevelAggrements().getSLA().get(i);
4568             if (get.getAction() != null) {
4569                 Iterator<SLAAction> iterator = get.getAction().getSLAAction().iterator();
4570                 while (iterator.hasNext()) {
4571                     SLAAction next = iterator.next();
4572                     Iterator<NameValuePair> iterator1 = next.getParameterNameValue().iterator();
4573                     while (iterator1.hasNext()) {
4574                         NameValuePair next1 = iterator1.next();
4575                         if (next1.isEncryptOnSave()!=null && next1.isEncryptOnSave()) {
4576                             next1.setValue(Utility.EN(next1.getValue()));
4577                             next1.setEncrypted(true);
4578                             next1.setEncryptOnSave(false);
4579                         }
4580                     }
4581                 }
4582             }
4583             if (get.getRule() != null) {
4584                 if (get.getRule() instanceof SLARuleGeneric) {
4585                     SLARuleGeneric rule = (SLARuleGeneric) get.getRule();
4586                     Iterator<NameValuePair> iterator1 = rule.getParameterNameValue().iterator();
4587                     while (iterator1.hasNext()) {
4588                         NameValuePair next1 = iterator1.next();
4589                         if (next1.isEncryptOnSave()!=null && next1.isEncryptOnSave()) {
4590                             next1.setValue(Utility.EN(next1.getValue()));
4591                             next1.setEncrypted(true);
4592                             next1.setEncryptOnSave(false);
4593                         }
4594                     }
4595                 }
4596                 //TODO recursive and/or/not stuff
4597             }
4598 
4599         }
4600     }
4601     
4602     private void encryptIfNeeded(FederationPolicyCollection policy) {
4603         if (policy == null) {
4604             return;
4605         }
4606         if (policy.getFederationPolicy() == null) {
4607             return;
4608         }
4609         for (int i = 0; i < policy.getFederationPolicy().size(); i++) {
4610             FederationPolicy get = policy.getFederationPolicy().get(i);
4611             if (get.getParameterNameValue() != null) {
4612                 Iterator<NameValuePair> iterator1 = get.getParameterNameValue().iterator();
4613                 while (iterator1.hasNext()) {
4614 
4615                     NameValuePair next1 = iterator1.next();
4616                     if (next1.isEncryptOnSave() != null && next1.isEncryptOnSave()) {
4617                         next1.setValue(Utility.EN(next1.getValue()));
4618                         next1.setEncrypted(true);
4619                         next1.setEncryptOnSave(false);
4620                     }
4621                 }
4622             }
4623         }
4624     }
4625 
4626 }