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.das.impl;
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.UnsupportedEncodingException;
24  import java.math.BigInteger;
25  import java.sql.*;
26  import java.util.*;
27  import javax.annotation.Resource;
28  import javax.jws.*;
29  import javax.jws.soap.SOAPBinding;
30  import javax.xml.bind.JAXBContext;
31  import javax.xml.bind.JAXBElement;
32  import javax.xml.bind.Unmarshaller;
33  import javax.xml.datatype.DatatypeConfigurationException;
34  import javax.xml.datatype.DatatypeFactory;
35  import javax.xml.datatype.Duration;
36  import java.util.Calendar;
37  import javax.xml.stream.XMLInputFactory;
38  import javax.xml.stream.XMLStreamReader;
39  import javax.xml.ws.RequestWrapper;
40  import javax.xml.ws.ResponseWrapper;
41  import javax.xml.ws.WebServiceContext;
42  import javax.xml.ws.soap.MTOM;
43  import org.miloss.fgsms.common.AuditLogger;
44  import org.miloss.fgsms.common.DBSettingsLoader;
45  import org.miloss.fgsms.common.Constants;
46  import org.miloss.fgsms.common.UserIdentityUtil;
47  import org.miloss.fgsms.common.Utility;
48  import org.miloss.fgsms.services.interfaces.common.*;
49  import org.miloss.fgsms.services.interfaces.dataaccessservice.*;
50  import org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableFaultCodes;
51  import org.miloss.fgsms.services.interfaces.policyconfiguration.KeyNameValueEnc;
52  import org.miloss.fgsms.services.interfaces.policyconfiguration.MachinePolicy;
53  import org.miloss.fgsms.services.interfaces.policyconfiguration.ServicePolicy;
54  import org.miloss.fgsms.services.interfaces.policyconfiguration.SetProcessListByMachineRequestMsg;
55  import org.miloss.fgsms.sla.SLACommon;
56  import org.apache.log4j.Level;
57  import org.miloss.fgsms.common.Logger;;
58  import org.miloss.fgsms.common.DBUtils;
59  import us.gov.ic.ism.v2.ClassificationType;
60  
61  /**
62   * DataAccessService WSDL Interface implementation Provides access to all
63   * recorded data of fgsms to authorized users
64   *
65   * @author AO
66   */
67  @MTOM(enabled = false)
68  //@javax.ejb.Stateless
69  @WebService(serviceName = "dataAccessService", name = "DAS",
70          targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService"
71  //, wsdlLocation = "WEB-INF/wsdl/DASv8.wsdl"
72  )
73  @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.WRAPPED, use = SOAPBinding.Use.LITERAL)
74  public class DAS4jBean implements DataAccessService, OpStatusService {
75  
76      protected static final Logger log = Logger.getLogger("fgsms.DataAccessService");
77      @Resource
78      private WebServiceContext ctx;
79      protected static DatatypeFactory df = null;
80      private static JAXBContext jc = null;
81      private static ResourceBundle bundle = null;
82      private static Calendar started = null;
83  
84      public DAS4jBean() throws DatatypeConfigurationException {
85          SetupBundle();
86          init();
87      }
88  
89      private synchronized void SetupBundle() {
90          if (bundle == null) {
91              try {
92                  bundle = ResourceBundle.getBundle("org.miloss.fgsms.db/das", Locale.getDefault());
93              } catch (Exception ex) {
94                  log.log(Level.FATAL, "unable to load the resource bundle for " + "org.miloss.fgsms.db/das" + Locale.getDefault().toString(), ex);
95              }
96          }
97          if (bundle == null) {
98              try {
99                  bundle = ResourceBundle.getBundle("org.miloss.fgsms.db/das");
100             } catch (Exception ex) {
101                 log.log(Level.FATAL, "unable to load the resource bundle for " + "org.miloss.fgsms.db/das", ex);
102             }
103         }
104         if (bundle == null) {
105             log.log(Level.FATAL, "unable to load the resource bundle for " + "org.miloss.fgsms.db/das" + Locale.getDefault().toString());
106         } else {
107             log.log(Level.DEBUG, "resouce bundle loaded");
108         }
109     }
110 
111     /**
112      * constructor used for unit testing, do not remove
113      *
114      * @param w
115      */
116     protected DAS4jBean(WebServiceContext w) throws DatatypeConfigurationException {
117         SetupBundle();
118         init();
119         ctx = w;
120     }
121 
122     private synchronized void init() throws DatatypeConfigurationException {
123         if (df == null) {
124             df = DatatypeFactory.newInstance();
125         }
126 
127         try {
128             jc = Utility.getSerializationContext();
129         } catch (Exception ex) {
130             log.log(Level.FATAL, bundle.getString("JAXBException"), ex);
131         }
132         if (started == null) {
133             GregorianCalendar gcal = new GregorianCalendar();
134             gcal.setTimeInMillis(System.currentTimeMillis());
135             started = (gcal);
136         }
137     }
138 
139     /**
140      *
141      *
142      * Get Average Performance Statistics For a Service
143      *
144      * Global admins see everything Regular users can only see what they have
145      * access to
146      *
147      * @param getAlertsRequest
148      * @return returns
149      * java.util.List<org.miloss.fgsms.services.interfaces.dataaccessservice.GetAlertsResponseMsg>
150      * @throws ServiceUnavailableException
151      * @throws AccessDeniedException
152      */
153     @WebMethod(operationName = "GetAlerts", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAlerts")
154     @WebResult(name = "GetAlertsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
155     @RequestWrapper(localName = "GetAlerts", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAlerts")
156     @ResponseWrapper(localName = "GetAlertsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAlertsResponse")
157     public List<GetAlertsResponseMsg> getAlerts(
158             @WebParam(name = "GetAlertsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAlertsRequestMsg getAlertsRequest)
159             throws AccessDeniedException, ServiceUnavailableException {
160         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
161         if (getAlertsRequest == null) {
162             throw new IllegalArgumentException(bundle.getString("NullRequestMessage"));
163         }
164 
165         Utility.validateClassification(getAlertsRequest.getClassification());
166         AuditLogger.logItem(this.getClass().getCanonicalName(), "GetAlerts", currentUser, "", (getAlertsRequest.getClassification()), ctx.getMessageContext());
167         if (getAlertsRequest.getRecordcount() <= 0 || getAlertsRequest.getRecordcount() > 1000) {
168             throw new IllegalArgumentException(bundle.getString("InvalidRecordCount"));
169         }
170 
171         long offset = 0;
172         if (getAlertsRequest.getOffset() > 0) {
173             offset = getAlertsRequest.getOffset();
174         }
175 
176         SecurityWrapper level = (getCurrentClassificationLevel());
177         List<GetAlertsResponseMsg> ret = new ArrayList<GetAlertsResponseMsg>();
178         GetAlertsResponseMsg t = new GetAlertsResponseMsg();
179         Connection config = Utility.getConfigurationDBConnection();;
180         Connection con = Utility.getPerformanceDBConnection();
181         GregorianCalendar cal = null;
182 
183         long timelimit = System.currentTimeMillis();
184         GregorianCalendar now = new GregorianCalendar();
185         now.setTimeInMillis(timelimit);
186         now.add(GregorianCalendar.HOUR, -1);
187         timelimit = now.getTimeInMillis();
188 
189         try {
190             //get list of all monitored services that i have access to
191             //put last x records for sla faults for all services
192             //pull last x message faults
193             //pull last status of monitored services, those that are not 'ok' add to list
194 
195             List<AlertHelper> list = new LinkedList<AlertHelper>();
196             ArrayOfServiceType GetServiceListfromPolicyDB = DASHelper.getServiceListfromPolicyDB(ctx, (getAlertsRequest.getClassification()));
197             if (GetServiceListfromPolicyDB != null && !GetServiceListfromPolicyDB.getServiceType().isEmpty()) {
198 
199                 for (int i = 0; i < GetServiceListfromPolicyDB.getServiceType().size(); i++) {
200                     PreparedStatement com = null;
201                     ResultSet rs = null;
202                     try {
203                         com = con.prepareStatement(
204                                 //bundle.getString("GetSLAVioliations"));
205                                 "SELECT utcdatetime, msg, uri, relatedtransaction, incidentid FROM slaviolations "
206                                 + "where (uri = ?) and (utcdatetime > ?) order by utcdatetime desc limit ? offset ?;");
207                         com.setLong(4, offset);
208                         com.setLong(3, getAlertsRequest.getRecordcount());
209                         com.setLong(2, timelimit);
210                         com.setString(1, GetServiceListfromPolicyDB.getServiceType().get(i).getURL());
211 
212                         rs = com.executeQuery();
213                         while (rs.next()) {
214                             AlertHelper hj = new AlertHelper();
215                             byte[] b = rs.getBytes("msg");
216                             if (b != null && b.length > 0) {
217                                 hj.message = new String(b, Constants.CHARSET);
218                             } else {
219                                 hj.message = "";
220                             }
221                             hj.timestamp = rs.getLong("utcdatetime");
222                             hj.url = GetServiceListfromPolicyDB.getServiceType().get(i).getURL();
223                             hj.type = AlertType.SLA_FAULT;
224                             hj.tid = rs.getString("relatedtransaction");
225                             list.add(hj);
226                         }
227                     } catch (Exception ex) {
228                         log.log(Level.WARN, "", ex);
229                     } finally {
230                         DBUtils.safeClose(rs);
231                         DBUtils.safeClose(com);
232                     }
233 
234                     try {
235                         com = con.prepareStatement("SELECT transactionid, utcdatetime FROM rawdata where uri=? and success=false and "
236                                 + "utcdatetime > ? "
237                                 + "order by utcdatetime desc limit ?;");
238                         com.setLong(3, getAlertsRequest.getRecordcount());
239                         com.setLong(2, timelimit);
240                         com.setString(1, GetServiceListfromPolicyDB.getServiceType().get(i).getURL());
241 
242                         rs = com.executeQuery();
243                         while (rs.next()) {
244                             AlertHelper hj = new AlertHelper();
245                             hj.message = "";
246                             hj.timestamp = rs.getLong("utcdatetime");
247                             hj.tid = rs.getString("transactionid");
248                             hj.url = GetServiceListfromPolicyDB.getServiceType().get(i).getURL();
249                             hj.type = AlertType.MESSAGE_FAULT;
250                             list.add(hj);
251                         }
252                     } catch (Exception ex) {
253                         log.log(Level.WARN, "", ex);
254                     } finally {
255                         DBUtils.safeClose(rs);
256                         DBUtils.safeClose(com);
257                     }
258 
259 //      I'm not sure why there was an extra filter here
260                     //removed 1-21-2012com = config.prepareStatement("select * from status where uri=? and status <> true and monitored = true;");
261                     try {
262                         com = config.prepareStatement("select * from status where uri=? and status =false;");
263                         com.setString(1, GetServiceListfromPolicyDB.getServiceType().get(i).getURL());
264                         rs = com.executeQuery();
265                         if (rs.next()) {
266                             boolean up = rs.getBoolean("status");
267                             if (!up) {
268                                 AlertHelper hj = new AlertHelper();
269                                 hj.message = rs.getString("message");
270                                 if (hj.message == null) {
271                                     hj.message = "";
272                                 }
273                                 hj.timestamp = rs.getLong("utcdatetime");
274                                 hj.url = rs.getString("uri");
275                                 hj.type = AlertType.OPERATING_STATUS;
276 
277                                 list.add(hj);
278                             }
279                         }
280                     } catch (Exception ex) {
281                         log.log(Level.WARN, "", ex);
282                     } finally {
283                         DBUtils.safeClose(rs);
284                         DBUtils.safeClose(com);
285                     }
286 
287                 }
288 
289             }
290             Collections.sort(list, new AlertTypeComparator());
291             Iterator e = list.iterator();
292 
293             int count = 0;
294             while (e.hasNext() && count < getAlertsRequest.getRecordcount()) {
295                 AlertHelper h = (AlertHelper) e.next();
296                 t = new GetAlertsResponseMsg();
297                 t.setClassification(level);
298                 t.setType(h.type);
299                 t.setMessage(h.message);
300                 t.setUrl(h.url);
301                 t.setTransactionid(h.tid);
302                 cal = new GregorianCalendar();
303                 cal.setTimeInMillis(h.timestamp);
304                 t.setTimestamp((cal));
305                 ret.add(t);
306                 count++;
307             }
308         } catch (Exception ex) {
309             log.log(Level.WARN, "das1 error caught", ex);
310             t.setType(AlertType.OPERATING_STATUS);
311             t.setMessage("Performance Database is not available.");
312             cal = new GregorianCalendar();
313             t.setTimestamp((cal));
314             ret.add(t);
315         } finally {
316 
317             DBUtils.safeClose(con);
318             DBUtils.safeClose(config);
319 
320         }
321 
322         return ret;
323     }
324 
325     /**
326      *
327      *
328      * Returns all available message logs sorted by timestamp descending, i.e.
329      * the most recent first. options are offset (for paging) and record count *
330      *
331      *
332      * This is the preferred method for accessing message transaction logs as it
333      * is faster that the other method Global Admins can read all Users can only
334      * see per ACLs <param name="request">Specify SLA Fault OR Faults Only, both
335      * is not supported</param>
336      *
337      *
338      *
339      * @param request
340      * @return returns
341      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageLogsResponseMsg
342      * @throws AccessDeniedException
343      * @throws ServiceUnavailableException
344      */
345     @WebMethod(operationName = "GetRecentMessageLogs", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetRecentMessageLogs")
346     @WebResult(name = "GetMessageLogsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
347     @RequestWrapper(localName = "GetRecentMessageLogs", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetRecentMessageLogs")
348     @ResponseWrapper(localName = "GetRecentMessageLogsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetRecentMessageLogsResponse")
349     public GetMessageLogsResponseMsg getRecentMessageLogs(
350             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetRecentMessageLogsRequestMsg request)
351             throws AccessDeniedException, ServiceUnavailableException {
352 
353         return QueryGetRecentMessageLogs.getRecentMessageLogs(request, ctx);
354 
355     }
356 
357     /**
358      *
359      *
360      * Get Average Performance Statistics For All Transactional Services - this
361      * will return performance stats for all services that the requestor has
362      * access to
363      *
364      *
365      *
366      *
367      *
368      *
369      *
370      * @param range
371      * @param classification
372      * @return returns
373      * java.util.List<org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsResponseMsg>
374      * @throws ServiceUnavailableException
375      * @throws AccessDeniedException
376      */
377     @WebMethod(operationName = "GetPerformanceAverageStatsAll", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetPerformanceAverageStatsAll")
378     @WebResult(name = "AllStats", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
379     @RequestWrapper(localName = "GetPerformanceAverageStatsAll", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsAll")
380     @ResponseWrapper(localName = "GetPerformanceAverageStatsAllResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsAllResponse")
381     public List<GetPerformanceAverageStatsResponseMsg> getPerformanceAverageStatsAll(
382             @WebParam(name = "classification", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") SecurityWrapper classification,
383             @WebParam(name = "range", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") TimeRange range)
384             throws AccessDeniedException, ServiceUnavailableException {
385         if (range == null || range.getEnd() == null || range.getStart() == null) {
386             throw new IllegalArgumentException("Missing input parameters");
387         }
388         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
389         Utility.validateClassification(classification);
390         AuditLogger.logItem(this.getClass().getCanonicalName(), "getPerformanceAverageStatsAll", currentUser, "", (classification), ctx.getMessageContext());
391         ArrayList<GetPerformanceAverageStatsResponseMsg> ret = new ArrayList<GetPerformanceAverageStatsResponseMsg>();
392         ArrayOfServiceType GetServiceListfromPolicyDB = DASHelper.getServiceListfromPolicyDB(ctx, (classification), PolicyType.TRANSACTIONAL);
393         if (GetServiceListfromPolicyDB == null
394                 || GetServiceListfromPolicyDB.getServiceType().isEmpty()) {
395             return ret;
396         }
397 
398         for (int i = 0; i < GetServiceListfromPolicyDB.getServiceType().size(); i++) {
399             //unneccessary UserIdentityUtil.assertReadAccess(GetServiceListfromPolicyDB.getValue().getServiceType().get(i).getURL(), currentUser, "GetPerformanceAvgStatsFromDB");
400             GetPerformanceAverageStatsResponseMsg item = DASHelper.getPerformanceAvgStatsFromDB(ctx,
401                     GetServiceListfromPolicyDB.getServiceType().get(i).getURL(), GetServiceListfromPolicyDB.getServiceType().get(i).getDisplayName(),
402                     //  GetServiceListfromPolicyDB.getValue().getServiceType().get(i).getDisplayName(),
403                     classification);
404             if (item != null) {
405                 ret.add(item);
406             }
407         }
408 
409         return ret;
410     }
411 
412     /**
413      *
414      *
415      * Returns a specific message transaction log for transactional web services
416      * *
417      *
418      *
419      *
420      *
421      *
422      * @param req
423      * @return returns
424      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLogDetailsResponseMsg
425      * @throws ServiceUnavailableException
426      * @throws AccessDeniedException
427      */
428     @WebMethod(operationName = "GetMessageTransactionLogDetails", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMessageTransactionLogDetails")
429     @WebResult(name = "req", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
430     @RequestWrapper(localName = "GetMessageTransactionLogDetails", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLogDetails")
431     @ResponseWrapper(localName = "GetMessageTransactionLogDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLogDetailsResponse")
432     public GetMessageTransactionLogDetailsResponseMsg getMessageTransactionLogDetails(
433             @WebParam(name = "req", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMessageTransactionLogDetailsMsg req)
434             throws AccessDeniedException, ServiceUnavailableException {
435         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
436 
437         //log.log(Level.INFO, name + "getMessageTransactionLogDetails" + currentUser);
438         if (req == null) {
439             throw new IllegalArgumentException("Request is empty");
440         }
441         if (Utility.stringIsNullOrEmpty(req.getTransactionID())) {
442             throw new IllegalArgumentException("Transactio ID  is empty");
443         }
444         Utility.validateClassification(req.getClassification());
445         AuditLogger.logItem(this.getClass().getCanonicalName(), "getMessageTransactionLogDetails", currentUser, "", (req.getClassification()), ctx.getMessageContext());
446         Connection con = Utility.getPerformanceDBConnection();
447         PreparedStatement comm = null;
448         ResultSet set = null;
449         try {
450 
451             GetMessageTransactionLogDetailsResponseMsg ret = new GetMessageTransactionLogDetailsResponseMsg();
452 
453             comm = con.prepareStatement("select * from RawData " + "where transactionid=?");
454             comm.setString(1, req.getTransactionID());
455             set = comm.executeQuery();
456 
457             if (set.next()) {
458                 String url = set.getString("uri");
459                 UserIdentityUtil.assertAuditAccess(url, currentUser, "getMessageTransactionLogDetails", (req.getClassification()), ctx);
460                 ret.setCorrectedURL(url);
461                 ret.setOriginalRequestURL(set.getString("originalurl"));
462                 if (Utility.stringIsNullOrEmpty(ret.getOriginalRequestURL())) {
463                     ret.setOriginalRequestURL(ret.getCorrectedURL());
464                 }
465                 ret.setAction(set.getString("soapaction"));
466                 ret.setAgentType(set.getString("agenttype"));
467                 ret.setIsFault(!set.getBoolean("success"));
468                 ret.setResponseTime(set.getLong("responsetimems"));
469                 String sla = set.getString("slafault");
470                 ret.setIsSLAFault(!Utility.stringIsNullOrEmpty(sla));
471                 if (ret.isIsSLAFault()) {
472                     ret.setSlaFaultMsg(DASHelper.getSLAFaultMsg(con, sla));
473                 }
474                 ret.setMonitorHostname(set.getString("monitorsource"));
475                 ret.setServiceHostname(set.getString("hostingsource"));
476                 ret.setTransactionId(set.getString("transactionid"));
477                 ret.setRequestSize(set.getLong("requestsize"));
478                 ret.setResponseSize(set.getLong("responsesize"));
479 
480                 byte[] header = null;
481                 try {
482                     header = set.getBytes("requestHeaders");
483                 } catch (Exception ex) {
484                     log.log(Level.INFO, "", ex);
485                 }
486                 if (header != null) {
487 
488                     String s = null;
489                     try {
490                         s = new String(header, Constants.CHARSET);
491                         s = Utility.DE(s);
492                         String[] headers = s.split("\\|");
493                         for (int a = 0; a < headers.length; a++) {
494                             String[] s1 = headers[a].split("=");
495                             Header h = new Header();
496                             h.setName(s1[0]);
497                             if (s1.length == 2) {
498                                 String[] vs = s1[1].split(";");
499                                 if (vs != null && vs.length > 0) {
500                                     for (int b = 0; b < vs.length; b++) {
501                                         h.getValue().add(vs[b]);
502                                     }
503                                 }
504                             }
505                             ret.getHeadersRequest().add(h);
506                         }
507 
508                     } catch (Exception x) {
509                     }
510                 }
511                 header = null;
512                 try {
513                     header = set.getBytes("responseHeaders");
514                 } catch (Exception ex) {
515                     log.log(Level.INFO, "", ex);
516                 }
517 
518                 if (header != null) {
519                     String s = "";
520                     try {
521                         s = new String(header, Constants.CHARSET);
522                         s = Utility.DE(s);
523                         String[] headers = s.split("\\|");
524                         for (int a = 0; a < headers.length; a++) {
525                             String[] s1 = headers[a].split("=");
526                             Header h = new Header();
527                             h.setName(s1[0]);
528                             if (s1.length == 2) {
529                                 String[] vs = s1[1].split(";");
530                                 if (vs != null && vs.length > 0) {
531                                     for (int b = 0; b < vs.length; b++) {
532                                         h.getValue().add(vs[b]);
533                                     }
534                                 }
535                             }
536                             ret.getHeadersResponse().add(h);
537                         }
538                     } catch (UnsupportedEncodingException ex) {
539                         log.log(Level.ERROR, null, ex);
540                     }
541                 }
542                 GregorianCalendar gcal = new GregorianCalendar();
543                 gcal.setTimeInMillis(set.getLong("utcdatetime"));
544 
545                 ret.setTimestamp((gcal));
546                 //ret.setSlaFaultMsg(set.getString("slafault"));
547                 byte[] x = (byte[]) set.getBytes("RequestXML");
548                 if (x != null) {
549                     ret.setXmlRequestMessage(Utility.DE(new String(x, Constants.CHARSET)));
550                 }
551                 x = (byte[]) set.getBytes("ResponseXML");
552                 if (x != null) {
553                     ret.setXmlResponseMessage(Utility.DE(new String(x, Constants.CHARSET)));
554                 }
555                 String temp = set.getString("consumeridentity");
556                 if (!Utility.stringIsNullOrEmpty(temp)) {
557                     String[] ids = temp.split(";");
558                     for (int i = 0; i < ids.length; i++) {
559                         ret.getIdentity().add(ids[i]);
560                     }
561                 }
562 
563                 x = (byte[]) set.getBytes("message");
564                 if (x != null) {
565                     try {
566                         ret.setAgentMemo(new String(x, "UTF-8"));
567                         //ret.setXmlResponseMessage(new String(x));
568                     } catch (UnsupportedEncodingException ex) {
569                         log.log(Level.ERROR, null, ex);
570                     }
571                 }
572 
573                 ret.setRelatedTransactionID(set.getString("relatedTransactionID"));
574                 ret.setTransactionthreadId(set.getString("threadid"));
575                 ret.setClassification(getCurrentClassificationLevel());
576 
577                 return ret;
578             } else {
579 
580                 throw new IllegalArgumentException("transaction not found");
581             }
582         } catch (Exception ex) {
583             log.log(Level.ERROR, null, ex);
584         } finally {
585             DBUtils.safeClose(set);
586             DBUtils.safeClose(comm);
587             DBUtils.safeClose(con);
588         }
589         ServiceUnavailableException e = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
590         e.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
591         throw e;
592 
593     }
594 
595     /**
596      *
597      *
598      * Get Average Performance Statistics For a Specific Transactional Service
599      *
600      *
601      *
602      *
603      *
604      *
605      *
606      * @param request
607      * @return returns
608      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsResponseMsg
609      * @throws ServiceUnavailableException
610      * @throws AccessDeniedException
611      */
612     @WebMethod(operationName = "GetPerformanceAverageStats", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetPerformanceAverageStats")
613     @WebResult(name = "GetPerformanceAverageStatsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
614     @RequestWrapper(localName = "GetPerformanceAverageStats", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStats")
615     @ResponseWrapper(localName = "GetPerformanceAverageStatsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsResponse")
616     public GetPerformanceAverageStatsResponseMsg getPerformanceAverageStats(
617             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetPerformanceAverageStatsRequestMsg request)
618             throws AccessDeniedException, ServiceUnavailableException {
619         if (request == null) {
620             throw new IllegalArgumentException("Missing input parameters");
621         }
622 
623         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
624         Utility.validateClassification(request.getClassification());
625         AuditLogger.logItem(this.getClass().getCanonicalName(), "getPerformanceAverageStats", currentUser, "", (request.getClassification()), ctx.getMessageContext());
626 
627         if (!Utility.stringIsNullOrEmpty(request.getURL())) {
628             UserIdentityUtil.assertReadAccess(request.getURL(), currentUser, "GetPerformanceAvgStatsFromDB", (request.getClassification()), ctx);
629             GetPerformanceAverageStatsResponseMsg item = DASHelper.getPerformanceAvgStatsFromDB(ctx, request.getURL(), getPolicyDisplayName(request.getURL()), (request.getClassification()));
630             if (item != null) {
631                 return item;
632             } else {
633                 throw new IllegalArgumentException("No data is current available for the specified service");
634             }
635         } else {
636             throw new IllegalArgumentException("Request URL is empty, at least one must be specified");
637         }
638     }
639 
640     /**
641      *
642      *
643      * Get Average Performance Statistics a Hosting Server
644      *
645      * I.E. a machine hosting a web service that is monitored by fgsms
646      *
647      * Requires Global Admin permissions
648      *
649      *
650      *
651      *
652      *
653      *
654      *
655      * @param request
656      * @return returns
657      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsResponseMsg
658      * @throws ServiceUnavailableException
659      * @throws AccessDeniedException
660      */
661     @WebMethod(operationName = "GetPerformanceAverageHostingStats", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetPerformanceAverageHostingStats")
662     @WebResult(name = "GetPerformanceAverageHostingStatsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
663     @RequestWrapper(localName = "GetPerformanceAverageHostingStats", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageHostingStats")
664     @ResponseWrapper(localName = "GetPerformanceAverageHostingStatsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageHostingStatsResponse")
665     public GetPerformanceAverageStatsResponseMsg getPerformanceAverageHostingStats(
666             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetPerformanceAverageHostStatsRequestMsg request)
667             throws AccessDeniedException, ServiceUnavailableException {
668 
669         if (request == null) {
670             throw new IllegalArgumentException("Request is empty");
671         }
672         if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
673             throw new IllegalArgumentException("Time range is empty");
674         }
675         if (Utility.stringIsNullOrEmpty(request.getHostname())) {
676             throw new IllegalArgumentException("Hostname is emtpy");
677         }
678         //FIXME add additional time range checks
679 
680         if (request.getRange().getStart().after(request.getRange().getEnd())) {
681             throw new IllegalArgumentException("Start can't be after the end time");
682         }
683         Calendar now = Calendar.getInstance();
684         now.add(Calendar.DATE, 2);
685         if (now.before(request.getRange().getEnd())) {
686             throw new IllegalArgumentException("End time " + request.getRange().getEnd().getTime().toString() + " can't be more than one 2 days in the future from now " + new java.util.Date());
687         }
688 
689         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
690         Utility.validateClassification(request.getClassification());
691         AuditLogger.logItem(this.getClass().getCanonicalName(), "getPerformanceAverageHostingStats", currentUser, "", (request.getClassification()), ctx.getMessageContext());
692 
693         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getPerformanceAverageHostingStats", (request.getClassification()), ctx);
694         Connection con = Utility.getPerformanceDBConnection();
695         PreparedStatement comm = null;
696         ResultSet avg = null;
697         GetPerformanceAverageStatsResponseMsg res = new GetPerformanceAverageStatsResponseMsg();
698         res.setAverageResponseTime(0);
699         res.setFailingInvocations(0);
700         res.setSuccessfulInvocations(0);
701         boolean norecords = true;
702         boolean toomanyrecords = false;
703         long totalinvocations = 0;
704         try {
705 
706             /////////////////////////////////////////////
707             //query
708             /////////////////////////////////////////////
709             comm = con.prepareStatement("select avg(responsetimems),count(*)from rawdata where UTCdatetime >= ? and UTCdatetime <= ? and hostingsource=?;");
710             //average response time for a host, total transactions
711             //average response time for a host, total transactions
712 
713             comm.setLong(1, request.getRange().getStart().getTimeInMillis());
714             comm.setLong(2, request.getRange().getEnd().getTimeInMillis());
715             comm.setString(3, request.getHostname());
716 
717             avg = comm.executeQuery();
718 
719             //if (!avg.isClosed()) {
720             while (avg.next()) {
721                 if (!norecords) {
722                     toomanyrecords = true;
723                 }
724                 norecords = false;
725                 res.setAverageResponseTime((long) avg.getFloat(1));
726                 totalinvocations = avg.getLong(2);
727             }
728             //}
729             if (norecords) {
730                 //no data available
731                 res.setAverageResponseTime(0);
732                 res.setFailingInvocations(0);
733                 res.setSuccessfulInvocations(0);
734                 comm.close();
735                 con.close();
736                 return res;
737             }
738         } catch (Exception ex) {
739             log.log(Level.ERROR, "sql error from getPerformanceAverageHostingStats", ex);
740             ServiceUnavailableException code = new ServiceUnavailableException("", null);
741             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
742             throw code;
743         } finally {
744             DBUtils.safeClose(avg);
745             DBUtils.safeClose(comm);
746             DBUtils.safeClose(con);
747         }
748 
749         try {
750 
751             if (toomanyrecords) {
752                 ServiceUnavailableException code = new ServiceUnavailableException("", null);
753                 code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
754                 log.log(Level.ERROR, "too many records returned for getPerformanceAverageHostingStats returned. this is unexpected");
755                 throw code;
756             }
757             norecords = true;
758             toomanyrecords = false;
759             con = Utility.getPerformanceDBConnection();
760             comm = con.prepareStatement("select count(*) from rawdata where UTCdatetime >= ? and UTCdatetime <= ? and hostingsource=? and success=false;");
761             comm.setLong(1, request.getRange().getStart().getTimeInMillis());
762             comm.setLong(2, request.getRange().getEnd().getTimeInMillis());
763             comm.setString(3, request.getHostname());
764             avg = comm.executeQuery();
765             //if (!failures.isClosed()) {
766             while (avg.next()) {
767                 if (!norecords) {
768                     toomanyrecords = true;
769                 }
770                 res.setFailingInvocations(avg.getLong(1));
771                 res.setSuccessfulInvocations(totalinvocations - avg.getLong(1));
772                 norecords = false;
773             }
774             // }
775             if (toomanyrecords) {
776                 ServiceUnavailableException code = new ServiceUnavailableException("", null);
777                 code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
778                 log.log(Level.ERROR, "too many records returned for getPerformanceAverageHostingStats returned. this is unexpected");
779                 throw code;
780             }
781 
782             res.setClassification(getCurrentClassificationLevel());
783             return res;
784         } catch (Exception ex) {
785             log.log(Level.ERROR, "sql error from getPerformanceAverageHostingStats", ex);
786         } finally {
787             DBUtils.safeClose(avg);
788             DBUtils.safeClose(comm);
789             DBUtils.safeClose(con);
790         }
791         ServiceUnavailableException code = new ServiceUnavailableException("", null);
792         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
793         throw code;
794     }
795 
796     /**
797      *
798      *
799      * Returns all available message logs for a given period of time, audit
800      * access required
801      *
802      *
803      *
804      * <param name="request"> GetMessageLogsRequest Optional parameters: URL,
805      * shows only transactions from a matching modified url monitorhostname
806      * servicehostname agenttype
807      *
808      * Required: Time Range Records Offset faultsOnly SLAfaultsOnly</param>
809      *
810      *
811      *
812      * @param request
813      * @return returns
814      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageLogsResponseMsg
815      * must specify SLA Faults OR Faults, or none, but not both
816      * @throws
817      * DataAccessServiceGetMessageLogsServiceUnavailableFaultCodesFaultFaultMessage
818      * @throws
819      * DataAccessServiceGetMessageLogsAccessDeniedExceptionFaultFaultMessage
820      */
821     @WebMethod(operationName = "GetMessageLogsByRange", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMessageLogsByRange")
822     @WebResult(name = "GetMessageLogsResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
823     @RequestWrapper(localName = "GetMessageLogsByRange", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageLogsByRange")
824     @ResponseWrapper(localName = "GetMessageLogsByRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageLogsByRangeResponse")
825     public GetMessageLogsResponseMsg getMessageLogsByRange(
826             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMessageLogsRequestMsg request)
827             throws AccessDeniedException, ServiceUnavailableException {
828 
829         return QueryGetMessageLogsByRange.getMessageLogsByRange(request, ctx);
830     }
831 
832     /**
833      *
834      *
835      * Return a specific message log (payloads) for a given web service
836      * transaction
837      *
838      *
839      *
840      *
841      *
842      *
843      *
844      * @param request
845      * @return returns
846      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLogResponseMsg
847      * @throws
848      * DataAccessServiceGetMessageTransactionLogServiceUnavailableExceptionFaultFaultMessage
849      * @throws
850      * DataAccessServiceGetMessageTransactionLogAccessDeniedExceptionFaultFaultMessage
851      */
852     @WebMethod(operationName = "GetMessageTransactionLog", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMessageTransactionLog")
853     @WebResult(name = "GetMessageTransactionLogResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
854     @RequestWrapper(localName = "GetMessageTransactionLog", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLog")
855     @ResponseWrapper(localName = "GetMessageTransactionLogResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMessageTransactionLogResponse")
856     public GetMessageTransactionLogResponseMsg getMessageTransactionLog(
857             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMessageTransactionLogRequestMsg request)
858             throws AccessDeniedException, ServiceUnavailableException {
859         if (request == null) {
860             throw new IllegalArgumentException("request is null");
861         }
862         if (request.getTransactionId() == null) {
863             throw new IllegalArgumentException("transaction id must be specified");
864         }
865         if (request.getURL() == null) {
866             throw new IllegalArgumentException("a valid URI must be specified");
867         }
868 
869         Connection con = Utility.getPerformanceDBConnection();
870         PreparedStatement comm = null;
871         ResultSet results = null;
872         try {
873             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
874             Utility.validateClassification(request.getClassification());
875             AuditLogger.logItem(this.getClass().getCanonicalName(), "getMessageTransactionLog", currentUser, "", (request.getClassification()), ctx.getMessageContext());
876             //log.log(Level.INFO, name + " GetMessageTransactionLog " + currentUser);
877             UserIdentityUtil.assertAuditAccess(request.getURL(), currentUser, "getMessageTransactionLog", (request.getClassification()), ctx);
878             GetMessageTransactionLogResponseMsg res = new GetMessageTransactionLogResponseMsg();
879 
880             comm = con.prepareStatement("Select * from RawData where transactionId=? and URI=?;");
881             comm.setString(1, request.getTransactionId());
882             comm.setString(2, request.getURL());
883             results = comm.executeQuery();
884             /////////////////////////////////////////////
885             //query
886             /////////////////////////////////////////////
887             boolean norecords = true;
888             boolean toomanyrecords = false;
889 
890             while (results.next()) {
891                 if (!norecords) {
892                     toomanyrecords = true;
893                 }
894                 norecords = false;
895 
896                 res = new GetMessageTransactionLogResponseMsg();
897 
898                 byte[] x = (byte[]) results.getBytes("RequestXML");
899 
900                 if (x != null) {
901                     res.setRequestMessage(new String(x, Constants.CHARSET));
902                 }
903                 x = (byte[]) results.getBytes("ResponseXML");
904 
905                 if (x != null) {
906                     res.setResponseMessage(new String(x, Constants.CHARSET));
907                 }
908                 res.setResponseTime(results.getLong("ResponseTimeMS"));
909                 res.setIsFault(!results.getBoolean("Success"));
910             }
911             if (norecords) {
912 
913                 return null;
914             }
915             if (toomanyrecords) {
916                 log.log(Level.ERROR, " GetMessageTransactionLog Database returned multiple rows when queriying for the primary transactionId key. This is unexpected");
917                 ServiceUnavailableException code = new ServiceUnavailableException("", null);
918                 code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
919                 throw code;
920             }
921 
922             res.setClassification(getCurrentClassificationLevel());
923             return res;
924         } catch (Exception ex) {
925             log.log(Level.ERROR, null, ex);
926         } finally {
927             DBUtils.safeClose(results);
928             DBUtils.safeClose(comm);
929             DBUtils.safeClose(con);
930         }
931         ServiceUnavailableException code = new ServiceUnavailableException("", null);
932         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
933         throw code;
934 
935     }
936 
937     /**
938      *
939      *
940      * Returns all available operational status change logs for a given period
941      * of time and service
942      *
943      *
944      *
945      *
946      *
947      *
948      *
949      * @param request
950      * @return returns
951      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetOperationalStatusLogResponseMsg
952      * @throws
953      * DataAccessServiceGetOperationalStatusLogAccessDeniedExceptionFaultFaultMessage
954      * @throws
955      * DataAccessServiceGetOperationalStatusLogServiceUnavailableExceptionFaultFaultMessage
956      */
957     @WebMethod(operationName = "GetOperationalStatusLog", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetOperationalStatusLog")
958     @WebResult(name = "GetOperationalStatusLogResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
959     @RequestWrapper(localName = "GetOperationalStatusLog", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetOperationalStatusLog")
960     @ResponseWrapper(localName = "GetOperationalStatusLogResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetOperationalStatusLogResponse")
961     public GetOperationalStatusLogResponseMsg getOperationalStatusLog(
962             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetOperationalStatusLogRequestMsg request)
963             throws AccessDeniedException, ServiceUnavailableException {
964 
965         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
966         Utility.validateClassification(request.getClassification());
967         AuditLogger.logItem(this.getClass().getCanonicalName(), "getOperationalStatusLog", currentUser, "", (request.getClassification()), ctx.getMessageContext());
968         if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
969             throw new IllegalArgumentException("range is null");
970         }
971         if (Utility.stringIsNullOrEmpty(request.getURL())) {
972             throw new IllegalArgumentException("url");
973         }
974 
975         UserIdentityUtil.assertReadAccess(request.getURL(), currentUser, "getOperationalStatusLog", (request.getClassification()), ctx);
976         GetOperationalStatusLogResponseMsg ret = new GetOperationalStatusLogResponseMsg();
977         Connection con = Utility.getPerformanceDBConnection();
978         PreparedStatement com = null;
979         ResultSet set = null;
980         try {
981             com = con.prepareStatement("SELECT uri, utcdatetime, status, id, message "
982                     + "FROM availability where utcdatetime > ? and utcdatetime < ? and uri=? order by utcdatetime asc;");
983             com.setString(3, request.getURL());
984             com.setLong(1, request.getRange().getStart().getTimeInMillis());
985             com.setLong(2, request.getRange().getEnd().getTimeInMillis());
986             set = com.executeQuery();
987             while (set.next()) {
988                 OperationalRecord op = new OperationalRecord();
989                 op.setID(set.getString("id"));
990                 byte[] b = set.getBytes("message");
991                 op.setMessage(new String(b, Constants.CHARSET));
992                 GregorianCalendar cal = new GregorianCalendar();
993                 cal.setTimeInMillis(set.getLong("utcdatetime"));
994                 op.setTimestamp((cal));
995                 op.setOperational(set.getBoolean("status"));
996                 ret.getOperationalRecord().add(op);
997             }
998 
999             ret.setURL(request.getURL());
1000             ret.setClassification(getCurrentClassificationLevel());
1001             return ret;
1002         } catch (Exception ex) {
1003             log.log(Level.ERROR, null, ex);
1004             ServiceUnavailableException code = new ServiceUnavailableException("", null);
1005             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1006             throw code;
1007         } finally {
1008             DBUtils.safeClose(set);
1009             DBUtils.safeClose(com);
1010             DBUtils.safeClose(con);
1011         }
1012 
1013     }
1014 
1015     /**
1016      *
1017      *
1018      * GetMonitoredServiceList
1019      *
1020      * Returns 0 or more monitored services.
1021      *
1022      * This list of services is generated from the defined policies
1023      *
1024      * The list of soap actions is generated from the actual message
1025      * transactions
1026      *
1027      * meaning that if a particular action has never been executed, fgsms
1028      * doesn't know about it.
1029      *
1030      * Returns a listing of services along with there associated soap actions
1031      *
1032      *
1033      *
1034      *
1035      *
1036      *
1037      *
1038      * @param request
1039      * @return returns
1040      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMonitoredServiceListResponseMsg
1041      * @throws
1042      * DataAccessServiceGetMonitoredServiceListAccessDeniedExceptionFaultFaultMessage
1043      * @throws
1044      * DataAccessServiceGetMonitoredServiceListServiceUnavailableExceptionFaultFaultMessage
1045      */
1046     @WebMethod(operationName = "GetMonitoredServiceList", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMonitoredServiceList")
1047     @WebResult(name = "GetMonitoredServiceListResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1048     @RequestWrapper(localName = "GetMonitoredServiceList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMonitoredServiceList")
1049     @ResponseWrapper(localName = "GetMonitoredServiceListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMonitoredServiceListResponse")
1050     public GetMonitoredServiceListResponseMsg getMonitoredServiceList(
1051             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMonitoredServiceListRequestMsg request)
1052             throws AccessDeniedException, ServiceUnavailableException {
1053 
1054         //access control is processed in GetServiceListfromPolicyDB
1055         if (request == null) {
1056             throw new IllegalArgumentException("request is null");
1057         }
1058         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1059         Utility.validateClassification(request.getClassification());
1060         AuditLogger.logItem(this.getClass().getCanonicalName(), "GetMonitoredServiceList", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1061         GetMonitoredServiceListResponseMsg ret = new GetMonitoredServiceListResponseMsg();
1062         if (request.getURL() == null || Utility.stringIsNullOrEmpty(request.getURL())) {
1063             ret.setServiceList(DASHelper.getServiceListfromPolicyDB(ctx, (request.getClassification())));
1064         } else {
1065             ret.setServiceList(DASHelper.getServiceListfromPolicyDB(ctx, request.getURL(), (request.getClassification())));
1066         }
1067         ret.setClassification(getCurrentClassificationLevel());
1068         return ret;
1069     }
1070 
1071     /**
1072      *
1073      *
1074      * Returns all available SLA fault records, transactional and
1075      * nontransactional logs for a given period of time and service
1076      *
1077      *
1078      *
1079      *
1080      *
1081      *
1082      *
1083      * @param request
1084      * @return returns
1085      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetSLAFaultRecordsResponseMsg
1086      * @throws
1087      * DataAccessServiceGetSLAFaultRecordsAccessDeniedExceptionFaultFaultMessage
1088      * @throws
1089      * DataAccessServiceGetSLAFaultRecordsServiceUnavailableExceptionFaultFaultMessage
1090      */
1091     @WebMethod(operationName = "GetSLAFaultRecords", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetSLAFaultRecords")
1092     @WebResult(name = "GetSLAFaultRecordsResponseMsgResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1093     @RequestWrapper(localName = "GetSLAFaultRecords", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetSLAFaultRecords")
1094     @ResponseWrapper(localName = "GetSLAFaultRecordsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetSLAFaultRecordsResponse")
1095     public List<GetSLAFaultRecordsResponseMsg> getSLAFaultRecords(
1096             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetSLAFaultRecordsRequestMsg request)
1097             throws AccessDeniedException, ServiceUnavailableException {
1098 
1099         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1100         Utility.validateClassification(request.getClassification());
1101         AuditLogger.logItem(this.getClass().getCanonicalName(), "getSLAFaultRecords", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1102         if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
1103             throw new IllegalArgumentException("range is null");
1104         }
1105         if (Utility.stringIsNullOrEmpty(request.getURL())) {
1106             throw new IllegalArgumentException("url is null");
1107         }
1108         long maxrecords = 200;
1109         if (request.getRecordcount() > 0 && request.getRecordcount() < 1000) {
1110             maxrecords = request.getRecordcount();
1111         }
1112         long offset = 0;
1113         if (request.getOffset() > 0) {
1114             offset = request.getOffset();
1115         }
1116 
1117 //TODO add record acounts and limits via wsdl
1118         UserIdentityUtil.assertReadAccess(request.getURL(), currentUser, "getSLAFaultRecords", (request.getClassification()), ctx);
1119         List<GetSLAFaultRecordsResponseMsg> ret = new ArrayList<GetSLAFaultRecordsResponseMsg>();
1120         Connection con = Utility.getPerformanceDBConnection();
1121         PreparedStatement com = null;
1122         ResultSet rs = null;
1123         try {
1124             com = con.prepareStatement("SELECT utcdatetime, msg, uri, relatedtransaction, incidentid FROM slaviolations "
1125                     + "where (utcdatetime > ?) and (utcdatetime < ?) and (uri = ?) order by utcdatetime DESC limit ? offset ?;");
1126             com.setLong(1, request.getRange().getStart().getTimeInMillis());
1127             com.setLong(2, request.getRange().getEnd().getTimeInMillis());
1128             com.setString(3, request.getURL());
1129             com.setLong(4, maxrecords);
1130             com.setLong(5, offset);
1131             rs = com.executeQuery();
1132             while (rs.next()) {
1133                 GetSLAFaultRecordsResponseMsg t = new GetSLAFaultRecordsResponseMsg();
1134                 t.setIncidentID(rs.getString("incidentid"));
1135                 byte[] b = rs.getBytes("msg");
1136                 t.setMessage(new String(b, Constants.CHARSET));
1137                 t.setRelatedTransaction(rs.getString("relatedtransaction"));
1138                 GregorianCalendar cal = new GregorianCalendar();
1139                 cal.setTimeInMillis(rs.getLong("utcdatetime"));
1140                 t.setTimestamp((cal));
1141                 ret.add(t);
1142 
1143             }
1144 
1145             return ret;
1146         } catch (Exception ex) {
1147             log.log(Level.ERROR, null, ex);
1148             ServiceUnavailableException code = new ServiceUnavailableException("", null);
1149             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1150             throw code;
1151         } finally {
1152             DBUtils.safeClose(rs);
1153             DBUtils.safeClose(com);
1154             DBUtils.safeClose(con);
1155         }
1156 
1157     }
1158 
1159     /**
1160      *
1161      *
1162      * Returns all available operational status change logs for a given period
1163      * of time for all services
1164      *
1165      *
1166      *
1167      *
1168      *
1169      *
1170      *
1171      * @param request
1172      * @return returns
1173      * java.util.List<org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllOperationalStatusLogResponseMsg>
1174      * @throws ServiceUnavailableException
1175      * @throws AccessDeniedException
1176      */
1177     @WebMethod(operationName = "GetAllOperationalStatusLog", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAllOperationalStatusLog")
1178     @WebResult(name = "GetAllOperationalStatusLogResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1179     @RequestWrapper(localName = "GetAllOperationalStatusLog", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllOperationalStatusLog")
1180     @ResponseWrapper(localName = "GetAllOperationalStatusLogResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllOperationalStatusLogResponse")
1181     public List<GetAllOperationalStatusLogResponseMsg> getAllOperationalStatusLog(
1182             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAllOperationalStatusLogRequestMsg request)
1183             throws AccessDeniedException, ServiceUnavailableException {
1184         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1185         Utility.validateClassification(request.getClassification());
1186         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAllOperationalStatusLog", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1187 
1188         if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
1189             throw new IllegalArgumentException("range is null");
1190         }
1191         if (request.getRange().getEnd() == null || request.getRange().getStart() == null) {
1192             throw new IllegalArgumentException("range is null");
1193         }
1194         List<GetAllOperationalStatusLogResponseMsg> ret = new ArrayList<GetAllOperationalStatusLogResponseMsg>();
1195         SecurityWrapper currentClassificationLevel = getCurrentClassificationLevel();
1196         Connection con = Utility.getPerformanceDBConnection();
1197         PreparedStatement com = null;
1198         ResultSet set = null;
1199         try {
1200             ArrayOfServiceType list = DASHelper.getServiceListfromPolicyDB(ctx, request.getClassification());
1201             if (!(list == null || list.getServiceType() == null)) {
1202                 for (int i = 0; i < list.getServiceType().size(); i++) {
1203                     try {
1204                         com = con.prepareStatement("SELECT uri, utcdatetime, status, id, message " + "FROM availability where utcdatetime > ? and " + "utcdatetime < ? and uri=?");
1205                         com.setString(3, list.getServiceType().get(i).getURL());
1206                         com.setLong(1, request.getRange().getStart().getTimeInMillis());
1207                         com.setLong(2, request.getRange().getEnd().getTimeInMillis());
1208                         set = com.executeQuery();
1209                         GetAllOperationalStatusLogResponseMsg t = new GetAllOperationalStatusLogResponseMsg();
1210                         t.setURL(list.getServiceType().get(i).getURL());
1211                         while (set.next()) {
1212                             OperationalRecord op = new OperationalRecord();
1213                             op.setID(set.getString("id"));
1214                             byte[] b = set.getBytes("message");
1215                             op.setMessage(new String(b, Constants.CHARSET));
1216                             GregorianCalendar cal = new GregorianCalendar();
1217                             cal.setTimeInMillis(set.getLong("utcdatetime"));
1218                             op.setTimestamp((cal));
1219                             op.setOperational(set.getBoolean("status"));
1220                             t.getOperationalRecord().add(op);
1221                         }
1222 
1223                         t.setClassification(currentClassificationLevel);
1224                         ret.add(t);
1225                     } catch (SQLException ex) {
1226                         log.log(Level.ERROR, "getAllOperationalStatusLog error caught sql error", ex);
1227                         ServiceUnavailableException code = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
1228                         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1229                         throw code;
1230                     } finally {
1231                         DBUtils.safeClose(set);
1232                         DBUtils.safeClose(com);
1233 
1234                     }
1235 
1236                 }
1237             }
1238             return ret;
1239         } catch (Exception ex) {
1240             log.log(Level.ERROR, "getAllOperationalStatusLog", ex);
1241         } finally {
1242             DBUtils.safeClose(con);
1243         }
1244 
1245         ServiceUnavailableException code = new ServiceUnavailableException("", new org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableException());
1246         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
1247         throw code;
1248     }
1249 
1250     /**
1251      *
1252      *
1253      * GetServiceHostList
1254      *
1255      * Returns 0 or more host names of machines hosting monitored web services.
1256      *
1257      *
1258      *
1259      *
1260      *
1261      *
1262      *
1263      * @param request
1264      * @return returns
1265      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceHostListResponseMsg
1266      * @throws ServiceUnavailableException
1267      * @throws AccessDeniedException
1268      */
1269     @WebMethod(operationName = "GetServiceHostList", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetServiceHostList")
1270     @WebResult(name = "GetServiceHostListResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1271     @RequestWrapper(localName = "GetServiceHostList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceHostList")
1272     @ResponseWrapper(localName = "GetServiceHostListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceHostListResponse")
1273     public GetServiceHostListResponseMsg getServiceHostList(
1274             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetServiceHostListRequestMsg request)
1275             throws AccessDeniedException, ServiceUnavailableException {
1276 
1277         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1278         Utility.validateClassification(request.getClassification());
1279         AuditLogger.logItem(this.getClass().getCanonicalName(), "getServiceHostList", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1280 
1281         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getServiceHostList", (request.getClassification()), ctx);
1282 
1283         //here we don't care about the request since we don't rely on any input
1284         GetServiceHostListResponseMsg res = new GetServiceHostListResponseMsg();
1285         Connection con = Utility.getConfigurationDBConnection();
1286         PreparedStatement comm = null;
1287         ResultSet results = null;
1288         try {
1289 
1290             comm = con.prepareStatement("Select * from servicehosts;");
1291             results = comm.executeQuery();
1292             /////////////////////////////////////////////
1293             //query
1294             /////////////////////////////////////////////
1295 
1296             ArrayOfHostInstanceStats list = new ArrayOfHostInstanceStats();
1297             while (results.next()) {
1298 
1299                 HostInstanceStats temp = new HostInstanceStats();
1300                 temp.setHost(results.getString("hostname"));
1301                 temp.setRecordedTransactionCount(Long.valueOf(results.getLong("records")).intValue());
1302                 list.getHostInstanceStats().add(temp);
1303             }
1304             results.close();
1305 
1306             res.setHosts(list);
1307 
1308             res.setClassification(getCurrentClassificationLevel());
1309             return res;
1310         } catch (SQLException ex) {
1311             log.log(Level.ERROR, null, ex);
1312             ServiceUnavailableException code = new ServiceUnavailableException("", null);
1313             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1314             throw code;
1315         } finally {
1316             DBUtils.safeClose(results);
1317             DBUtils.safeClose(comm);
1318             DBUtils.safeClose(con);
1319         }
1320 
1321     }
1322 
1323     /**
1324      *
1325      *
1326      * GetDataCollectorList
1327      *
1328      * Returns 0 or more host names of machines hosting data collector services
1329      *
1330      *
1331      *
1332      *
1333      *
1334      *
1335      *
1336      * @param request
1337      * @return returns
1338      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetDataCollectorListResponseMsg
1339      * @throws ServiceUnavailableException
1340      * @throws AccessDeniedException
1341      */
1342     @WebMethod(operationName = "GetDataCollectorList", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetDataCollectorList")
1343     @WebResult(name = "GetDataCollectorListResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1344     @RequestWrapper(localName = "GetDataCollectorList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetDataCollectorList")
1345     @ResponseWrapper(localName = "GetDataCollectorListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetDataCollectorListResponse")
1346     public GetDataCollectorListResponseMsg getDataCollectorList(
1347             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetDataCollectorListRequestMsg request)
1348             throws AccessDeniedException, ServiceUnavailableException {
1349 
1350         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1351         Utility.validateClassification(request.getClassification());
1352         AuditLogger.logItem(this.getClass().getCanonicalName(), "getDataCollectorList", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1353         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getDataCollectorList", (request.getClassification()), ctx);
1354 
1355         //here, we don't rely on any input parameters, so it doesn't matter if it's null
1356         GetDataCollectorListResponseMsg res = new GetDataCollectorListResponseMsg();
1357         res.setClassification(getCurrentClassificationLevel());
1358         Connection con = Utility.getConfigurationDBConnection();
1359         PreparedStatement comm = null;
1360         ResultSet results = null;
1361         try {
1362             comm = con.prepareStatement("Select * from dcsservicehosts;");
1363             results = comm.executeQuery();
1364             /////////////////////////////////////////////
1365             //query
1366             /////////////////////////////////////////////
1367             //  boolean norecords = true;
1368             ArrayOfHostInstanceStats list = new ArrayOfHostInstanceStats();
1369             while (results.next()) {
1370                 //         norecords = false;
1371                 HostInstanceStats temp = new HostInstanceStats();
1372                 temp.setHost(results.getString("hostname"));
1373                 temp.setRecordedTransactionCount(Long.valueOf(results.getLong("records")).intValue());
1374                 list.getHostInstanceStats().add(temp);
1375             }
1376 
1377             res.setHosts(list);
1378             return res;
1379         } catch (SQLException ex) {
1380             log.log(Level.ERROR, null, ex);
1381             ServiceUnavailableException code = new ServiceUnavailableException("", null);
1382             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1383             throw code;
1384         } finally {
1385             DBUtils.safeClose(results);
1386             DBUtils.safeClose(comm);
1387             DBUtils.safeClose(con);
1388         }
1389 
1390     }
1391 
1392     /**
1393      *
1394      *
1395      * Removes performance data for the specified service(s) and optionally for
1396      * the specified time range.
1397      *
1398      * If access is denied for any item, no changes will be made and a fault
1399      * will be returned.
1400      *
1401      *
1402      *
1403      *
1404      *
1405      *
1406      *
1407      * @param request
1408      * @return returns
1409      * org.miloss.fgsms.services.interfaces.dataaccessservice.PurgePerformanceDataResponseMsg
1410      * @throws ServiceUnavailableException
1411      * @throws AccessDeniedException
1412      */
1413     @WebMethod(operationName = "PurgePerformanceData", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/PurgePerformanceData")
1414     @WebResult(name = "PurgePerformanceDataResult", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1415     @RequestWrapper(localName = "PurgePerformanceData", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.PurgePerformanceData")
1416     @ResponseWrapper(localName = "PurgePerformanceDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.PurgePerformanceDataResponse")
1417     public PurgePerformanceDataResponseMsg purgePerformanceData(
1418             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") PurgePerformanceDataRequestMsg request)
1419             throws AccessDeniedException, ServiceUnavailableException {
1420         if (request == null) {
1421             throw new IllegalArgumentException("request is null");
1422         }
1423 
1424         if ((request.getURL() == null)) {
1425             throw new IllegalArgumentException("URL is null");
1426         }
1427 
1428         PurgePerformanceDataResponseMsg response = new PurgePerformanceDataResponseMsg();
1429 
1430         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1431         Utility.validateClassification(request.getClassification());
1432         AuditLogger.logItem(this.getClass().getCanonicalName(), "purgePerformanceData", currentUser, "", (request.getClassification()), ctx.getMessageContext());
1433 
1434         for (int i = 0; i < request.getURL().size(); i++) {
1435             UserIdentityUtil.assertAdministerAccess(request.getURL().get(i), currentUser, "purgePerformanceData", (request.getClassification()), ctx);
1436         }
1437 
1438         Connection con = Utility.getPerformanceDBConnection();
1439         PreparedStatement cmd = null;
1440         try {
1441 
1442             for (int i = 0; i < request.getURL().size(); i++) {
1443                 try {
1444                     if (request.getRange() != null) {
1445                         cmd = con.prepareStatement("Delete from RawData where URI=? and utcdatetime >= ? and UTCdatetime <= ?;");
1446 
1447                         cmd.setLong(2, request.getRange().getStart().getTimeInMillis());
1448                         cmd.setLong(3, request.getRange().getEnd().getTimeInMillis());
1449                     } else {
1450                         cmd = con.prepareStatement("Delete from RawData where URI=?");
1451                     }
1452                     cmd.setString(1, request.getURL().get(i));
1453                     cmd.execute();
1454                 } catch (SQLException ex) {
1455                     log.log(Level.ERROR, "error caught deleted records for service" + request.getURL().get(i), ex);
1456                 } finally {
1457                     DBUtils.safeClose(cmd);
1458                 }
1459             }
1460             response.setClassification(getCurrentClassificationLevel());
1461             return response;
1462         } catch (Exception ex) {
1463             log.log(Level.WARN, null, ex);
1464         } finally {
1465             DBUtils.safeClose(cmd);
1466             DBUtils.safeClose(con);
1467         }
1468         ServiceUnavailableException code = new ServiceUnavailableException("", null);
1469         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1470         throw code;
1471     }
1472 
1473     /**
1474      *
1475      *
1476      * Returns the fgsms audit log for
1477      *
1478      *
1479      *
1480      *
1481      *
1482      *
1483      *
1484      * @param getAuditLog
1485      * @return returns
1486      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLogResponseMsg
1487      * @throws ServiceUnavailableException
1488      * @throws AccessDeniedException
1489      */
1490     @WebMethod(operationName = "GetAuditLog", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAuditLog")
1491     @WebResult(name = "GetAuditLogResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1492     @RequestWrapper(localName = "GetAuditLog", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLog")
1493     @ResponseWrapper(localName = "GetAuditLogResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLogResponse")
1494     public GetAuditLogResponseMsg getAuditLog(
1495             @WebParam(name = "GetAuditLog", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAuditLogRequestMsg getAuditLog)
1496             throws AccessDeniedException, ServiceUnavailableException {
1497 
1498         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1499         if (getAuditLog == null) {
1500             throw new IllegalArgumentException("null message");
1501         }
1502         Utility.validateClassification(getAuditLog.getClassification());
1503         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAuditLog", currentUser, "read audit logs", (getAuditLog.getClassification()), ctx.getMessageContext());
1504         UserIdentityUtil.assertGlobalAuditRole(currentUser, "getAuditLog", (getAuditLog.getClassification()), ctx);
1505         Connection con = Utility.getConfigurationDBConnection();
1506         PreparedStatement com = null;
1507         ResultSet rs = null;
1508         try {
1509             GetAuditLogResponseMsg ret = new GetAuditLogResponseMsg();
1510 
1511             long count = 100;
1512             long offset = 0;
1513             if (getAuditLog.getRecordcount() >= 1) {
1514                 count = getAuditLog.getRecordcount();
1515             }
1516             if (getAuditLog.getOffset() < 0) {
1517                 offset = 0;
1518             } else {
1519                 offset = getAuditLog.getOffset();
1520             }
1521 
1522             com = con.prepareStatement(" SELECT utcdatetime, username, classname, method, memo, "
1523                     + "classification, ipaddress FROM auditlog order by utcdatetime desc limit ? offset ?;");
1524             com.setLong(1, count);
1525             com.setLong(2, offset);
1526 
1527             rs = com.executeQuery();
1528 
1529             while (rs.next()) {
1530                 /*
1531                  * recordcount++; if (recordcount >
1532                  * getAuditLog.getRecordcount()) { break; }
1533                  */
1534                 AuditLog e = new AuditLog();
1535                 e.setClassification(rs.getString("classification"));
1536                 e.setClazz(rs.getString("classname"));
1537                 e.setIpaddress(rs.getString("ipaddress"));
1538                 e.setUsername(rs.getString("username"));
1539                 e.setMethod(rs.getString("method"));
1540                 e.setMemo(new String(rs.getBytes("memo"), Constants.CHARSET));
1541                 GregorianCalendar cal = new GregorianCalendar();
1542                 cal.setTimeInMillis(rs.getLong("utcdatetime"));
1543                 e.setTimestamp((cal));
1544                 ret.getAuditLog().add(e);
1545 
1546             }
1547 
1548             ret.setClassification(getCurrentClassificationLevel());
1549             return ret;
1550         } catch (Exception ex) {
1551             log.log(Level.ERROR, null, ex);
1552 
1553         } finally {
1554             DBUtils.safeClose(rs);
1555             DBUtils.safeClose(com);
1556             DBUtils.safeClose(con);
1557         }
1558         ServiceUnavailableException code = new ServiceUnavailableException("", null);
1559         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1560         throw code;
1561     }
1562 
1563     /**
1564      *
1565      *
1566      * Returns the current list of monitored brokers and some general statistics
1567      * on each broker, such as current total message counts as reported by the
1568      * broker, average queue depth amonst all queues, etc.
1569      *
1570      *
1571      *
1572      *
1573      *
1574      *
1575      *
1576      * @param getBrokerListRequest
1577      * @return returns
1578      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetBrokerListResponseMsg
1579      * @throws ServiceUnavailableException
1580      * @throws AccessDeniedException
1581      */
1582     @WebMethod(operationName = "GetBrokerList", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetBrokerList")
1583     @WebResult(name = "GetBrokerListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1584     @RequestWrapper(localName = "GetBrokerList", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetBrokerList")
1585     @ResponseWrapper(localName = "GetBrokerListResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetBrokerListResponse")
1586     public GetBrokerListResponseMsg getBrokerList(
1587             @WebParam(name = "GetBrokerListRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetBrokerListRequestMsg getBrokerListRequest)
1588             throws AccessDeniedException, ServiceUnavailableException {
1589         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1590         if (getBrokerListRequest == null) {
1591             throw new IllegalArgumentException("null message");
1592         }
1593         Utility.validateClassification(getBrokerListRequest.getClassification());
1594         AuditLogger.logItem(this.getClass().getCanonicalName(), "getBrokerList", currentUser, "", (getBrokerListRequest.getClassification()), ctx.getMessageContext());
1595 
1596         GetBrokerListResponseMsg res = new GetBrokerListResponseMsg();
1597 
1598         boolean admin = UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "getBrokerList", getBrokerListRequest.getClassification(), ctx);
1599         Connection con = Utility.getPerformanceDBConnection();
1600         ResultSet rs = null;
1601 
1602         PreparedStatement com = null;
1603 //TODO this needs to be rewritten, probably easier to load the service policies of type
1604 //broker, then query for the details of thsoe brokers
1605         if (admin) {
1606             try {
1607                 com = con.prepareStatement("select host  from brokerrawdata group by host;");
1608                 rs = com.executeQuery();
1609                 while (rs.next()) {
1610                     BrokerDetails bd = new BrokerDetails();
1611                     bd.setUri(rs.getString(1));
1612                     res.getBrokerList().add(bd);
1613                 }
1614             } catch (Exception ex) {
1615                 log.log(Level.ERROR, null, ex);
1616             } finally {
1617                 DBUtils.safeClose(rs);
1618                 DBUtils.safeClose(com);
1619 
1620             }
1621         } else {
1622             try {
1623                 List<String> potentials = new ArrayList<String>();
1624 
1625                 com = con.prepareStatement("select host  from brokerrawdata group by host;");
1626                 rs = com.executeQuery();
1627                 while (rs.next()) {
1628                     potentials.add(rs.getString(1));
1629                 }
1630                 rs.close();
1631                 com.close();
1632 
1633                 PreparedStatement comPermissions = null;
1634                 Connection config = Utility.getConfigurationDBConnection();
1635                 for (int i = 0; i < potentials.size(); i++) {
1636                     comPermissions = config.prepareStatement("select ObjectURI from UserPermissions where ObjectURI=? and username=? and (ReadObject=true or WriteObject=true or AdministerObject=true or AuditObject=true);");
1637                     comPermissions.setString(1, potentials.get(i));
1638                     comPermissions.setString(2, currentUser);
1639                     rs = comPermissions.executeQuery();
1640                     while (rs.next()) {
1641                         BrokerDetails bd = new BrokerDetails();
1642                         bd.setUri(potentials.get(i));
1643                         res.getBrokerList().add(bd);
1644                     }
1645                     rs.close();
1646                     comPermissions.close();
1647                 }
1648             } catch (Exception ex) {
1649                 log.log(Level.ERROR, null, ex);
1650             } finally {
1651                 DBUtils.safeClose(rs);
1652                 DBUtils.safeClose(com);
1653 
1654             }
1655 
1656         }
1657 
1658         for (int i = 0; i < res.getBrokerList().size(); i++) {
1659             try {
1660                 com = con.prepareStatement("select sum(messagecount), sum(consumercount), sum(recievedmessagecount), sum(activeconsumercount), "
1661                         + "sum(queuedepth), sum(messagedropcount), sum(bytesdropcount), sum(bytesin), sum(bytesout) from brokerrawdata where host=?");
1662                 com.setString(1, res.getBrokerList().get(i).getUri());
1663                 rs = com.executeQuery();
1664                 if (rs.next()) {
1665 
1666                     res.getBrokerList().get(i).setTotalmessagesent(rs.getLong(1));
1667                     res.getBrokerList().get(i).setTotalconsumers(rs.getLong(2));
1668                     res.getBrokerList().get(i).setTotalmessagesrecieved(rs.getLong(3));
1669                     res.getBrokerList().get(i).setTotalactiveconsumers(rs.getLong(4));
1670                     res.getBrokerList().get(i).setTotalqueuedepth(rs.getLong(5));
1671                     res.getBrokerList().get(i).setTotalmessagesdropped(rs.getLong(6));
1672                     res.getBrokerList().get(i).setTotalbytesdropped(rs.getLong(7));
1673                     res.getBrokerList().get(i).setTotalbytesin(rs.getLong(8));
1674                     res.getBrokerList().get(i).setTotalbytesout(rs.getLong(9));
1675 
1676                 }
1677             } catch (Exception ex) {
1678                 log.log(Level.ERROR, null, ex);
1679             } finally {
1680                 DBUtils.safeClose(rs);
1681                 DBUtils.safeClose(com);
1682             }
1683 
1684         }
1685         for (int i = 0; i < res.getBrokerList().size(); i++) {
1686             try {
1687                 // com = con.prepareStatement("select host  from brokerrawdata group by host;");
1688                 com = con.prepareStatement("select count(*) from brokerrawdata where host=?;");
1689                 com.setString(1, res.getBrokerList().get(i).getUri());
1690                 rs = com.executeQuery();
1691                 if (rs.next()) {
1692                     res.getBrokerList().get(i).setNumberOfQueuesTopics(rs.getLong(1));
1693                 }
1694                 rs.close();
1695                 com.close();
1696             } catch (Exception ex) {
1697                 log.log(Level.ERROR, null, ex);
1698             } finally {
1699                 DBUtils.safeClose(rs);
1700                 DBUtils.safeClose(com);
1701             }
1702         }
1703 
1704         con = Utility.getConfigurationDBConnection();
1705 
1706         for (int i = 0; i < res.getBrokerList().size(); i++) {
1707             try {
1708                 com = con.prepareStatement("SELECT utcdatetime, status  FROM status where uri=?;");
1709                 com.setString(1, res.getBrokerList().get(i).getUri());
1710                 rs = com.executeQuery();
1711                 if (rs.next()) {
1712                     GregorianCalendar c = new GregorianCalendar();
1713                     c.setTimeInMillis((long) rs.getLong(1));
1714 
1715                     res.getBrokerList().get(i).setLastCheckIn((c));
1716                     res.getBrokerList().get(i).setOperational(rs.getBoolean(2));
1717                 }
1718             } catch (Exception ex) {
1719                 log.log(Level.ERROR, null, ex);
1720             } finally {
1721                 DBUtils.safeClose(rs);
1722                 DBUtils.safeClose(com);
1723             }
1724 
1725         }
1726         DBUtils.safeClose(con);
1727         res.setClassification(getCurrentClassificationLevel());
1728         return res;
1729 
1730     }
1731 
1732     protected static SecurityWrapper getCurrentClassificationLevel() throws ServiceUnavailableException {
1733         Connection con = Utility.getConfigurationDBConnection();
1734         ResultSet results = null;
1735         PreparedStatement comm = null;
1736         SecurityWrapper ret = new SecurityWrapper();
1737         try {
1738 
1739             comm = con.prepareStatement("Select classification, caveat from GlobalPolicies;");
1740 
1741             /////////////////////////////////////////////
1742             //get the global policy for data retension
1743             /////////////////////////////////////////////
1744             results = comm.executeQuery();
1745 
1746             if (results.next()) {
1747                 ret.setClassification(ClassificationType.fromValue(results.getString("classification")));
1748                 ret.setCaveats(results.getString("caveat"));
1749 
1750                 return ret;
1751             }
1752         } catch (Exception ex) {
1753             log.log(Level.ERROR, "Error setting global policy (no records currently exist", ex);
1754 
1755         } finally {
1756             DBUtils.safeClose(results);
1757             DBUtils.safeClose(comm);
1758             DBUtils.safeClose(con);
1759         }
1760 
1761         try {
1762             con = Utility.getConfigurationDBConnection();
1763             comm = con.prepareStatement("INSERT INTO GlobalPolicies (PolicyRefreshRate, RecordedMessageCap, classification, caveat) " + " VALUES (?, ?, ?, ?);");
1764             comm.setLong(1, 3 * 60 * 100);
1765             comm.setLong(2, 1024000);
1766             comm.setString(3, "U");
1767             comm.setString(4, "None");
1768             comm.execute();
1769             return ret;
1770 
1771         } catch (Exception ex) {
1772             log.log(Level.ERROR, "Error setting global policy (no records currently exist", ex);
1773 
1774         } finally {
1775             DBUtils.safeClose(comm);
1776             DBUtils.safeClose(con);
1777         }
1778         ServiceUnavailableException f = new ServiceUnavailableException("", null);
1779         f.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1780         throw f;
1781     }
1782 
1783     /**
1784      *
1785      *
1786      * Returns the last known data set for a broker
1787      *
1788      *
1789      *
1790      *
1791      *
1792      *
1793      *
1794      * @param getCurrentBrokerDetailsRequest
1795      * @return returns
1796      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetCurrentBrokerDetailsResponseMsg
1797      * @throws ServiceUnavailableException
1798      * @throws AccessDeniedException
1799      */
1800     @WebMethod(operationName = "GetCurrentBrokerDetails", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetCurrentBrokerDetails")
1801     @WebResult(name = "GetCurrentBrokerDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1802     @RequestWrapper(localName = "GetCurrentBrokerDetails", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetCurrentBrokerDetails")
1803     @ResponseWrapper(localName = "GetCurrentBrokerDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetCurrentBrokerDetailsResponse")
1804     public GetCurrentBrokerDetailsResponseMsg getCurrentBrokerDetails(
1805             @WebParam(name = "GetCurrentBrokerDetailsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetCurrentBrokerDetailsRequestMsg getCurrentBrokerDetailsRequest)
1806             throws AccessDeniedException, ServiceUnavailableException {
1807 
1808         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1809         Utility.validateClassification(getCurrentBrokerDetailsRequest.getClassification());
1810         if (Utility.stringIsNullOrEmpty(getCurrentBrokerDetailsRequest.getUrl())) {
1811             throw new IllegalArgumentException("url is null");
1812         }
1813         UserIdentityUtil.assertReadAccess(getCurrentBrokerDetailsRequest.getUrl(), currentUser, "getCurrentBrokerDetails", getCurrentBrokerDetailsRequest.getClassification(), ctx);
1814         AuditLogger.logItem(this.getClass().getCanonicalName(), "getCurrentBrokerDetails", currentUser, getCurrentBrokerDetailsRequest.getUrl(), (getCurrentBrokerDetailsRequest.getClassification()), ctx.getMessageContext());
1815         GetCurrentBrokerDetailsResponseMsg res = new GetCurrentBrokerDetailsResponseMsg();
1816 
1817         Connection con = Utility.getPerformanceDBConnection();
1818         ResultSet rs = null;
1819         PreparedStatement com = null;
1820         try {
1821             com = con.prepareStatement("SELECT *  FROM brokerrawdata where host=?;");
1822             com.setString(1, getCurrentBrokerDetailsRequest.getUrl());
1823             res.setUri(getCurrentBrokerDetailsRequest.getUrl());
1824             rs = com.executeQuery();
1825 
1826             while (rs.next()) {
1827                 QueueORtopicDetails item = new QueueORtopicDetails();
1828                 item.setActiveconsumercount(rs.getLong("activeconsumercount"));
1829                 item.setAgenttype(rs.getString("agenttype"));
1830                 item.setCanonicalname(rs.getString("canonicalname"));
1831                 item.setConsumercount(rs.getLong("consumercount"));
1832                 item.setItemtype(rs.getString("typecol"));
1833                 item.setMessagecount(rs.getLong("messagecount"));
1834                 item.setName(rs.getString("namecol"));
1835                 item.setQueueDepth(rs.getLong("queuedepth"));
1836                 item.setRecievedmessagecount(rs.getLong("recievedmessagecount"));
1837                 GregorianCalendar c = new GregorianCalendar();
1838                 c.setTimeInMillis(rs.getLong("utcdatetime"));
1839                 item.setTimestamp((c));
1840                 item.setBytesdropped(rs.getLong("bytesdropcount"));
1841                 item.setBytesin(rs.getLong("bytesin"));
1842                 item.setBytesout(rs.getLong("bytesout"));
1843                 item.setMessagesdropped(rs.getLong("messagedropcount"));
1844                 res.getQueueORtopicDetails().add(item);
1845             }
1846         } catch (Exception ex) {
1847             log.log(Level.ERROR, null, ex);
1848         } finally {
1849             DBUtils.safeClose(rs);
1850             DBUtils.safeClose(com);
1851             DBUtils.safeClose(con);
1852 
1853         }
1854         con = Utility.getConfigurationDBConnection();
1855         try {
1856             com = con.prepareCall("SELECT status FROM status where uri=?;");
1857             com.setString(1, getCurrentBrokerDetailsRequest.getUrl());
1858             rs = com.executeQuery();
1859             if (rs.next()) {
1860                 res.setOperational(rs.getBoolean("Status"));
1861 
1862             } else {
1863                 //throw unexpected error
1864                 res.setOperational(false);
1865             }
1866             res.setClassification(getCurrentClassificationLevel());
1867 
1868             return res;
1869         } catch (Exception ex) {
1870             log.log(Level.ERROR, null, ex);
1871         } finally {
1872             DBUtils.safeClose(rs);
1873             DBUtils.safeClose(com);
1874             DBUtils.safeClose(con);
1875         }
1876         ServiceUnavailableException code = new ServiceUnavailableException("", null);
1877         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1878         throw code;
1879 
1880     }
1881 
1882     /**
1883      *
1884      *
1885      * Returns the historical data for a specific broker, such as average queue
1886      * depth across all topics and queues, over the given period of time
1887      *
1888      *
1889      *
1890      *
1891      *
1892      *
1893      *
1894      * @param getHistoricalBrokerDetailsRequest
1895      * @return returns
1896      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalBrokerDetailsResponseMsg
1897      * @throws ServiceUnavailableException
1898      * @throws AccessDeniedException
1899      */
1900     @WebMethod(operationName = "GetHistoricalBrokerDetails", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetHistoricalBrokerDetails")
1901     @WebResult(name = "GetHistoricalBrokerDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1902     @RequestWrapper(localName = "GetHistoricalBrokerDetails", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalBrokerDetails")
1903     @ResponseWrapper(localName = "GetHistoricalBrokerDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalBrokerDetailsResponse")
1904     public GetHistoricalBrokerDetailsResponseMsg getHistoricalBrokerDetails(
1905             @WebParam(name = "GetHistoricalBrokerDetailsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetHistoricalBrokerDetailsRequestMsg getHistoricalBrokerDetailsRequest)
1906             throws AccessDeniedException, ServiceUnavailableException {
1907         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1908         Utility.validateClassification(getHistoricalBrokerDetailsRequest.getClassification());
1909         AuditLogger.logItem(this.getClass().getCanonicalName(), "getCurrentBrokerDetails", currentUser, getHistoricalBrokerDetailsRequest.getUri(), (getHistoricalBrokerDetailsRequest.getClassification()), ctx.getMessageContext());
1910         GetHistoricalBrokerDetailsResponseMsg res = new GetHistoricalBrokerDetailsResponseMsg();
1911         if (Utility.stringIsNullOrEmpty(getHistoricalBrokerDetailsRequest.getUri())) {
1912             throw new IllegalArgumentException("url is null");
1913         }
1914         if (getHistoricalBrokerDetailsRequest.getRange() == null) {
1915             throw new IllegalArgumentException("time range is null");
1916         }
1917         UserIdentityUtil.assertReadAccess(getHistoricalBrokerDetailsRequest.getUri(),
1918                 currentUser, "getHistoricalBrokerDetails", getHistoricalBrokerDetailsRequest.getClassification(),
1919                 ctx);
1920         Connection con = Utility.getPerformanceDBConnection();
1921         PreparedStatement com = null;
1922         ResultSet rs = null;
1923         try {
1924             res.setUri(getHistoricalBrokerDetailsRequest.getUri());
1925 
1926             com = con.prepareStatement("select avg(activeconsumercount), avg(consumercount), "
1927                     + "avg(messagecount), avg(recievedmessagecount), avg(queuedepth),  avg(messagedropcount), "
1928                     + "avg(bytesdropcount), avg(bytesin), avg(bytesout) "
1929                     + "from brokerrawdata where host=? "
1930                     + "and (utcdatetime > ?) and (utcdatetime < ?)");
1931             com.setString(1, getHistoricalBrokerDetailsRequest.getUri());
1932             com.setLong(
1933                     2, getHistoricalBrokerDetailsRequest.getRange().getStart().getTimeInMillis());
1934             com.setLong(
1935                     3, getHistoricalBrokerDetailsRequest.getRange().getEnd().getTimeInMillis());
1936             rs = com.executeQuery();
1937             if (rs.next()) {
1938 
1939                 res.setAverageactiveconsumers(rs.getDouble(1));
1940                 // res.setAveragenumberOfQueuesTopics(value)
1941                 res.setAverageconsumers(rs.getDouble(2));
1942                 res.setAveragemessagesent(rs.getDouble(3));
1943                 res.setAveragemessagesrecieved(rs.getDouble(4));
1944                 res.setAveragequeuedepth(rs.getDouble(5));
1945                 res.setAveragemessagesdropped(rs.getDouble(6));
1946                 res.setAveragebytesdropped(rs.getDouble(7));
1947                 res.setAveragebytesin(rs.getDouble(8));
1948                 res.setAveragebytesout(rs.getDouble(9));
1949             }
1950 
1951             res.setClassification(getCurrentClassificationLevel());
1952             return res;
1953         } catch (SQLException ex) {
1954             log.log(Level.ERROR, null, ex);
1955 
1956         } finally {
1957             DBUtils.safeClose(rs);
1958             DBUtils.safeClose(com);
1959             DBUtils.safeClose(con);
1960         }
1961         ServiceUnavailableException code = new ServiceUnavailableException("", null);
1962         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
1963         throw code;
1964     }
1965 
1966     /**
1967      *
1968      *
1969      * Returns the historical data for a specific topic or queue on a specific
1970      * broker Must input either (URI AND topic/queue name) OR (URI AND
1971      * cannoicalname)
1972      *
1973      *
1974      *
1975      *
1976      *
1977      * @param getHistoricalTopicQueueDetailsRequest
1978      * @return returns
1979      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalTopicQueueDetailsResponseMsg
1980      * @throws ServiceUnavailableException
1981      * @throws AccessDeniedException
1982      */
1983     @WebMethod(operationName = "GetHistoricalTopicQueueDetails", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetHistoricalTopicQueueDetails")
1984     @WebResult(name = "GetHistoricalTopicQueueDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
1985     @RequestWrapper(localName = "GetHistoricalTopicQueueDetails", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalTopicQueueDetails")
1986     @ResponseWrapper(localName = "GetHistoricalTopicQueueDetailsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetHistoricalTopicQueueDetailsResponse")
1987     public GetHistoricalTopicQueueDetailsResponseMsg getHistoricalTopicQueueDetails(
1988             @WebParam(name = "GetHistoricalTopicQueueDetailsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetHistoricalTopicQueueDetailsRequestMsg getHistoricalTopicQueueDetailsRequest)
1989             throws AccessDeniedException, ServiceUnavailableException {
1990         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
1991         Utility.validateClassification(getHistoricalTopicQueueDetailsRequest.getClassification());
1992 
1993         GetHistoricalTopicQueueDetailsResponseMsg res = new GetHistoricalTopicQueueDetailsResponseMsg();
1994         res.setClassification(getCurrentClassificationLevel());
1995 
1996         if (getHistoricalTopicQueueDetailsRequest.getUri() == null) {
1997             throw new IllegalArgumentException("uri is null");
1998         }
1999         if (getHistoricalTopicQueueDetailsRequest.getRange() == null) {
2000             throw new IllegalArgumentException("range is null");
2001         }
2002         if (Utility.stringIsNullOrEmpty(getHistoricalTopicQueueDetailsRequest.getQueuetopiccanonicalname()) || Utility.stringIsNullOrEmpty(getHistoricalTopicQueueDetailsRequest.getQueuetopicname())) {
2003             throw new IllegalArgumentException("queue name is null");
2004         }
2005 
2006         String name = "";
2007         if (!Utility.stringIsNullOrEmpty(getHistoricalTopicQueueDetailsRequest.getQueuetopiccanonicalname())) {
2008             name = getHistoricalTopicQueueDetailsRequest.getQueuetopiccanonicalname();
2009         } else {
2010             name = getHistoricalTopicQueueDetailsRequest.getQueuetopicname();
2011         }
2012         AuditLogger.logItem(this.getClass().getCanonicalName(), "getHistoricalTopicQueueDetails", currentUser, getHistoricalTopicQueueDetailsRequest.getQueuetopicname() + getHistoricalTopicQueueDetailsRequest.getQueuetopiccanonicalname(), (getHistoricalTopicQueueDetailsRequest.getClassification()), ctx.getMessageContext());
2013         UserIdentityUtil.assertReadAccess(getHistoricalTopicQueueDetailsRequest.getUri(), currentUser, "getHistoricalTopicQueueDetails", getHistoricalTopicQueueDetailsRequest.getClassification(), ctx);
2014         Connection con = Utility.getPerformanceDBConnection();
2015         PreparedStatement com = null;
2016         ResultSet rs = null;
2017         try {
2018 
2019             com = con.prepareStatement("select * from brokerhistory where  host=? and (utcdatetime > ?) and (utcdatetime < ?) and (name=? or canonicalname=?) order by utcdatetime desc;");
2020             com.setString(1, getHistoricalTopicQueueDetailsRequest.getUri());
2021             com.setLong(2, getHistoricalTopicQueueDetailsRequest.getRange().getStart().getTimeInMillis());
2022             com.setLong(3, getHistoricalTopicQueueDetailsRequest.getRange().getEnd().getTimeInMillis());
2023             com.setString(4, name);
2024             com.setString(5, name);
2025             rs = com.executeQuery();
2026             while (rs.next()) {
2027                 QueueORtopicDetails qt = new QueueORtopicDetails();
2028                 qt.setActiveconsumercount(rs.getLong("activeconsumercount"));
2029                 qt.setAgenttype(rs.getString("agenttype"));
2030                 qt.setBytesdropped(rs.getLong("bytesdropped"));
2031                 qt.setBytesin(rs.getLong("bytesin"));
2032                 qt.setBytesout(rs.getLong("bytesout"));
2033                 qt.setCanonicalname(rs.getString("canonicalname"));
2034                 qt.setName(rs.getString("namecol"));
2035                 qt.setQueueDepth(rs.getLong("queuedepth"));
2036                 qt.setRecievedmessagecount(rs.getLong("reievedmessagecount"));
2037                 GregorianCalendar cal = new GregorianCalendar();
2038                 cal.setTimeInMillis(rs.getLong("utcdatetime"));
2039                 qt.setTimestamp((cal));
2040                 res.getHistoricalTopicQueueDetails().add(qt);
2041             }
2042         } catch (SQLException ex) {
2043             log.log(Level.ERROR, null, ex);
2044 
2045         } finally {
2046             DBUtils.safeClose(rs);
2047             DBUtils.safeClose(com);
2048             DBUtils.safeClose(con);
2049 
2050         }
2051         ServiceUnavailableException code = new ServiceUnavailableException("", null);
2052         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2053         throw code;
2054     }
2055 
2056     /**
2057      *
2058      *
2059      * Returns a listing of fgsms agents that have recorded data
2060      *
2061      *
2062      *
2063      *
2064      *
2065      *
2066      *
2067      * @param getAgentTypesRequest
2068      * @return returns
2069      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetAgentTypesResponseMsg
2070      * @throws ServiceUnavailableException
2071      * @throws AccessDeniedException
2072      */
2073     @WebMethod(operationName = "GetAgentTypes", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAgentTypes")
2074     @WebResult(name = "GetAgentTypesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2075     @RequestWrapper(localName = "GetAgentTypes", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAgentTypes")
2076     @ResponseWrapper(localName = "GetAgentTypesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAgentTypesResponse")
2077     public GetAgentTypesResponseMsg getAgentTypes(
2078             @WebParam(name = "GetAgentTypesRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAgentTypesRequestMsg getAgentTypesRequest)
2079             throws AccessDeniedException, ServiceUnavailableException {
2080         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2081         Utility.validateClassification(getAgentTypesRequest.getClassification());
2082         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAgentTypes", currentUser, "", (getAgentTypesRequest.getClassification()), ctx.getMessageContext());
2083         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getAgentTypes",
2084                 getAgentTypesRequest.getClassification(), ctx);
2085 
2086         Connection con;
2087         con = Utility.getConfigurationDBConnection();
2088         PreparedStatement com = null;
2089         ResultSet rs = null;
2090         try {
2091             com = con.prepareStatement("select * from agents order by agenttype asc;");
2092 
2093             rs = com.executeQuery();
2094             GetAgentTypesResponseMsg res = new GetAgentTypesResponseMsg();
2095             while (rs.next()) {
2096                 String s = rs.getString(1);
2097                 if (!Utility.stringIsNullOrEmpty(s)) {
2098                     res.getAgentType().add(s);
2099                 }
2100             }
2101             res.setClassification(getCurrentClassificationLevel());
2102             return res;
2103         } catch (SQLException ex) {
2104             log.log(Level.ERROR, null, ex);
2105 
2106         } finally {
2107             DBUtils.safeClose(rs);
2108             DBUtils.safeClose(com);
2109             DBUtils.safeClose(con);
2110         }
2111         ServiceUnavailableException code = new ServiceUnavailableException("", null);
2112         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2113         throw code;
2114     }
2115 
2116     /**
2117      *
2118      *
2119      * Returns a listing of related transaction IDs, given a thread transaction
2120      * id
2121      *
2122      *
2123      *
2124      *
2125      *
2126      * @param getThreadTransactionsRequest
2127      * @return returns
2128      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetThreadTransactionsResponseMsg
2129      * @throws AccessDeniedException
2130      * @throws ServiceUnavailableException
2131      */
2132     @WebMethod(operationName = "GetThreadTransactions", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetRelatedTransactions")
2133     @WebResult(name = "GetThreadTransactionsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2134     @RequestWrapper(localName = "GetThreadTransactions", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetThreadTransactions")
2135     @ResponseWrapper(localName = "GetThreadTransactionsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetThreadTransactionsResponse")
2136     public GetThreadTransactionsResponseMsg getThreadTransactions(
2137             @WebParam(name = "GetThreadTransactionsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetThreadTransactionsRequestMsg request)
2138             throws AccessDeniedException, ServiceUnavailableException {
2139 
2140         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2141         Utility.validateClassification(request.getClassification());
2142         AuditLogger.logItem(this.getClass().getCanonicalName(), "getThreadTransactions", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2143         Connection con = Utility.getPerformanceDBConnection();
2144         PreparedStatement com = null;
2145         ResultSet rs = null;
2146         try {
2147 
2148             if (Utility.stringIsNullOrEmpty(request.getId())) {
2149                 throw new IllegalArgumentException("id");
2150             }
2151             com = con.prepareStatement("select uri, success, utcdatetime, responsetimems, soapaction, transactionid from rawdata where threadid=? order by utcdatetime desc;");
2152             com.setString(1, request.getId());
2153             rs = com.executeQuery();
2154             GetThreadTransactionsResponseMsg res = new GetThreadTransactionsResponseMsg();
2155             while (rs.next()) {
2156                 ThreadTime tt = new ThreadTime();
2157                 tt.setAction(rs.getString("soapaction"));
2158                 //tt.set
2159                 tt.setUri(rs.getString("uri"));
2160 
2161                 tt.setTransactionid(rs.getString("transactionid"));
2162                 tt.setResponsetimems(rs.getLong("responsetimems"));
2163                 tt.setSuccess(rs.getBoolean("success"));
2164                 GregorianCalendar gcal = new GregorianCalendar();
2165                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
2166                 tt.setTimestamp((gcal));
2167                 if (UserIdentityUtil.hasReadAccess(currentUser, "getThreadTransactions",tt.getUri(), 
2168                         request.getClassification(), ctx)) {
2169                     res.getThreads().add(tt);
2170                 }
2171             }
2172 
2173             res.setClassification(getCurrentClassificationLevel());
2174             return res;
2175         } catch (SQLException ex) {
2176             log.log(Level.ERROR, null, ex);
2177         } finally {
2178             DBUtils.safeClose(rs);
2179             DBUtils.safeClose(com);
2180             DBUtils.safeClose(con);
2181         }
2182 
2183         ServiceUnavailableException code = new ServiceUnavailableException("", null);
2184 
2185         code.getFaultInfo()
2186                 .setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2187         throw code;
2188 
2189     }
2190 
2191     /**
2192      *
2193      *
2194      * quickly returns statistics for a given service *
2195      *
2196      *
2197      *
2198      *
2199      *
2200      * @param getQuickStatsRequest
2201      * @return returns
2202      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsResponseMsg
2203      * @throws AccessDeniedException
2204      * @throws ServiceUnavailableException
2205      */
2206     @WebMethod(operationName = "GetQuickStats", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetQuickStats")
2207     @WebResult(name = "GetQuickStatsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2208     @RequestWrapper(localName = "GetQuickStats", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStats")
2209     @ResponseWrapper(localName = "GetQuickStatsResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsResponse")
2210     public GetQuickStatsResponseMsg getQuickStats(
2211             @WebParam(name = "GetQuickStatsRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetQuickStatsRequestMsg getQuickStatsRequest)
2212             throws AccessDeniedException, ServiceUnavailableException {
2213 
2214         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2215         Utility.validateClassification(getQuickStatsRequest.getClassification());
2216         if (!UserIdentityUtil.isTrustedAgent(currentUser, "getQuickStats", getQuickStatsRequest.getClassification(), ctx)) {
2217             UserIdentityUtil.assertReadAccess(getQuickStatsRequest.getUri(), currentUser, "getQuickStats", getQuickStatsRequest.getClassification(), ctx);
2218         }
2219 
2220         if (Utility.stringIsNullOrEmpty(getQuickStatsRequest.getUri())) {
2221             throw new IllegalArgumentException("uri");
2222         }
2223         AuditLogger.logItem(this.getClass().getCanonicalName(), "getQuickStats", currentUser, getQuickStatsRequest.getUri(), (getQuickStatsRequest.getClassification()), ctx.getMessageContext());
2224 
2225         return fetchQuickStat(getQuickStatsRequest.getUri(), getQuickStatPeriods(), false);
2226 
2227     }
2228 
2229     /**
2230      * returns all of the current time periods used for statistics aggregation
2231      *
2232      * @return
2233      */
2234     private List<Long> getQuickStatPeriods() {
2235         List<Long> periods = new ArrayList<Long>();
2236         try {
2237             KeyNameValueEnc GetPropertiesFromDB = DBSettingsLoader.GetPropertiesFromDB(true, "StatisticsAggregator", "Periods");
2238             String[] items = GetPropertiesFromDB.getKeyNameValue().getPropertyValue().split(",");
2239             for (int i = 0; i < items.length; i++) {
2240                 long l = Long.parseLong(items[i]);
2241                 if (l > 0) {
2242                     periods.add(l);
2243                 }
2244             }
2245             periods.add(Long.valueOf(5 * 60 * 1000));
2246             periods.add(Long.valueOf(15 * 60 * 1000));
2247             periods.add(Long.valueOf(60 * 60 * 1000));
2248             periods.add(Long.valueOf(24 * 60 * 60 * 1000));
2249 
2250             Set<Long> minified = new HashSet<Long>(periods);
2251             periods = new ArrayList<Long>(minified);
2252         } catch (Exception e) {
2253             log.log(Level.INFO, "Statistics settings from the database for time periods was unparsable, reverting to the defaults.");
2254             periods.add(Long.valueOf(5 * 60 * 1000));
2255             periods.add(Long.valueOf(15 * 60 * 1000));
2256             periods.add(Long.valueOf(60 * 60 * 1000));
2257             periods.add(Long.valueOf(24 * 60 * 60 * 1000));
2258         }
2259         Collections.sort(periods);
2260         return periods;
2261     }
2262 
2263     private GetQuickStatsResponseMsg fetchQuickStat(String url, List<Long> periods, boolean allmethodsonly) throws ServiceUnavailableException {
2264         Connection con = Utility.getPerformanceDBConnection();
2265         PreparedStatement com = null;
2266         ResultSet rs = null;
2267         try {
2268 
2269             //Load flexible quick stat periods
2270             GetQuickStatsResponseMsg res = new GetQuickStatsResponseMsg();
2271 
2272             res.setUri(url);
2273 
2274             List<String> actions = new ArrayList<String>();
2275             if (!allmethodsonly) {
2276                 DASHelper.addServiceActionsFromDB(actions, url);
2277             }
2278             actions.add("All-Methods");
2279 
2280             Duration uptime = DASHelper.getUpTime(url);
2281             QuickStatWrapper w = null;// = new QuickStatWrapper();
2282             for (int i = 0; i < actions.size(); i++) {
2283                 w = new QuickStatWrapper();
2284                 w.setAction(actions.get(i));
2285                 w.setUptime(uptime);
2286 
2287                 for (int k = 0; k < periods.size(); k++) {
2288                     try {
2289                         com = con.prepareStatement("select * from agg2 where uri=? and soapaction=? and timerange=?;");
2290                         com.setString(1, url);
2291                         com.setString(2, actions.get(i));
2292                         com.setLong(3, periods.get(k));
2293                         rs = com.executeQuery();
2294 
2295                         while (rs.next()) {
2296 
2297                             QuickStatData d = new QuickStatData();
2298                             Long x = periods.get(k) / (60 * 1000);
2299                             d.setTimeInMinutes(BigInteger.valueOf(x));
2300                             d.setAvailabilityPercentage(rs.getDouble("avail"));
2301                             d.setFailureCount(rs.getLong("failure"));
2302                             d.setSuccessCount(rs.getLong("success"));
2303                             d.setSLAViolationCount(rs.getLong("sla"));
2304                             if (d.getSLAViolationCount() < 0) {
2305                                 d.setSLAViolationCount(0);
2306                             }
2307 
2308                             d.setAverageResponseTime(rs.getLong("avgres"));
2309                             d.setMTBF(df.newDuration(rs.getLong("mtbf")));
2310                             d.setMaximumRequestSize(rs.getLong("maxreq"));
2311                             d.setMaximumResponseSize(rs.getLong("maxres"));
2312                             d.setMaximumResponseTime(rs.getLong("maxresponsetime"));
2313                             GregorianCalendar gcal = new GregorianCalendar();
2314                             gcal.setTimeInMillis(rs.getLong("timestampepoch"));
2315                             d.setUpdatedAt((gcal));
2316 
2317                             d.setAverageCPUUsage(rs.getDouble("avgcpu"));
2318                             d.setAverageMemoryUsage(rs.getLong("avgmem"));
2319                             d.setAverageThreadCount(rs.getLong("avgthread"));
2320                             d.setAverageOpenFileCount(rs.getLong("avgfile"));
2321 
2322                             d.setAverageMessagesIn(rs.getLong("avgmsgin"));
2323                             d.setAverageMessagesOut(rs.getLong("avgmsgout"));
2324                             d.setAverageMessagesDropped(rs.getLong("avgmsgdropped"));
2325                             d.setLargestQueueDepth(rs.getLong("maxqueuedepth"));
2326                             w.getQuickStatData().add(d);
2327                         }
2328                     } catch (Exception ex) {
2329                         log.log(Level.ERROR, "unexpected SQL error", ex);
2330                     } finally {
2331                         DBUtils.safeClose(rs);
2332                         DBUtils.safeClose(com);
2333                     }
2334 
2335                 }   //end of for each period/timerange 
2336                 res.getQuickStatWrapper().add(w);
2337             } //for each action
2338 
2339             res.setClassification(getCurrentClassificationLevel());
2340             return res;
2341         } catch (Exception ex) {
2342             log.log(Level.ERROR, null, ex);
2343             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2344             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2345             throw code;
2346         } finally {
2347             DBUtils.safeClose(con);
2348         }
2349     }
2350 
2351     private String getPolicyDisplayName(String uRL) {
2352         Connection con = Utility.getConfigurationDBConnection();
2353         PreparedStatement com = null;
2354         ResultSet rs = null;
2355         try {
2356             com = con.prepareStatement("select displayname from servicepolicies where uri=?;");
2357             com.setString(1, uRL);
2358             rs = com.executeQuery();
2359             if (rs.next()) {
2360                 String s = rs.getString(1);
2361                 rs.close();
2362                 com.close();
2363                 con.close();
2364                 return s;
2365             }
2366             rs.close();
2367             com.close();
2368         } catch (Exception ex) {
2369             log.log(Level.WARN, "couldn't get the display name for " + uRL, ex);
2370 
2371         } finally {
2372             DBUtils.safeClose(rs);
2373             DBUtils.safeClose(com);
2374             DBUtils.safeClose(con);
2375         }
2376 
2377         return null;
2378 
2379     }
2380 
2381     /**
2382      *
2383      *
2384      * quickly returns statistics for all accessible services *
2385      *
2386      *
2387      *
2388      *
2389      *
2390      * @param getQuickStatsAllRequest
2391      * @return returns
2392      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsAllResponseMsg
2393      * @throws AccessDeniedException
2394      * @throws ServiceUnavailableException
2395      */
2396     @WebMethod(operationName = "GetQuickStatsAll", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetQuickStatsAll")
2397     @WebResult(name = "GetQuickStatsAllResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2398     @RequestWrapper(localName = "GetQuickStatsAll", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsAll")
2399     @ResponseWrapper(localName = "GetQuickStatsAllResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetQuickStatsAllResponse")
2400     public GetQuickStatsAllResponseMsg getQuickStatsAll(
2401             @WebParam(name = "GetQuickStatsAllRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetQuickStatsAllRequestMsg getQuickStatsAllRequest)
2402             throws AccessDeniedException, ServiceUnavailableException {
2403 
2404         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2405         Utility.validateClassification(getQuickStatsAllRequest.getClassification());
2406         GetQuickStatsAllResponseMsg res2 = new GetQuickStatsAllResponseMsg();
2407         res2.setClassification(getCurrentClassificationLevel());
2408         AuditLogger.logItem(this.getClass().getCanonicalName(), "getQuickStatsAllRequest", currentUser, "", (getQuickStatsAllRequest.getClassification()), ctx.getMessageContext());
2409         List<Long> periods = getQuickStatPeriods();
2410 
2411         ArrayOfServiceType temp = DASHelper.getServiceListfromPolicyDB(ctx, getQuickStatsAllRequest.getClassification());
2412         if (temp == null || temp.getServiceType().isEmpty()) {
2413             return res2;
2414         }
2415 
2416         ArrayOfServiceType urls = temp;
2417         for (int i = 0; i < urls.getServiceType().size(); i++) {
2418             GetQuickStatsResponseMsg w2 = fetchQuickStat(urls.getServiceType().get(i).getURL(), periods, getQuickStatsAllRequest.isAllMethodsOnly());
2419             QuickStatURIWrapper wrapper = new QuickStatURIWrapper();
2420             wrapper.setUri(urls.getServiceType().get(i).getURL());
2421             wrapper.getQuickStatWrapper().addAll(w2.getQuickStatWrapper());
2422             res2.getQuickStatURIWrapper().add(wrapper);
2423 
2424         } //for each service
2425 
2426         //con.close();
2427         return res2;
2428 
2429     }
2430 
2431     /**
2432      *
2433      *
2434      * obtain audit logs by time range, requires global admin role *
2435      *
2436      *
2437      *
2438      *
2439      *
2440      * @param getAuditLogsByTimeRangeRequest
2441      * @return returns
2442      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLogsByTimeRangeResponseMsg
2443      * @throws AccessDeniedException
2444      * @throws ServiceUnavailableException
2445      */
2446     @WebMethod(operationName = "GetAuditLogsByTimeRange", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAuditLogsByTimeRange")
2447     @WebResult(name = "GetAuditLogsByTimeRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2448     @RequestWrapper(localName = "GetAuditLogsByTimeRange", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLogsByTimeRange")
2449     @ResponseWrapper(localName = "GetAuditLogsByTimeRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAuditLogsByTimeRangeResponse")
2450     public GetAuditLogsByTimeRangeResponseMsg getAuditLogsByTimeRange(
2451             @WebParam(name = "GetAuditLogsByTimeRangeRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAuditLogsByTimeRangeRequestMsg getAuditLogsByTimeRangeRequest)
2452             throws AccessDeniedException, ServiceUnavailableException {
2453         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2454         if (getAuditLogsByTimeRangeRequest == null) {
2455             throw new IllegalArgumentException("null message");
2456         }
2457         Utility.validateClassification(getAuditLogsByTimeRangeRequest.getClassification());
2458         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAuditLogsByTimeRangeRequest", currentUser, "read audit logs", (getAuditLogsByTimeRangeRequest.getClassification()), ctx.getMessageContext());
2459         UserIdentityUtil.assertGlobalAuditRole(currentUser, "getAuditLogsByTimeRangeRequest", (getAuditLogsByTimeRangeRequest.getClassification()), ctx);
2460         GetAuditLogsByTimeRangeResponseMsg ret = new GetAuditLogsByTimeRangeResponseMsg();
2461         Connection con = Utility.getConfigurationDBConnection();
2462         PreparedStatement com = null;
2463         ResultSet rs = null;
2464         try {
2465 
2466             long count = 100;
2467             long offset = 0;
2468             if (getAuditLogsByTimeRangeRequest.getRecordcount() >= 1) {
2469                 count = getAuditLogsByTimeRangeRequest.getRecordcount();
2470             }
2471             if (getAuditLogsByTimeRangeRequest.getOffset() < 0) {
2472                 offset = 0;
2473             } else {
2474                 offset = getAuditLogsByTimeRangeRequest.getOffset();
2475             }
2476             if (getAuditLogsByTimeRangeRequest.getRange() == null
2477                     || getAuditLogsByTimeRangeRequest.getRange().getEnd() == null
2478                     || getAuditLogsByTimeRangeRequest.getRange().getStart() == null) {
2479                 throw new IllegalArgumentException("null time range");
2480             }
2481 
2482             com = con.prepareStatement(" SELECT utcdatetime, username, classname, method, memo, "
2483                     + "classification, ipaddress FROM auditlog where utcdatetime > ? and utcdatetime < ? order by utcdatetime desc limit ? offset ?;");
2484             com.setLong(1, getAuditLogsByTimeRangeRequest.getRange().getStart().getTimeInMillis());
2485             com.setLong(2, getAuditLogsByTimeRangeRequest.getRange().getEnd().getTimeInMillis());
2486             com.setLong(3, count);
2487             com.setLong(4, offset);
2488 
2489             rs = com.executeQuery();
2490 
2491             while (rs.next()) {
2492 
2493                 AuditLog e = new AuditLog();
2494                 e.setClassification(rs.getString("classification"));
2495                 e.setClazz(rs.getString("classname"));
2496                 e.setIpaddress(rs.getString("ipaddress"));
2497                 e.setUsername(rs.getString("username"));
2498                 e.setMethod(rs.getString("method"));
2499                 e.setMemo(new String(rs.getBytes("memo"), Constants.CHARSET));
2500                 GregorianCalendar cal = new GregorianCalendar();
2501                 cal.setTimeInMillis(rs.getLong("utcdatetime"));
2502                 e.setTimestamp((cal));
2503                 ret.getAuditLog().add(e);
2504 
2505             }
2506 
2507             ret.setClassification(getCurrentClassificationLevel());
2508             return ret;
2509         } catch (IllegalArgumentException ex) {
2510             log.log(Level.INFO, ex.getMessage());
2511             throw ex;
2512 
2513         } catch (Exception ex) {
2514             log.log(Level.ERROR, null, ex);
2515 
2516         } finally {
2517             DBUtils.safeClose(rs);
2518             DBUtils.safeClose(com);
2519             DBUtils.safeClose(con);
2520         }
2521 
2522         ServiceUnavailableException code = new ServiceUnavailableException("", null);
2523         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2524         throw code;
2525     }
2526 
2527     /**
2528      *
2529      * get all machines in a given domain plus drive info
2530      *
2531      *
2532      * @param getMostRecentMachineDataByDomainRequest
2533      * @return returns
2534      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineDataByDomainResponseMsg
2535      * @throws AccessDeniedException
2536      * @throws ServiceUnavailableException
2537      */
2538     @WebMethod(operationName = "GetMostRecentMachineDataByDomain", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMostRecentMachineDataByDomain")
2539     @WebResult(name = "GetMostRecentMachineDataByDomainResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2540     @RequestWrapper(localName = "GetMostRecentMachineDataByDomain", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineDataByDomain")
2541     @ResponseWrapper(localName = "GetMostRecentMachineDataByDomainResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineDataByDomainResponse")
2542     public GetMostRecentMachineDataByDomainResponseMsg getMostRecentMachineDataByDomain(
2543             @WebParam(name = "GetMostRecentMachineDataByDomainRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMostRecentMachineDataByDomainRequestMsg request)
2544             throws AccessDeniedException, ServiceUnavailableException {
2545         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2546         if (request == null) {
2547             throw new IllegalArgumentException("null message");
2548         }
2549         if (Utility.stringIsNullOrEmpty(request.getDomain())) {
2550             throw new IllegalArgumentException("null domain. use unspecified for domains that are not identified");
2551         }
2552         Utility.validateClassification(request.getClassification());
2553         AuditLogger.logItem(this.getClass().getCanonicalName(), "getMostRecentMachineDataByDomain", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2554         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMostRecentMachineDataByDomain", (request.getClassification()), ctx);
2555 
2556         GetMostRecentMachineDataByDomainResponseMsg ret = new GetMostRecentMachineDataByDomainResponseMsg();
2557 
2558         //get all urls with policy type =machine
2559         Connection con = Utility.getConfigurationDBConnection();
2560         PreparedStatement com = null;
2561         ResultSet rs = null;
2562         try {
2563 
2564             //this.GetServiceListfromPolicyDB(null, PolicyType.STATUS, currentUser)
2565             com = con.prepareStatement(" SELECT * from servicepolicies where policytype=? and domaincol=?;");
2566             com.setInt(1, PolicyType.MACHINE.ordinal());
2567             com.setString(2, request.getDomain());
2568 
2569             rs = com.executeQuery();
2570 
2571             while (rs.next()) {
2572                 MachineData d = new MachineData();
2573                 d.setHostname(rs.getString("hostname"));
2574                 d.setDomainName(rs.getString("domaincol"));
2575                 ret.getMachineData().add(d);
2576             }
2577 
2578             for (int i = 0; i < ret.getMachineData().size(); i++) {
2579                 //get machine performance
2580                 MachinePolicy mp = (MachinePolicy) SLACommon.LoadPolicyPooled("urn:" + ret.getMachineData().get(i).getHostname() + ":system");
2581                 ret.getMachineData().get(i).setMachinePerformanceData(getCurrentMachinePerformanceData(mp));
2582 
2583                 //get all monitored processes on this machine
2584                 //    List<String> processURLlist = GetProcessListByHostname(ret.getMachineData().get(i).getHostname(), ret.getMachineData().get(i).getDomainName());
2585                 ret.getMachineData().get(i).getProcessPerformanceData().addAll((getCurrentProcessPerformanceDataList(getProcessListByHostname(ret.getMachineData().get(i).getHostname(), ret.getMachineData().get(i).getDomainName()))));
2586                 //get performance for each monitpored process
2587                 //get al drive infomration
2588                 ret.getMachineData().get(i).getDriveInformation().addAll(getCurrentDriveInformation(ret.getMachineData().get(i).getHostname(), ret.getMachineData().get(i).getDomainName()));
2589             }
2590 
2591             ret.setClassification(getCurrentClassificationLevel());
2592             return ret;
2593         } catch (SQLException ex) {
2594             log.log(Level.ERROR, null, ex);
2595 
2596         } finally {
2597             DBUtils.safeClose(rs);
2598             DBUtils.safeClose(com);
2599             DBUtils.safeClose(con);
2600         }
2601         ServiceUnavailableException code = new ServiceUnavailableException("", null);
2602         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
2603         throw code;
2604     }
2605 
2606     /**
2607      *
2608      * machine's perf data plus drive usage
2609      *
2610      *
2611      * @param getMostRecentMachineDataRequest
2612      * @return returns
2613      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineDataResponseMsg
2614      * @throws AccessDeniedException
2615      * @throws ServiceUnavailableException
2616      */
2617     @WebMethod(operationName = "GetMostRecentMachineData", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMostRecentMachineData")
2618     @WebResult(name = "GetMostRecentMachineDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2619     @RequestWrapper(localName = "GetMostRecentMachineData", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineData")
2620     @ResponseWrapper(localName = "GetMostRecentMachineDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentMachineDataResponse")
2621     public GetMostRecentMachineDataResponseMsg getMostRecentMachineData(
2622             @WebParam(name = "GetMostRecentMachineDataRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMostRecentMachineDataRequestMsg request)
2623             throws AccessDeniedException, ServiceUnavailableException {
2624 
2625         try {
2626             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2627             if (request == null) {
2628                 throw new IllegalArgumentException("null message");
2629             }
2630             if (Utility.stringIsNullOrEmpty(request.getUri()) && (Utility.stringIsNullOrEmpty(request.getHostname()) || Utility.stringIsNullOrEmpty(request.getDomainname()))) {
2631                 throw new IllegalArgumentException("the uri must be specified.");
2632             }
2633 
2634             String hostname = request.getHostname();
2635             String domainname = request.getDomainname();
2636             String uri = request.getUri();
2637             if (!Utility.stringIsNullOrEmpty(uri)) {
2638                 Pair p = translateURItoPair(uri);
2639                 if (p == null) {
2640                     throw new IllegalArgumentException("the specific URI is not known");
2641                 }
2642                 hostname = p.hostname;
2643                 domainname = p.domainname;
2644             }
2645 
2646             Utility.validateClassification(request.getClassification());
2647             AuditLogger.logItem(this.getClass().getCanonicalName(), "getMostRecentMachineData", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2648             //UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMostRecentMachineData", (request.getClassification()), ctx);
2649             UserIdentityUtil.assertReadAccess(uri, currentUser, "getMostRecentMachineData", request.getClassification(), ctx);
2650             GetMostRecentMachineDataResponseMsg ret = new GetMostRecentMachineDataResponseMsg();
2651             MachineData d = new MachineData();
2652             d.setDomainName(domainname);
2653             d.setHostname(hostname);
2654             ServicePolicy sp = SLACommon.LoadPolicyPooled(uri);
2655             if (!(sp instanceof MachinePolicy)) {
2656                 throw new IllegalArgumentException("The requested URL is not of type Machine Policy");
2657             }
2658             MachinePolicy mp = (MachinePolicy) sp;
2659             d.getDriveInformation().addAll(getCurrentDriveInformation(mp));
2660             d.setMachinePerformanceData(getCurrentMachinePerformanceData(mp));
2661             //d.getProcessPerformanceData().addAll(GetCurrentProcessPerformanceDataList());
2662             ret.setMachineData(d);
2663             ret.setClassification(getCurrentClassificationLevel());
2664             return ret;
2665         } catch (Exception ex) {
2666             log.log(Level.ERROR, null, ex);
2667             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2668             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2669             throw code;
2670         }
2671 
2672     }
2673 
2674     /**
2675      *
2676      * process's perf data
2677      *
2678      *
2679      * @param getMostRecentProcessDataRequest
2680      * @return returns
2681      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentProcessDataResponseMsg
2682      * @throws AccessDeniedException
2683      * @throws ServiceUnavailableException
2684      */
2685     @WebMethod(operationName = "GetMostRecentProcessData", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMostRecentProcessData")
2686     @WebResult(name = "GetMostRecentProcessDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2687     @RequestWrapper(localName = "GetMostRecentProcessData", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentProcessData")
2688     @ResponseWrapper(localName = "GetMostRecentProcessDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMostRecentProcessDataResponse")
2689     public GetMostRecentProcessDataResponseMsg getMostRecentProcessData(
2690             @WebParam(name = "GetMostRecentProcessDataRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMostRecentProcessDataRequestMsg request)
2691             throws AccessDeniedException, ServiceUnavailableException {
2692 
2693         try {
2694             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2695             if (request == null) {
2696                 throw new IllegalArgumentException("null message");
2697             }
2698             if (Utility.stringIsNullOrEmpty(request.getUri())) {
2699                 throw new IllegalArgumentException("null uri. a process uri must be specified");
2700             }
2701 
2702             Utility.validateClassification(request.getClassification());
2703             AuditLogger.logItem(this.getClass().getCanonicalName(), "getMostRecentProcessData", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2704             //UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMostRecentProcessData", (request.getClassification()), ctx);
2705             UserIdentityUtil.assertReadAccess(request.getUri(), currentUser, "getMostRecentProcessData", request.getClassification(), ctx);
2706             GetMostRecentProcessDataResponseMsg ret = new GetMostRecentProcessDataResponseMsg();
2707             ret.setPerformanceData(getCurrentProcessPerformanceDataList(request.getUri()));
2708             ret.setClassification(getCurrentClassificationLevel());
2709             return ret;
2710         } catch (DatatypeConfigurationException ex) {
2711             log.log(Level.ERROR, null, ex);
2712             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2713             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2714             throw code;
2715         }
2716     }
2717 
2718     /**
2719      *
2720      * returns performance and drive information logs of a specific machine
2721      * records by uri and time range
2722      *
2723      *
2724      * @param getMachinePerformanceLogsByRangeRequest
2725      * @return returns
2726      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetMachinePerformanceLogsByRangeResponseMsg
2727      * @throws AccessDeniedException
2728      * @throws ServiceUnavailableException
2729      */
2730     @WebMethod(operationName = "GetMachinePerformanceLogsByRange", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetMachinePerformanceLogsByRange")
2731     @WebResult(name = "GetMachinePerformanceLogsByRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2732     @RequestWrapper(localName = "GetMachinePerformanceLogsByRange", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMachinePerformanceLogsByRange")
2733     @ResponseWrapper(localName = "GetMachinePerformanceLogsByRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetMachinePerformanceLogsByRangeResponse")
2734     public GetMachinePerformanceLogsByRangeResponseMsg getMachinePerformanceLogsByRange(
2735             @WebParam(name = "GetMachinePerformanceLogsByRangeRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetMachinePerformanceLogsByRangeRequestMsg request)
2736             throws AccessDeniedException, ServiceUnavailableException {
2737 
2738         try {
2739             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2740             if (request == null) {
2741                 throw new IllegalArgumentException("null message");
2742             }
2743             if (Utility.stringIsNullOrEmpty(request.getUri())) {
2744                 throw new IllegalArgumentException("null uri. a process uri must be specified");
2745             }
2746             long offset = 0;
2747             if (request.getOffset() > 0) {
2748                 offset = request.getOffset();
2749             }
2750             long records = 100;
2751             if (request.getRecordcount() < 0) {
2752                 records = 1;
2753             }
2754             if (request.getRecordcount() > 1000) {
2755                 records = 1000;
2756             }
2757             if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
2758                 throw new IllegalArgumentException("Missing input parameters");
2759             }
2760             Utility.validateClassification(request.getClassification());
2761             AuditLogger.logItem(this.getClass().getCanonicalName(), "getMachinePerformanceLogsByRange", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2762             //    UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getMachinePerformanceLogsByRange", (request.getClassification()), ctx);
2763             UserIdentityUtil.assertReadAccess(request.getUri(), currentUser, "getMachinePerformanceLogsByRange", (request.getClassification()), ctx);
2764             GetMachinePerformanceLogsByRangeResponseMsg ret = GetMachinePerfLogsByRange(request.getUri(), request.getRange(), offset, records);
2765 
2766             ret.setClassification(getCurrentClassificationLevel());
2767             return ret;
2768         } catch (DatatypeConfigurationException ex) {
2769             log.log(Level.ERROR, null, ex);
2770             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2771             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2772             throw code;
2773         }
2774 
2775     }
2776 
2777     /**
2778      *
2779      * returns the most recent information for all machine and processes that
2780      * the requestor has access to
2781      *
2782      *
2783      * @param getAllMostRecentMachineAndProcessDataRequest
2784      * @return returns
2785      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllMostRecentMachineAndProcessDataResponseMsg
2786      * @throws AccessDeniedException
2787      * @throws ServiceUnavailableException
2788      */
2789     @WebMethod(operationName = "GetAllMostRecentMachineAndProcessData", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAllMostRecentMachineAndProcessData")
2790     @WebResult(name = "GetAllMostRecentMachineAndProcessDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2791     @RequestWrapper(localName = "GetAllMostRecentMachineAndProcessData", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllMostRecentMachineAndProcessData")
2792     @ResponseWrapper(localName = "GetAllMostRecentMachineAndProcessDataResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllMostRecentMachineAndProcessDataResponse")
2793     public GetAllMostRecentMachineAndProcessDataResponseMsg getAllMostRecentMachineAndProcessData(
2794             @WebParam(name = "GetAllMostRecentMachineAndProcessDataRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAllMostRecentMachineAndProcessDataRequestMsg request)
2795             throws AccessDeniedException, ServiceUnavailableException {
2796 
2797         try {
2798             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2799             if (request == null) {
2800                 throw new IllegalArgumentException("null message");
2801             }
2802 
2803             Utility.validateClassification(request.getClassification());
2804             AuditLogger.logItem(this.getClass().getCanonicalName(), "getAllMostRecentMachineAndProcessData", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2805 
2806             //TODO reduce to AssertRead access with filtering based on user
2807             UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getAllMostRecentMachineAndProcessData", (request.getClassification()), ctx);
2808             GetAllMostRecentMachineAndProcessDataResponseMsg ret = new GetAllMostRecentMachineAndProcessDataResponseMsg();
2809             ArrayOfServiceType machines = DASHelper.getServiceListfromPolicyDB(ctx, request.getClassification(), PolicyType.MACHINE);
2810             if (machines != null) {
2811                 for (int i = 0; i < machines.getServiceType().size(); i++) {
2812                     ServicePolicy md = SLACommon.LoadPolicyPooled(machines.getServiceType().get(i).getURL());
2813                     MachineData data = new MachineData();
2814                     data.setDomainName(md.getDomainName());
2815                     data.setHostname(md.getMachineName());
2816                     data.setMachinePerformanceData(getCurrentMachinePerformanceData((MachinePolicy) md));
2817                     ArrayOfServiceType processes = DASHelper.getServiceListfromPolicyDB(ctx, request.getClassification(), PolicyType.PROCESS, md.getMachineName());
2818                     if (processes != null) {
2819                         for (int k = 0; k < processes.getServiceType().size(); k++) {
2820                             ProcessPerformanceData ppd = this.getCurrentProcessPerformanceDataList(processes.getServiceType().get(k).getURL());
2821                             data.getProcessPerformanceData().add(ppd);
2822                         }
2823                     }
2824                     ret.getMachineData().add(data);
2825                 }
2826             }
2827             ret.setClassification(getCurrentClassificationLevel());
2828             return ret;
2829         } catch (DatatypeConfigurationException ex) {
2830             log.log(Level.ERROR, null, ex);
2831             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2832             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2833             throw code;
2834         } catch (Exception ex) {
2835             log.log(Level.ERROR, null, ex);
2836             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2837             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2838             throw code;
2839         }
2840     }
2841 
2842     /**
2843      *
2844      * returns performance logs of a specific process records by uri and time
2845      * range
2846      *
2847      *
2848      * @param getProcessPerformanceLogsByRangeRequest
2849      * @return returns
2850      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetProcessPerformanceLogsByRangeResponseMsg
2851      * @throws AccessDeniedException
2852      * @throws ServiceUnavailableException
2853      */
2854     @WebMethod(operationName = "GetProcessPerformanceLogsByRange", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetProcessPerformanceLogsByRange")
2855     @WebResult(name = "GetProcessPerformanceLogsByRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
2856     @RequestWrapper(localName = "GetProcessPerformanceLogsByRange", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetProcessPerformanceLogsByRange")
2857     @ResponseWrapper(localName = "GetProcessPerformanceLogsByRangeResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetProcessPerformanceLogsByRangeResponse")
2858     public GetProcessPerformanceLogsByRangeResponseMsg getProcessPerformanceLogsByRange(
2859             @WebParam(name = "GetProcessPerformanceLogsByRangeRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetProcessPerformanceLogsByRangeRequestMsg request)
2860             throws AccessDeniedException, ServiceUnavailableException {
2861 
2862         if (request == null) {
2863             throw new IllegalArgumentException("null message");
2864         }
2865         if (Utility.stringIsNullOrEmpty(request.getUri())) {
2866             throw new IllegalArgumentException("null uri. a process uri must be specified");
2867         }
2868         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
2869         long offset = 0;
2870         if (request.getOffset() > 0) {
2871             offset = request.getOffset();
2872         }
2873         long records = 100;
2874         if (request.getRecordcount() < 0) {
2875             records = 1;
2876         }
2877         if (request.getRecordcount() > 1000) {
2878             records = 1000;
2879         }
2880         if (request.getRange() == null || request.getRange().getEnd() == null || request.getRange().getStart() == null) {
2881             throw new IllegalArgumentException("Missing input parameters");
2882         }
2883 
2884         Utility.validateClassification(request.getClassification());
2885         AuditLogger.logItem(this.getClass().getCanonicalName(), "getProcessPerformanceLogsByRange", currentUser, "", (request.getClassification()), ctx.getMessageContext());
2886         //    UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getProcessPerformanceLogsByRange", (request.getClassification()), ctx);
2887         UserIdentityUtil.assertReadAccess(request.getUri(), currentUser, "getProcessPerformanceLogsByRange", (request.getClassification()), ctx);
2888 
2889         try {
2890             GetProcessPerformanceLogsByRangeResponseMsg ret = new GetProcessPerformanceLogsByRangeResponseMsg();
2891             ret.setInstalledMemory(this.getMachineInstalledRam(SLACommon.LoadPolicyPooled(request.getUri()).getMachineName()));
2892             ret.getProcessData().addAll(this.GetProcessPerformanceDataList(request.getUri(), request.getRange(), offset, records));
2893 
2894             ret.setClassification(getCurrentClassificationLevel());
2895             return ret;
2896         } catch (DatatypeConfigurationException ex) {
2897             log.log(Level.ERROR, null, ex);
2898             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2899             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2900             throw code;
2901         } catch (Exception ex) {
2902             log.log(Level.ERROR, null, ex);
2903             ServiceUnavailableException code = new ServiceUnavailableException("", null);
2904             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
2905             throw code;
2906         }
2907     }
2908 
2909     /**
2910      * used to load installed ram on a given system
2911      *
2912      * @param hostname
2913      * @return
2914      */
2915     protected long getMachineInstalledRam(String hostname) {
2916         long ret = -1;
2917         Connection con = Utility.getConfigurationDBConnection();
2918         PreparedStatement comm = null;
2919         ResultSet rs = null;
2920 
2921         try {
2922 
2923             comm = con.prepareStatement(""
2924                     + "select * from machineinfo where hostname=?;");
2925             comm.setString(1, hostname);
2926             rs = comm.executeQuery();
2927             if (rs.next()) {
2928                 Unmarshaller u = jc.createUnmarshaller();
2929                 byte[] s = rs.getBytes("xmlcol");
2930 
2931                 ByteArrayInputStream bss = new ByteArrayInputStream(s);
2932                 XMLInputFactory xf = XMLInputFactory.newInstance();
2933                 XMLStreamReader r = xf.createXMLStreamReader(bss);
2934                 JAXBElement<SetProcessListByMachineRequestMsg> foo = (JAXBElement<SetProcessListByMachineRequestMsg>) u.unmarshal(r, SetProcessListByMachineRequestMsg.class);
2935                 if (foo
2936                         == null || foo.getValue()
2937                         == null) {
2938                     log.log(Level.WARN, "xml is unexpectedly null or empty");
2939                 } else {
2940                     ret = foo.getValue().getMachineInformation().getMemoryinstalled();
2941                 }
2942             }
2943         } catch (Exception ex) {
2944             log.log(Level.ERROR, "error caught loading machine information", ex);
2945         } finally {
2946             DBUtils.safeClose(rs);
2947             DBUtils.safeClose(comm);
2948             DBUtils.safeClose(con);
2949 
2950         }
2951         return ret;
2952     }
2953 
2954     private List<String> getProcessListByHostname(String hostname, String domainName) {
2955         List<String> r = new ArrayList<String>();
2956 
2957         Connection con = Utility.getConfigurationDBConnection();
2958         PreparedStatement com = null;
2959         ResultSet rs = null;
2960         try {
2961             com = con.prepareStatement("select uri from servicepolicies where hostname=? and domaincol=? and policytype=?;");
2962             com.setString(1, hostname);
2963             com.setString(2, domainName);
2964             com.setInt(3, PolicyType.PROCESS.ordinal());
2965             rs = com.executeQuery();
2966             while (rs.next()) {
2967                 r.add(rs.getString(1));
2968             }
2969 
2970         } catch (Exception ex) {
2971             log.log(Level.ERROR, null, ex);
2972         } finally {
2973             DBUtils.safeClose(rs);
2974             DBUtils.safeClose(com);
2975             DBUtils.safeClose(con);
2976         }
2977         return r;
2978 
2979     }
2980 
2981     private ProcessPerformanceData getCurrentProcessPerformanceDataList(String processURI) throws DatatypeConfigurationException {
2982         Connection con = Utility.getPerformanceDBConnection();
2983         PreparedStatement com = null;
2984         ResultSet rs = null;
2985         ProcessPerformanceData p = new ProcessPerformanceData();
2986 
2987         try {
2988             com = con.prepareStatement("select * from rawdatamachineprocess where uri=? order by utcdatetime desc limit 1;");
2989             com.setString(1, processURI);
2990             rs = com.executeQuery();
2991             if (rs.next()) {
2992 
2993                 p.setUri(processURI);
2994                 p.setBytesusedMemory(rs.getLong("memoryused"));
2995                 p.setId(rs.getString("id"));
2996                 //p.setKilobytespersecondDisk(rs.getLong("diskKBs"));
2997                 p.setPercentusedCPU(rs.getDouble("percentCPU"));
2998                 p.setNumberofActiveThreads(rs.getLong("threads"));
2999                 //p.setKilobytespersecondNetwork(rs.getLong("networkKBs"));
3000                 p.setOpenFileHandles(rs.getLong("openfiles"));
3001                 GregorianCalendar gcal = new GregorianCalendar();
3002                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3003                 p.setTimestamp((gcal));
3004 
3005             }
3006 
3007         } catch (Exception ex) {
3008             log.log(Level.ERROR, null, ex);
3009         } finally {
3010             DBUtils.safeClose(rs);
3011             DBUtils.safeClose(com);
3012             DBUtils.safeClose(con);
3013         }
3014 
3015         try {
3016             StatusHelper sh = getStatus(processURI);
3017             if (sh != null) {
3018                 p.setOperationalstatus(sh.running);
3019                 p.setStatusmessage(sh.msg);
3020             } else {
3021                 p.setStatusmessage("Unknown");
3022                 p.setOperationalstatus(false);
3023             }
3024         } catch (Exception ex) {
3025             p.setStatusmessage("Unknown");
3026             p.setOperationalstatus(false);
3027             log.log(Level.WARN, "trouble getting status info", ex);
3028         }
3029 
3030         return p;
3031     }
3032 
3033     private List<ProcessPerformanceData> GetProcessPerformanceDataList(String processURI, TimeRange range, long offset, long records) throws DatatypeConfigurationException {
3034         List<ProcessPerformanceData> ret = new ArrayList<ProcessPerformanceData>();
3035         Connection con = Utility.getPerformanceDBConnection();
3036 
3037         ProcessPerformanceData p = null;
3038         PreparedStatement com = null;
3039         ResultSet rs = null;
3040         try {
3041             com = con.prepareStatement("select * from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ? order by utcdatetime desc limit ? offset ?;");
3042             com.setString(1, processURI);
3043             com.setLong(2, range.getStart().getTimeInMillis());
3044             com.setLong(3, range.getEnd().getTimeInMillis());
3045             com.setLong(4, records);
3046             com.setLong(5, offset);
3047             rs = com.executeQuery();
3048             while (rs.next()) {
3049                 p = new ProcessPerformanceData();
3050                 p.setUri(processURI);
3051                 p.setBytesusedMemory(rs.getLong("memoryused"));
3052                 p.setId(rs.getString("id"));
3053                 //p.setKilobytespersecondDisk(rs.getLong("diskKBs"));
3054                 p.setPercentusedCPU(rs.getDouble("percentCPU"));
3055                 p.setNumberofActiveThreads(rs.getLong("threads"));
3056                 //p.setKilobytespersecondNetwork(rs.getLong("networkKBs"));
3057                 p.setOpenFileHandles(rs.getLong("openfiles"));
3058                 GregorianCalendar gcal = new GregorianCalendar();
3059                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3060                 p.setTimestamp((gcal));
3061 
3062                 gcal = new GregorianCalendar();
3063                 gcal.setTimeInMillis(rs.getLong("startedat"));
3064                 p.setStartedAt((gcal));
3065                 ret.add(p);
3066             }
3067             rs.close();
3068             com.close();
3069         } catch (Exception ex) {
3070             log.log(Level.ERROR, null, ex);
3071         } finally {
3072             DBUtils.safeClose(rs);
3073             DBUtils.safeClose(com);
3074             DBUtils.safeClose(con);
3075         }
3076         return ret;
3077     }
3078 
3079     private List<NetworkAdapterPerformanceData> GetCurrentNicInfo(MachinePolicy mp) {
3080         List<NetworkAdapterPerformanceData> items = new ArrayList<NetworkAdapterPerformanceData>();
3081 
3082         if (mp == null) {
3083             return items;
3084         }
3085         if (mp.getRecordNetworkUsage().isEmpty()) {
3086             return items;
3087         }
3088         Connection con = Utility.getPerformanceDBConnection();
3089         PreparedStatement com = null;
3090         ResultSet rs = null;
3091         for (int i = 0; i < mp.getRecordNetworkUsage().size(); i++) {
3092             try {
3093                 NetworkAdapterPerformanceData d = new NetworkAdapterPerformanceData();
3094                 d.setAdapterName(mp.getRecordNetworkUsage().get(i));
3095 
3096                 com = con.prepareStatement("select * from rawdatanic where nicid=? and hostname=? and domainname=? order by utcdatetime desc limit 1;");
3097                 com.setString(1, mp.getRecordNetworkUsage().get(i));
3098                 com.setString(2, mp.getMachineName());
3099                 com.setString(3, mp.getDomainName());
3100                 rs = com.executeQuery();
3101                 if (rs.next()) {
3102                     d.setKilobytespersecondNetworkTransmit(rs.getLong("sendKBs"));
3103                     d.setKilobytespersecondNetworkReceive(rs.getLong("receiveKBs"));
3104                 }
3105 
3106                 items.add(d);
3107             } catch (Exception ex) {
3108                 log.log(Level.ERROR, null, ex);
3109             } finally {
3110                 DBUtils.safeClose(rs);
3111                 DBUtils.safeClose(com);
3112 
3113             }
3114         }
3115 
3116         DBUtils.safeClose(con);
3117         return items;
3118 
3119     }
3120 
3121     private GetMachinePerformanceLogsByRangeResponseMsg GetMachinePerfLogsByRange(String uri, TimeRange range, long offset, long records) throws DatatypeConfigurationException {
3122         GetMachinePerformanceLogsByRangeResponseMsg ret = new GetMachinePerformanceLogsByRangeResponseMsg();
3123         Pair TranslateURItoPair = this.translateURItoPair(uri);
3124         // List<ProcessPerformanceData> ret = new ArrayList<ProcessPerformanceData>();
3125         Connection con = Utility.getPerformanceDBConnection();
3126 
3127         MachinePerformanceData p = null;
3128         PreparedStatement com = null;
3129         ResultSet rs = null;
3130         try {
3131             com = con.prepareStatement("select * from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ? order by utcdatetime desc limit ? offset ?;");
3132             com.setString(1, uri);
3133             com.setLong(2, range.getStart().getTimeInMillis());
3134             com.setLong(3, range.getEnd().getTimeInMillis());
3135             com.setLong(4, records);
3136             com.setLong(5, offset);
3137             rs = com.executeQuery();
3138             while (rs.next()) {
3139                 p = new MachinePerformanceData();
3140                 p.setUri(uri);
3141                 p.setBytesusedMemory(rs.getLong("memoryused"));
3142                 p.setId(rs.getString("id"));
3143                 p.setPercentusedCPU(rs.getDouble("percentCPU"));
3144                 p.setNumberofActiveThreads(rs.getLong("threads"));
3145                 StatusHelper h = getStatus(uri);
3146                 p.setStatusmessage(h.msg);
3147 
3148                 GregorianCalendar gcal = new GregorianCalendar();
3149                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3150                 p.setTimestamp((gcal));
3151                 Long l = rs.getLong("startedat");
3152                 if (l != null) {
3153                     gcal = new GregorianCalendar();
3154                     gcal.setTimeInMillis(l);
3155                     p.setStartedAt((gcal));
3156                 }
3157                 p.getDriveInformation().addAll(this.getDriveLogsByRange(TranslateURItoPair.hostname, TranslateURItoPair.domainname, rs.getLong("utcdatetime")));
3158                 p.getNetworkAdapterPerformanceData().addAll(this.getNICLogsByRange(TranslateURItoPair.hostname, TranslateURItoPair.domainname, rs.getLong("utcdatetime")));
3159                 ret.getMachinePerformanceData().add(p);
3160             }
3161 
3162         } catch (Exception ex) {
3163             log.log(Level.ERROR, null, ex);
3164         } finally {
3165             DBUtils.safeClose(rs);
3166             DBUtils.safeClose(com);
3167             DBUtils.safeClose(con);
3168         }
3169         return ret;
3170 
3171     }
3172 
3173     private List<DriveInformation> getDriveLogsByRange(String hostname, String domainname, long timestamp) {
3174         Connection con = Utility.getPerformanceDBConnection();
3175         List<DriveInformation> ret = new ArrayList<DriveInformation>();
3176         DriveInformation p = null;
3177 //get a list of nics recorded during this time range
3178         PreparedStatement com = null;
3179         ResultSet rs = null;
3180         try {
3181             com = con.prepareStatement("select * from rawdatadrives where hostname=? and domainname=? and utcdatetime = ?;");
3182             com.setString(1, hostname);
3183             com.setString(2, domainname);
3184             com.setLong(3, timestamp);
3185             rs = com.executeQuery();
3186             while (rs.next()) {
3187                 p = new DriveInformation();
3188                 p.setFreespace(rs.getLong("freespace"));
3189                 p.setId(rs.getString("id"));
3190                 p.setKilobytespersecondDiskRead(rs.getLong("readKBs"));
3191                 p.setKilobytespersecondDiskWrite(rs.getLong("writeKBs"));
3192                 p.setOperationalstatus(rs.getString("statusmsg"));
3193                 p.setOperational(rs.getBoolean("status"));
3194                 p.setPartition(rs.getString("driveIdentifier"));
3195                 p.setSystemid(rs.getString("deviceIdentifier"));
3196                 GregorianCalendar gcal = new GregorianCalendar();
3197                 gcal.setTimeInMillis(timestamp);
3198                 p.setTimestamp((gcal));
3199                 ret.add(p);
3200             }
3201             rs.close();
3202             com.close();
3203         } catch (Exception ex) {
3204             log.log(Level.ERROR, null, ex);
3205         } finally {
3206             DBUtils.safeClose(rs);
3207             DBUtils.safeClose(com);
3208             DBUtils.safeClose(con);
3209         }
3210 
3211         return ret;
3212     }
3213 
3214     private List<NetworkAdapterPerformanceData> getNICLogsByRange(String hostname, String domainname, long timestamp) {
3215         Connection con = Utility.getPerformanceDBConnection();
3216         List<NetworkAdapterPerformanceData> ret = new ArrayList<NetworkAdapterPerformanceData>();
3217         NetworkAdapterPerformanceData p = null;
3218         PreparedStatement com = null;
3219         ResultSet rs = null;
3220         try {
3221             com = con.prepareStatement("select * from rawdatanic where hostname=? and domainname=? and utcdatetime = ?;");
3222             com.setString(1, hostname);
3223             com.setString(2, domainname);
3224             com.setLong(3, timestamp);
3225             rs = com.executeQuery();
3226             while (rs.next()) {
3227                 p = new NetworkAdapterPerformanceData();
3228                 p.setAdapterName(rs.getString("nicid"));
3229                 p.setKilobytespersecondNetworkReceive(rs.getLong("receiveKBs"));
3230                 p.setKilobytespersecondNetworkTransmit(rs.getLong("sendKBs"));
3231 
3232                 GregorianCalendar gcal = new GregorianCalendar();
3233                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3234 
3235                 ret.add(p);
3236             }
3237 
3238         } catch (Exception ex) {
3239             log.log(Level.ERROR, null, ex);
3240         } finally {
3241             DBUtils.safeClose(rs);
3242             DBUtils.safeClose(com);
3243             DBUtils.safeClose(con);
3244         }
3245         return ret;
3246 
3247     }
3248 
3249     private List<ProcessPerformanceData> getCurrentProcessPerformanceDataList(List<String> processURLlist) {
3250         List<ProcessPerformanceData> data = new ArrayList<ProcessPerformanceData>();
3251         Connection con = Utility.getPerformanceDBConnection();
3252         for (int i = 0; i < processURLlist.size(); i++) {
3253             PreparedStatement com = null;
3254             ResultSet rs = null;
3255             try {
3256                 com = con.prepareStatement("select * from rawdatamachineprocess where uri=? order by utcdatetime desc limit 1;");
3257                 com.setString(1, processURLlist.get(i));
3258                 rs = com.executeQuery();
3259                 if (rs.next()) {
3260                     ProcessPerformanceData p = new ProcessPerformanceData();
3261                     p.setUri(processURLlist.get(i));
3262                     p.setBytesusedMemory(rs.getLong("memoryused"));
3263                     p.setId(rs.getString("id"));
3264                     //p.setKilobytespersecondDisk(rs.getLong("diskKBs"));
3265                     p.setPercentusedCPU(rs.getDouble("percentCPU"));
3266                     p.setNumberofActiveThreads(rs.getLong("threads"));
3267                     p.setOpenFileHandles(rs.getLong("openfiles"));
3268                     //p.setKilobytespersecondNetwork(rs.getLong("networkKBs"));
3269                     StatusHelper h = getStatus(p.getUri());
3270                     if (h != null) {
3271                         p.setOperationalstatus(h.running);
3272                         p.setStatusmessage(h.msg);
3273 
3274                     } else {
3275                         p.setOperationalstatus(false);
3276                         p.setStatusmessage("Unknown");
3277                     }
3278                     GregorianCalendar gcal = new GregorianCalendar();
3279                     gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3280                     p.setTimestamp((gcal));
3281                     Long l = rs.getLong("startedat");
3282                     if (l != null) {
3283                         gcal = new GregorianCalendar();
3284                         gcal.setTimeInMillis(l);
3285                         p.setStartedAt((gcal));
3286                     }
3287                     data.add(p);
3288                 }
3289 
3290             } catch (Exception ex) {
3291                 log.log(Level.ERROR, null, ex);
3292             } finally {
3293                 DBUtils.safeClose(rs);
3294                 DBUtils.safeClose(com);
3295 
3296             }
3297         }
3298         DBUtils.safeClose(con);
3299 
3300         return data;
3301     }
3302 
3303     private List<DriveInformation> getCurrentDriveInformation(String hostname, String domainName) {
3304         Connection con = Utility.getPerformanceDBConnection();
3305         List<DriveInformation> r = new ArrayList<DriveInformation>();
3306         PreparedStatement com = null;
3307         ResultSet rs = null;
3308         try {
3309 
3310             com = con.prepareStatement("select * from rawdatadrives where hostname=? and domainname=? order by utcdatetime desc limit 1;");
3311             com.setString(1, hostname);
3312             com.setString(2, domainName);
3313             rs = com.executeQuery();
3314             while (rs.next()) {
3315                 DriveInformation d = new DriveInformation();
3316                 d.setFreespace(rs.getLong("freespace"));
3317                 d.setPartition(rs.getString("driveIdentifier"));
3318                 d.setKilobytespersecondDiskWrite(rs.getLong("writeKBs"));
3319                 d.setKilobytespersecondDiskRead(rs.getLong("readKBs"));
3320                 d.setOperational(rs.getBoolean("status"));
3321                 d.setOperationalstatus(rs.getString("statusmsg"));
3322                 d.setId(rs.getString("id"));
3323                 GregorianCalendar gcal = new GregorianCalendar();
3324                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3325                 d.setTimestamp((gcal));
3326                 r.add(d);
3327             }
3328             rs.close();
3329             com.close();
3330         } catch (Exception ex) {
3331             log.log(Level.ERROR, null, ex);
3332         } finally {
3333             DBUtils.safeClose(rs);
3334             DBUtils.safeClose(com);
3335             DBUtils.safeClose(con);
3336         }
3337 
3338         return r;
3339     }
3340 
3341     /**
3342      * returns null if not found
3343      *
3344      * @param uri
3345      * @return
3346      * @throws SQLException
3347      */
3348     private StatusHelper getStatus(String uri) throws SQLException {
3349         Connection con = Utility.getConfigurationDBConnection();
3350         PreparedStatement cmd = null;
3351         ResultSet rs = null;
3352         try {
3353             StatusHelper h = new StatusHelper();
3354             cmd = con.prepareStatement("select * from status where uri=?;");
3355             cmd.setString(1, uri);
3356             rs = cmd.executeQuery();
3357             if (rs.next()) {
3358                 h.msg = rs.getString("message");
3359                 h.running = rs.getBoolean("status");
3360                 rs.close();
3361                 cmd.close();
3362                 con.close();
3363                 return h;
3364             }
3365             rs.close();
3366             cmd.close();
3367             con.close();
3368             return null;
3369         } catch (Exception ex) {
3370             log.log(Level.ERROR, null, ex);
3371         } finally {
3372             DBUtils.safeClose(rs);
3373             DBUtils.safeClose(cmd);
3374             DBUtils.safeClose(con);
3375         }
3376         return null;
3377     }
3378 
3379     private MachinePerformanceData getCurrentMachinePerformanceData(MachinePolicy mp) {
3380         MachinePerformanceData ret = new MachinePerformanceData();
3381         Connection con = null;
3382         //get machine info
3383         con = Utility.getPerformanceDBConnection();
3384         PreparedStatement com = null;
3385         ResultSet rs = null;
3386         try {
3387 
3388             com = con.prepareStatement("SELECT uri, memoryused, "
3389                     + "percentcpu, id, utcdatetime, threads, openfiles  FROM rawdatamachineprocess where uri=? order by utcdatetime desc limit 1;");
3390             com.setString(1, mp.getURL());
3391             rs = com.executeQuery();
3392             if (rs.next()) {
3393                 ret.setBytesusedMemory(rs.getLong("memoryused"));
3394                 ret.setId(rs.getString("id"));
3395                 ret.setNumberofActiveThreads(rs.getLong("threads"));
3396                 ret.setPercentusedCPU(rs.getDouble("percentCPU"));
3397                 ret.setUri(rs.getString("uri"));
3398                 GregorianCalendar gcal = new GregorianCalendar();
3399                 gcal.setTimeInMillis(rs.getLong("utcdatetime"));
3400                 ret.setTimestamp((gcal));
3401             }
3402             rs.close();
3403             com.close();
3404         } catch (Exception ex) {
3405             log.log(Level.WARN, null, ex);
3406         } finally {
3407             DBUtils.safeClose(rs);
3408             DBUtils.safeClose(com);
3409             DBUtils.safeClose(con);
3410         }
3411 
3412         ret.getDriveInformation().addAll(this.getCurrentDriveInformation(mp));
3413         ret.getNetworkAdapterPerformanceData().addAll(GetCurrentNicInfo(mp));
3414         try {
3415             StatusHelper sh = getStatus(mp.getURL());
3416             if (sh != null) {
3417                 ret.setOperationalstatus(sh.running);
3418                 ret.setStatusmessage(sh.msg);
3419             } else {
3420                 ret.setStatusmessage("Unknown");
3421                 ret.setOperationalstatus(false);
3422             }
3423         } catch (Exception ex) {
3424             ret.setStatusmessage("Unknown");
3425             log.log(Level.WARN, "trouble getting status info", ex);
3426         }
3427         return ret;
3428     }
3429 
3430     private List<DriveInformation> getCurrentDriveInformation(MachinePolicy mp) {
3431         return this.getCurrentDriveInformation(mp.getMachineName(), mp.getDomainName());
3432     }
3433 
3434     private Pair translateURItoPair(String policyURI) {
3435         Connection con = Utility.getConfigurationDBConnection();
3436         Pair p = null;
3437         PreparedStatement com = null;
3438         ResultSet rs = null;
3439         try {
3440             com = con.prepareStatement("select hostname, domaincol from servicepolicies where uri=?;");
3441             com.setString(1, policyURI);
3442             rs = com.executeQuery();
3443             if (rs.next()) {
3444                 p = new Pair();
3445                 p.hostname = rs.getString("hostname");
3446                 p.domainname = rs.getString("domaincol");
3447             }
3448 
3449         } catch (Exception ex) {
3450             log.log(Level.ERROR, null, ex);
3451         } finally {
3452             DBUtils.safeClose(rs);
3453             DBUtils.safeClose(com);
3454             DBUtils.safeClose(con);
3455         }
3456         return p;
3457     }
3458 
3459     /**
3460      *
3461      * removes a record of a specific service dependency
3462      *
3463      *
3464      * @param deleteServiceDependencyRequest
3465      * @return returns
3466      * org.miloss.fgsms.services.interfaces.dataaccessservice.DeleteServiceDependencyResponseMsg
3467      * @throws AccessDeniedException
3468      * @throws ServiceUnavailableException
3469      */
3470     @WebMethod(operationName = "DeleteServiceDependency", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/DeleteServiceDependency")
3471     @WebResult(name = "DeleteServiceDependencyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
3472     @RequestWrapper(localName = "DeleteServiceDependency", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.DeleteServiceDependency")
3473     @ResponseWrapper(localName = "DeleteServiceDependencyResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.DeleteServiceDependencyResponse")
3474     public DeleteServiceDependencyResponseMsg deleteServiceDependency(
3475             @WebParam(name = "DeleteServiceDependencyRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") DeleteServiceDependencyRequestMsg request)
3476             throws AccessDeniedException, ServiceUnavailableException {
3477         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3478         if (request == null) {
3479             throw new IllegalArgumentException("null message");
3480         }
3481         if (Utility.stringIsNullOrEmpty(request.getUri()) || Utility.stringIsNullOrEmpty(request.getDependenturi())) {
3482             throw new IllegalArgumentException("the uri must be specified");
3483         }
3484 
3485         Utility.validateClassification(request.getClassification());
3486         AuditLogger.logItem(this.getClass().getCanonicalName(), "deleteServiceDependency", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3487         UserIdentityUtil.assertWriteAccess(request.getUri(), currentUser, "deleteServiceDependency", (request.getClassification()), ctx);
3488         Connection con = Utility.getPerformanceDBConnection();
3489         PreparedStatement cmd = null;
3490         try {
3491             cmd = con.prepareStatement("DELETE FROM dependencies WHERE sourceurl=? and sourcesoapaction=? and destinationurl=? and destinationsoapaction=?;");
3492             cmd.setString(1, request.getUri());
3493             if (Utility.stringIsNullOrEmpty(request.getAction())) {
3494                 cmd.setNull(2, Types.VARCHAR);
3495             } else {
3496                 cmd.setString(2, request.getAction());
3497             }
3498             cmd.setString(3, request.getDependenturi());
3499             if (Utility.stringIsNullOrEmpty(request.getDependentaction())) {
3500                 cmd.setNull(4, Types.VARCHAR);
3501             } else {
3502                 cmd.setString(4, request.getDependentaction());
3503             }
3504             cmd.executeUpdate();
3505             cmd.close();
3506             con.close();
3507             DeleteServiceDependencyResponseMsg res = new DeleteServiceDependencyResponseMsg();
3508             res.setClassification(getCurrentClassificationLevel());
3509             return res;
3510         } catch (Exception ex) {
3511             log.log(Level.ERROR, null, ex);
3512 
3513         } finally {
3514             DBUtils.safeClose(cmd);
3515             DBUtils.safeClose(con);
3516         }
3517         ServiceUnavailableException code = new ServiceUnavailableException("", null);
3518         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3519         throw code;
3520     }
3521 
3522     /**
3523      *
3524      * returns the service policy urls that all the service depends on global
3525      * admin rights required
3526      *
3527      * @param getAllServiceDependenciesRequest
3528      * @return returns
3529      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllServiceDependenciesResponseMsg
3530      * @throws AccessDeniedException
3531      * @throws ServiceUnavailableException
3532      */
3533     @WebMethod(operationName = "GetAllServiceDependencies", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetAllServiceDependencies")
3534     @WebResult(name = "GetAllServiceDependenciesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
3535     @RequestWrapper(localName = "GetAllServiceDependencies", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllServiceDependencies")
3536     @ResponseWrapper(localName = "GetAllServiceDependenciesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetAllServiceDependenciesResponse")
3537     public GetAllServiceDependenciesResponseMsg getAllServiceDependencies(
3538             @WebParam(name = "GetAllServiceDependenciesRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetAllServiceDependenciesRequestMsg request)
3539             throws AccessDeniedException, ServiceUnavailableException {
3540         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3541         if (request == null) {
3542             throw new IllegalArgumentException("null message");
3543         }
3544 
3545         Utility.validateClassification(request.getClassification());
3546         UserIdentityUtil.assertGlobalAdministratorRole(currentUser, "getAllServiceDependencies", (request.getClassification()), ctx);
3547         AuditLogger.logItem(this.getClass().getCanonicalName(), "getAllServiceDependencies", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3548         Connection con = Utility.getPerformanceDBConnection();
3549         ResultSet rs = null;
3550         PreparedStatement cmd = null;
3551         try {
3552 
3553             GetAllServiceDependenciesResponseMsg res = new GetAllServiceDependenciesResponseMsg();
3554             res.setClassification(getCurrentClassificationLevel());
3555 
3556             cmd = con.prepareStatement("select * from dependencies");
3557 
3558             rs = cmd.executeQuery();
3559 
3560             while (rs.next()) {
3561                 DependencyWrapper dw = new DependencyWrapper();
3562                 dw.setSourceuri(rs.getString("sourceurl"));
3563                 dw.setSourceaction(rs.getString("sourcesoapaction"));
3564                 dw.setDestinationaction(rs.getString("destinationaction"));
3565                 dw.setDestinationuri(rs.getString("destinationurl"));
3566                 res.getDependencies().add(dw);
3567                 //res.getIdependonAndDependonme().add(of.createGetAllServiceDependenciesResponseMsgIdependon(d));
3568             }
3569 
3570             /*
3571 
3572              cmd = con.prepareStatement("select * from dependencies where destinationurl=?");
3573              cmd.setString(1, list.getValue().getServiceType().get(i).getURL());
3574              rs = cmd.executeQuery();
3575              while (rs.next()) {
3576              Dependencies d = new Dependencies();
3577              d.setAction(rs.getString("sourcesoapaction"));
3578              d.setUrl(rs.getString("sourceurl"));
3579              res.getIdependonAndDependonme().add(of.createGetAllServiceDependenciesResponseMsgDependonme(d));
3580              }
3581              rs.close();
3582              cmd.close();*/
3583             return res;
3584         } catch (Exception ex) {
3585             log.log(Level.ERROR, null, ex);
3586         } finally {
3587             DBUtils.safeClose(rs);
3588             DBUtils.safeClose(cmd);
3589             DBUtils.safeClose(con);
3590         }
3591         ServiceUnavailableException code = new ServiceUnavailableException("", null);
3592         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3593         throw code;
3594 
3595     }
3596 
3597     /**
3598      *
3599      * returns the service policy urls that the given service depends on
3600      *
3601      *
3602      * @param getServiceDependenciesRequest
3603      * @return returns
3604      * org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceDependenciesResponseMsg
3605      * @throws AccessDeniedException
3606      * @throws ServiceUnavailableException
3607      */
3608     @WebMethod(operationName = "GetServiceDependencies", action = "urn:org:miloss:fgsms:services:interfaces:dataAccessService/dataAccessService/GetServiceDependencies")
3609     @WebResult(name = "GetServiceDependenciesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService")
3610     @RequestWrapper(localName = "GetServiceDependencies", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceDependencies")
3611     @ResponseWrapper(localName = "GetServiceDependenciesResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService", className = "org.miloss.fgsms.services.interfaces.dataaccessservice.GetServiceDependenciesResponse")
3612     public GetServiceDependenciesResponseMsg getServiceDependencies(
3613             @WebParam(name = "GetServiceDependenciesRequest", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:dataAccessService") GetServiceDependenciesRequestMsg request)
3614             throws AccessDeniedException, ServiceUnavailableException {
3615         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3616         if (request == null) {
3617             throw new IllegalArgumentException("null message");
3618         }
3619         if (Utility.stringIsNullOrEmpty(request.getUri())) {
3620             throw new IllegalArgumentException("the uri must be specified");
3621         }
3622 
3623         Utility.validateClassification(request.getClassification());
3624         AuditLogger.logItem(this.getClass().getCanonicalName(), "getServiceDependencies", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3625         UserIdentityUtil.assertReadAccess(request.getUri(), currentUser, "getServiceDependencies", (request.getClassification()), ctx);
3626 
3627         Connection con = Utility.getPerformanceDBConnection();
3628         PreparedStatement cmd = null;
3629         ResultSet rs = null;
3630         GetServiceDependenciesResponseMsg res = new GetServiceDependenciesResponseMsg();
3631         try {
3632 
3633             res.setClassification(getCurrentClassificationLevel());
3634 
3635             cmd = con.prepareStatement("select * from dependencies where sourceurl=?");
3636             cmd.setString(1, request.getUri());
3637             rs = cmd.executeQuery();
3638             while (rs.next()) {
3639                 Dependencies d = new Dependencies();
3640                 d.setAction(rs.getString("destinationsoapaction"));
3641                 d.setUrl(rs.getString("destinationurl"));
3642                 res.getIdependon().add(d);
3643             }
3644         } catch (Exception ex) {
3645             log.log(Level.ERROR, null, ex);
3646         } finally {
3647             DBUtils.safeClose(rs);
3648             DBUtils.safeClose(cmd);
3649         }
3650 
3651         try {
3652             cmd = con.prepareStatement("select * from dependencies where destinationurl=?");
3653             cmd.setString(1, request.getUri());
3654             rs = cmd.executeQuery();
3655             while (rs.next()) {
3656                 Dependencies d = new Dependencies();
3657                 d.setAction(rs.getString("sourcesoapaction"));
3658                 d.setUrl(rs.getString("sourceurl"));
3659                 res.getDependonme().add(d);
3660             }
3661             return res;
3662 
3663         } catch (Exception ex) {
3664             log.log(Level.ERROR, null, ex);
3665 
3666         } finally {
3667             DBUtils.safeClose(rs);
3668             DBUtils.safeClose(cmd);
3669             DBUtils.safeClose(con);
3670         }
3671         ServiceUnavailableException code = new ServiceUnavailableException("", null);
3672 
3673         code.getFaultInfo()
3674                 .setCode(ServiceUnavailableFaultCodes.UNEXPECTED_ERROR);
3675         throw code;
3676 
3677     }
3678 
3679     /**
3680      * Get the operating status of this service
3681      *
3682      * @param request
3683      * @return returns
3684      * org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponseMessage
3685      */
3686     @WebMethod(operationName = "GetOperatingStatus", action = "urn:org:miloss:fgsms:services:interfaces:opStatusService/GetOperatingStatus")
3687     @WebResult(name = "response", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common")
3688     @RequestWrapper(localName = "GetOperatingStatus", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common", className = "org.miloss.fgsms.services.interfaces.common.GetOperatingStatus")
3689     @ResponseWrapper(localName = "GetOperatingStatusResponse", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common", className = "org.miloss.fgsms.services.interfaces.common.GetOperatingStatusResponse")
3690     public GetOperatingStatusResponseMessage getOperatingStatus(
3691             @WebParam(name = "request", targetNamespace = "urn:org:miloss:fgsms:services:interfaces:common") GetOperatingStatusRequestMessage request) {
3692         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
3693 
3694         Utility.validateClassification(request.getClassification());
3695         AuditLogger.logItem(this.getClass().getCanonicalName(), "getOperatingStatus", currentUser, "", (request.getClassification()), ctx.getMessageContext());
3696 
3697         GetOperatingStatusResponseMessage res = new GetOperatingStatusResponseMessage();
3698 
3699         res.setClassification(request.getClassification());
3700         res.setVersionInfo(new GetOperatingStatusResponseMessage.VersionInfo());
3701         res.getVersionInfo().setVersionData(org.miloss.fgsms.common.Constants.Version);
3702         res
3703                 .getVersionInfo().setVersionSource(org.miloss.fgsms.common.Constants.class
3704                         .getCanonicalName());
3705         res.setStartedAt(started);
3706         boolean ok = true;
3707         Connection con = Utility.getConfigurationDBConnection();
3708         Connection con2 = Utility.getPerformanceDBConnection();
3709         PreparedStatement prepareStatement = null;
3710         PreparedStatement prepareStatement2 = null;
3711         try {
3712             prepareStatement = con.prepareStatement("select 1=1;");
3713             prepareStatement.execute();
3714 
3715             prepareStatement2 = con2.prepareStatement("select 1=1;");
3716             prepareStatement2.execute();
3717             res.setStatusMessage("OK");
3718         } catch (Exception ex) {
3719             ok = false;
3720             res.setStatusMessage("One or more of the database connections is available");
3721         } finally {
3722             DBUtils.safeClose(prepareStatement);
3723             DBUtils.safeClose(prepareStatement2);
3724             DBUtils.safeClose(con);
3725             DBUtils.safeClose(con2);
3726         }
3727 
3728         res.setStatus(ok);
3729         return res;
3730     }
3731 }