View Javadoc
1   /*
2    * To change this license header, choose License Headers in Project Properties.
3    * To change this template file, choose Tools | Templates
4    * and open the template in the editor.
5    */
6   package org.miloss.fgsms.services.das.impl;
7   
8   import java.sql.Connection;
9   import java.sql.PreparedStatement;
10  import java.sql.ResultSet;
11  import java.sql.SQLException;
12  import java.util.List;
13  import javax.xml.bind.JAXBElement;
14  import javax.xml.datatype.Duration;
15  import javax.xml.namespace.QName;
16  import javax.xml.ws.WebServiceContext;
17  import org.apache.log4j.Level;
18  import org.miloss.fgsms.common.AuditLogger;
19  import org.miloss.fgsms.common.Constants;
20  import org.miloss.fgsms.common.DBUtils;
21  import org.miloss.fgsms.common.UserIdentityUtil;
22  import org.miloss.fgsms.common.Utility;
23  import static org.miloss.fgsms.services.das.impl.DAS4jBean.log;
24  import org.miloss.fgsms.services.interfaces.common.PolicyType;
25  import org.miloss.fgsms.services.interfaces.common.SecurityWrapper;
26  import org.miloss.fgsms.services.interfaces.dataaccessservice.ArrayOfServiceType;
27  import org.miloss.fgsms.services.interfaces.dataaccessservice.GetPerformanceAverageStatsResponseMsg;
28  import org.miloss.fgsms.services.interfaces.dataaccessservice.ServiceType;
29  import org.miloss.fgsms.services.interfaces.dataaccessservice.ServiceUnavailableException;
30  import org.miloss.fgsms.services.interfaces.faults.ServiceUnavailableFaultCodes;
31  
32  /**
33   *
34   * @author AO
35   */
36  public class DASHelper {
37  
38      protected static GetPerformanceAverageStatsResponseMsg getPerformanceAvgStatsFromDB(WebServiceContext ctx, String uri, String displayname, SecurityWrapper classification) {
39          Utility.validateClassification(classification);
40          /*
41               * 12-10-2011 if (timeRange == null) { throw new
42               * IllegalArgumentException("time range is null"); }
43           */
44          if (Utility.stringIsNullOrEmpty(uri)) {
45              throw new IllegalArgumentException("uri is null");
46          }
47          String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
48          AuditLogger.logItem(DAS4jBean.class.getCanonicalName(), "GetPerformanceAvgStatsFromDB", currentUser, uri, classification, ctx.getMessageContext());
49          GetPerformanceAverageStatsResponseMsg res = new GetPerformanceAverageStatsResponseMsg();
50          res.setClassification(classification);
51          res.setAverageResponseTime(-1);
52          res.setFailingInvocations(-1);
53          res.setSuccessfulInvocations(-1);
54          res.setURL(uri);
55  
56          Connection con = Utility.getPerformanceDBConnection();
57          PreparedStatement comm = null;
58          ResultSet r = null;
59          try {
60  
61              /////////////////////////////////////////////
62              //query
63              /////////////////////////////////////////////
64              //revised 6-13-2012 to pull from quick stats agg2 table for adjustable
65              //5, 15, 60 and 24 are mandatory
66              //revised dec-10-2011 to pull from quickstats "agg" table
67              boolean ok = false;
68              comm = con.prepareStatement(" select avgres, success, failure, sla, mtbf from agg2 where URI=?  and soapaction=? and timerange=?;");
69              //12-10-2011 PreparedStatement comm = con.prepareStatement(" select success, responsetimems,slafault from RawData where URI=? and Success=true and (UTCdatetime > ?) and (UTCdatetime < ?);");
70              comm.setString(1, uri);
71              comm.setString(2, "All-Methods");
72              comm.setLong(3, 86400000);
73              //12-10-2011 comm.setLong(2, timeRange.getStart().getTimeInMillis());
74              //12-10-2011 comm.setLong(3, timeRange.getEnd().getTimeInMillis());
75  
76              r = comm.executeQuery();
77              if (r.next()) {
78                  res.setAverageResponseTime(r.getLong("avgres"));
79                  res.setFailingInvocations(r.getLong("failure"));
80  
81                  res.setMTBF(DAS4jBean.df.newDuration(r.getLong("mtbf")));
82                  res.setServiceLevelAgreementViolations(r.getLong("sla"));
83                  res.setSuccessfulInvocations(r.getLong("success"));
84                  ok = true;
85              }
86  
87              if (!ok) {
88                  log.log(Level.WARN, "statistics not found for service " + uri);
89                  return null;
90              }
91              if (!Utility.stringIsNullOrEmpty(displayname)) {
92                  res.setDisplayName(displayname);
93              }
94              return res;
95          } catch (Exception ex) {
96              log.log(Level.ERROR, "Error getting average stats from database", ex);
97          } finally {
98              DBUtils.safeClose(r);
99              DBUtils.safeClose(comm);
100             DBUtils.safeClose(con);
101         }
102         return null;
103     }
104 
105     /**
106      * this function filters results by the current request context username
107      *
108      * @param classification
109      * @return
110      * @throws ServiceUnavailableException
111      */
112     protected static ArrayOfServiceType getServiceListfromPolicyDB(WebServiceContext ctx, SecurityWrapper classification) throws ServiceUnavailableException {
113         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
114         AuditLogger.logItem(DAS4jBean.class.getCanonicalName(), "GetServiceListfromPolicyDB", currentUser, "", classification, ctx.getMessageContext());
115         //here user access is controlled by the database stored proceedure which filters
116         //access by user permissions
117         ArrayOfServiceType list = new ArrayOfServiceType();
118         ServiceType temp = null;
119         Connection con = Utility.getConfigurationDBConnection();
120         PreparedStatement comm = null;
121         ResultSet results = null;
122         try {
123 
124             if (UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "GetServiceListfromPolicyDB", (classification), ctx)) {
125                 comm = con.prepareStatement("select URI,  displayname, policytype, hostname, domaincol, parenturi from servicepolicies order by uri asc;");
126             } else {
127                 //changed RC5
128                 comm = con.prepareStatement("select ObjectURI as URI, displayname, policytype,hostname, domaincol, parenturi from UserPermissions, servicepolicies where servicepolicies.uri=objecturi and username=? and (ReadObject=true or WriteObject=true or AdministerObject=true or AuditObject=true)  order by URI asc;");
129                 comm.setString(1, currentUser);
130 
131             }
132             results = comm.executeQuery();
133             int count = 0;
134             /////////////////////////////////////////////
135             //query
136             /////////////////////////////////////////////
137             while (results.next()) {
138                 temp = new ServiceType();
139                 temp.setURL(results.getString("URI"));
140                 temp.setDisplayName(results.getString("displayname"));
141                 temp.setPolicyType(PolicyType.values()[results.getInt("policytype")]);
142                 temp.setDomainname(results.getString("domaincol"));
143                 temp.setHostname(results.getString("hostname"));
144                 temp.setParentobject(results.getString("parenturi"));
145 
146                 list.getServiceType().add(temp);
147                 count++;
148             }
149             log.log(Level.INFO, "GetServiceListfromPolicyDB records returned " + count + " for " + currentUser);
150 
151         } catch (Exception ex) {
152             log.log(Level.ERROR, null, ex);
153             ServiceUnavailableException code = new ServiceUnavailableException("", null);
154             code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
155             throw code;
156         } finally {
157             DBUtils.safeClose(results);
158             DBUtils.safeClose(comm);
159             DBUtils.safeClose(con);
160         }
161         return list;
162         // return null;
163     }
164 
165     /**
166      * Returns a list of services, filtered by the current user and policy type
167      *
168      * @param classification
169      * @param p
170      * @return
171      * @throws ServiceUnavailableException
172      */
173     protected static ArrayOfServiceType getServiceListfromPolicyDB(WebServiceContext ctx, SecurityWrapper classification, PolicyType p) throws ServiceUnavailableException {
174         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
175         AuditLogger.logItem(DAS4jBean.class.getCanonicalName(), "GetServiceListfromPolicyDB", currentUser, "", classification, ctx.getMessageContext());
176 
177         Connection con = Utility.getConfigurationDBConnection();
178         PreparedStatement comm = null;
179         ResultSet results = null;
180         try {
181             //here user access is controlled by the database stored proceedure which filters
182             //access by user permissions
183             ArrayOfServiceType list = new ArrayOfServiceType();
184             ServiceType temp = null;
185 
186             if (UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "GetServiceListfromPolicyDB", (classification), ctx)) {
187                 comm = con.prepareStatement("select URI,  displayname, policytype, hostname, domaincol, parenturi from servicepolicies where policytype = ? order by uri asc;");
188                 comm.setInt(1, p.ordinal());
189 
190             } else {
191                 //changed RC5
192                 comm = con.prepareStatement("select ObjectURI as URI, displayname, policytype, hostname, domaincol, parenturi from UserPermissions, servicepolicies where servicepolicies.uri=objecturi and username=? and (ReadObject=true or WriteObject=true or AdministerObject=true or AuditObject=true)  and policytype = ? order by URI asc;");
193                 comm.setString(1, currentUser);
194                 comm.setInt(2, p.ordinal());
195 
196             }
197             results = comm.executeQuery();
198             int count = 0;
199             /////////////////////////////////////////////
200             //query
201             /////////////////////////////////////////////
202             while (results.next()) {
203                 temp = new ServiceType();
204                 temp.setURL(results.getString("URI"));
205                 temp.setDisplayName(results.getString("displayname"));
206                 temp.setPolicyType(PolicyType.values()[results.getInt("policytype")]);
207                 temp.setDomainname(results.getString("domaincol"));
208                 temp.setHostname(results.getString("hostname"));
209                 temp.setParentobject(results.getString("parenturi"));
210                 list.getServiceType().add(temp);
211                 count++;
212             }
213             log.log(Level.INFO, "GetServiceListfromPolicyDB records by policy type returned " + count + " for " + currentUser);
214             DBUtils.safeClose(results);
215             DBUtils.safeClose(comm);
216             DBUtils.safeClose(con);
217             if (list.getServiceType().isEmpty()) {
218                 return null;
219             }
220             return list;
221         } catch (Exception ex) {
222             log.log(Level.ERROR, null, ex);
223 
224         } finally {
225             DBUtils.safeClose(results);
226             DBUtils.safeClose(comm);
227             DBUtils.safeClose(con);
228         }
229         ServiceUnavailableException code = new ServiceUnavailableException("", null);
230         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
231         throw code;
232         // return null;
233     }
234 
235     /**
236      * loads all actions for a given service from the actionlist in perf db
237      * All-Actions is NOT explicitly added
238      *
239      * @param actions - out
240      * @param uRL
241      */
242     protected static void addServiceActionsFromDB(List<String> actions, String uRL) {
243         if (Utility.stringIsNullOrEmpty(uRL)) {
244             throw new IllegalArgumentException("URL is null");
245         }
246         Connection con = Utility.getPerformanceDBConnection();
247         ResultSet results = null;
248         PreparedStatement comm = null;
249         try {
250 
251             //dec 10 2011  PreparedStatement comm = con.prepareStatement("Select action from RawData where URI=? group by action;");
252             comm = con.prepareStatement("Select soapaction from actionlist where URI=?;");
253             comm.setString(1, uRL);
254             results = comm.executeQuery();
255             /////////////////////////////////////////////
256             //query
257             /////////////////////////////////////////////
258             while (results.next()) {
259                 actions.add(results.getString("soapaction"));
260             }
261         } catch (Exception ex) {
262             log.log(Level.ERROR, "error getting action list for service " + uRL, ex);
263         } finally {
264             DBUtils.safeClose(results);
265             DBUtils.safeClose(comm);
266             DBUtils.safeClose(con);
267         }
268     }
269 
270     /**
271      * Returns a list of services, filtered by the current user and policy type
272      * and hostname
273      *
274      * @param classification
275      * @param p
276      * @return
277      * @throws ServiceUnavailableException
278      */
279     protected static ArrayOfServiceType getServiceListfromPolicyDB(WebServiceContext ctx, SecurityWrapper classification, PolicyType p, String hostname) throws ServiceUnavailableException {
280         Connection con = Utility.getConfigurationDBConnection();
281         PreparedStatement comm = null;
282         ResultSet results = null;
283         try {
284             String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
285             AuditLogger.logItem(DAS4jBean.class.getCanonicalName(), "GetServiceListfromPolicyDB", currentUser, "", classification, ctx.getMessageContext());
286             //here user access is controlled by the database stored proceedure which filters
287             //access by user permissions
288             ArrayOfServiceType list = new ArrayOfServiceType();
289             ServiceType temp = null;
290 
291             if (UserIdentityUtil.hasGlobalAdministratorRole(currentUser, "GetServiceListfromPolicyDB", (classification), ctx)) {
292                 comm = con.prepareStatement("select URI,  displayname, policytype from servicepolicies where policytype = ? and hostname=? order by uri asc;");
293                 comm.setInt(1, p.ordinal());
294                 comm.setString(2, hostname);
295 
296             } else {
297                 //changed RC5
298                 comm = con.prepareStatement("select ObjectURI as URI, displayname, policytype from UserPermissions, servicepolicies where servicepolicies.uri=objecturi and username=? and (ReadObject=true or WriteObject=true or AdministerObject=true or AuditObject=true)  and policytype = ? and hostname=? order by URI asc;");
299                 comm.setString(1, currentUser);
300                 comm.setInt(2, p.ordinal());
301                 comm.setString(3, hostname);
302             }
303             results = comm.executeQuery();
304             int count = 0;
305             /////////////////////////////////////////////
306             //query
307             /////////////////////////////////////////////
308             while (results.next()) {
309                 temp = new ServiceType();
310                 temp.setURL(results.getString("URI"));
311                 temp.setDisplayName(results.getString("displayname"));
312                 temp.setPolicyType(PolicyType.values()[results.getInt("policytype")]);
313                 list.getServiceType().add(temp);
314                 count++;
315             }
316             log.log(Level.INFO, "GetServiceListfromPolicyDB records by hostname and policy returned " + count + " for " + currentUser);
317             DBUtils.safeClose(results);
318             DBUtils.safeClose(comm);
319             DBUtils.safeClose(con);
320             if (list.getServiceType().isEmpty()) {
321 
322                 return null;
323             }
324 
325             return list;
326         } catch (SQLException ex) {
327             log.log(Level.ERROR, null, ex);
328 
329         } finally {
330             DBUtils.safeClose(results);
331             DBUtils.safeClose(comm);
332             DBUtils.safeClose(con);
333         }
334         ServiceUnavailableException code = new ServiceUnavailableException("", null);
335         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
336         throw code;
337 
338     }
339 
340     /**
341      * Returns a list of services, filtered by the current user
342      *
343      * @param uRL
344      * @param classification
345      * @return
346      * @throws ServiceUnavailableException
347      */
348     protected static ArrayOfServiceType getServiceListfromPolicyDB(WebServiceContext ctx, String uRL, SecurityWrapper classification) throws ServiceUnavailableException {
349         String currentUser = UserIdentityUtil.getFirstIdentityToString(ctx);
350         AuditLogger.logItem(DAS4jBean.class.getCanonicalName(), "GetServiceListfromPolicyDB", currentUser, "", classification, ctx.getMessageContext());
351 
352         UserIdentityUtil.assertReadAccess(uRL, currentUser, "GetServiceListfromPolicyDB", classification, ctx);
353         Connection con = Utility.getConfigurationDBConnection();
354         PreparedStatement comm = null;
355         ResultSet results = null;
356         try {
357 
358             ArrayOfServiceType list = new ArrayOfServiceType();
359             ServiceType temp = null;
360 
361             comm = con.prepareStatement("Select URI from ServicePolicies where URI=?");
362             comm.setString(1, uRL);
363 
364             results = comm.executeQuery();
365             /////////////////////////////////////////////
366             //query
367             /////////////////////////////////////////////
368             while (results.next()) {
369                 temp = new ServiceType();
370                 temp.setURL(results.getString("URI"));
371                 DASHelper.addServiceActionsFromDB(temp.getActions(), uRL);
372                 //  log.log(Level.ERROR, "Hello world!" + temp.getActions().size());
373                 //temp.setActions(GetServiceActionListfromDB(uRL.getValue()));
374                 list.getServiceType().add(temp);
375             }
376             DBUtils.safeClose(results);
377             DBUtils.safeClose(comm);
378             DBUtils.safeClose(con);
379             return list;
380         } catch (Exception ex) {
381             log.log(Level.ERROR, null, ex);
382 
383         } finally {
384             DBUtils.safeClose(results);
385             DBUtils.safeClose(comm);
386             DBUtils.safeClose(con);
387         }
388         ServiceUnavailableException code = new ServiceUnavailableException("", null);
389         code.getFaultInfo().setCode(ServiceUnavailableFaultCodes.DATA_BASE_UNAVAILABLE);
390         throw code;
391         // return null;
392     }
393 
394     protected static String getSLAFaultMsg(Connection con, String slaID) {
395         if (con == null) {
396             //log it
397             return null;
398         }
399         PreparedStatement com = null;
400         ResultSet rs = null;
401         try {
402             com = con.prepareStatement("select msg from slaviolations where incidentid=?;");
403             com.setString(1, slaID);
404             rs = com.executeQuery();
405             if (rs.next()) {
406                 byte[] msg = rs.getBytes("msg");
407                 rs.close();
408                 com.close();
409                 //can't close it here con.close();
410                 return new String(msg, Constants.CHARSET);
411             }
412 
413             return "";
414         } catch (Exception ex) {
415             log.log(Level.ERROR, "unable to get sla fault text from perf db.", ex);
416         } finally {
417             DBUtils.safeClose(rs);
418             DBUtils.safeClose(com);
419         }
420         return null;
421     }
422 
423     protected static Duration getUpTime(String uri) {
424         Connection con = Utility.getPerformanceDBConnection();
425         PreparedStatement com = null;
426         ResultSet rs = null;
427         try {
428 
429             com = con.prepareStatement("select * from availability where uri=? order by utcdatetime desc limit 1");
430             com.setString(1, uri);
431             Duration d = null;
432             rs = com.executeQuery();
433             if (rs.next()) {
434                 long changeat = rs.getLong("utcdatetime");
435                 long now = System.currentTimeMillis();
436 
437                 d = DAS4jBean.df.newDuration(now - changeat);
438             }
439             DBUtils.safeClose(rs);
440             DBUtils.safeClose(com);
441             DBUtils.safeClose(con);
442             return d;
443         } catch (Exception ex) {
444             log.log(Level.ERROR, "unable to get uptime for uri " + uri, ex);
445         } finally {
446             DBUtils.safeClose(rs);
447             DBUtils.safeClose(com);
448             DBUtils.safeClose(con);
449         }
450         return null;
451     }
452 
453 }