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.sdks;
21  
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.util.*;
25  import java.util.Map.Entry;
26  import java.util.Properties;
27  import javax.xml.bind.JAXBContext;
28  import javax.xml.bind.JAXBException;
29  import javax.xml.bind.Marshaller;
30  import javax.xml.datatype.DatatypeFactory;
31  import org.miloss.fgsms.common.Constants.AuthMode;
32  import org.miloss.fgsms.common.Utility;
33  import org.miloss.fgsms.services.interfaces.common.PolicyType;
34  import org.miloss.fgsms.services.interfaces.dataaccessservice.*;
35  import org.miloss.fgsms.services.interfaces.policyconfiguration.*;
36  import org.miloss.fgsms.services.interfaces.status.GetStatusResponseMsg;
37  import us.gov.ic.ism.v2.ClassificationType;
38  
39  /**
40   * This is a very basic console application that provides access to basic
41   * functionality of fgsms services. Note: it does not currently support PKI/CAC
42   * authentication
43   *
44   * @author AO
45   */
46  public class ConsoleAdapter {
47  
48      public static void main(String[] args) throws Exception {
49          new ConsoleAdapter().start();
50      }
51      FgsmsSDK sdk;
52      List<ServiceType> GetListOfMonitoredServices;
53      Map<String, Object> context;
54  
55      /**
56       * processes a command from the console and routes the control to the
57       * appropriate action
58       *
59       * @param command
60       * @return
61       * @throws Exception
62       */
63      private boolean process(String command) throws Exception {
64          if (command.toLowerCase().startsWith("help")) {
65              printCommands();
66          } else if (command.toLowerCase().startsWith("list services")) {
67              printServiceList();
68          } else if (command.toLowerCase().startsWith("ls")) {
69              printServiceList();
70          } else if (command.toLowerCase().startsWith("list brokers")) {
71              printServiceList(PolicyType.STATISTICAL);
72          } else if (command.toLowerCase().startsWith("list machine")) {
73              printServiceList(PolicyType.MACHINE);
74          } else if (command.toLowerCase().startsWith("list process")) {
75              printServiceList(PolicyType.PROCESS);
76          } else if (command.toLowerCase().startsWith("list status")) {
77              printServiceList(PolicyType.STATUS);
78          } else if (command.toLowerCase().startsWith("list ws")) {
79              printServiceList(PolicyType.TRANSACTIONAL);
80          } else if (command.toLowerCase().startsWith("refresh")) {
81              getServiceList();
82          } else if (command.toLowerCase().startsWith("agg")) {
83              getAggregatedStats(command);
84          } else if (command.toLowerCase().startsWith("status-all")) {
85              getStatusAll();
86          } else if (command.toLowerCase().startsWith("status")) {
87              getStatus();
88          } else if (command.toLowerCase().startsWith("perf-broker")) {
89              getBrokerPerf();
90          } else if (command.toLowerCase().startsWith("perf-proc")) {
91              getProcessPerf();
92          } else if (command.toLowerCase().startsWith("perf-machine")) {
93              getMachinePerf();
94          } else if (command.toLowerCase().startsWith("perf-wslogs-faulting")) {
95              getWSLogsFault();
96          } else if (command.toLowerCase().startsWith("perf-wslogs-detail")) {
97              GetWSLogsDetails();
98          } else if (command.toLowerCase().startsWith("perf-wslogs-sla")) {
99              getWSLogsSLA();
100         } else if (command.toLowerCase().startsWith("perf-wslogs")) {
101             getWSLogs();
102         } else if (command.toLowerCase().startsWith("gen-settings-get")) {
103             GetGenSettings();
104         } else if (command.toLowerCase().startsWith("gen-settings-add")) {
105             addGenSetting();
106         } else if (command.toLowerCase().startsWith("gen-settings-remove")) {
107             removeGenSetting();
108         } else if (command.toLowerCase().startsWith("email-settings-get")) {
109             getEmail();
110         } else if (command.toLowerCase().startsWith("policy-get-basic")) {
111             printPolicy(getPolicy());
112 
113         } else if (command.toLowerCase().startsWith("machine-net-bulk")) {
114             getServiceList();
115             machineNetBulk(command);
116         } else if (command.toLowerCase().startsWith("machine-net-loop")) {
117             while (true) {
118                 getServiceList();
119                 machineNetBulk(command);
120                 Thread.sleep(1000);
121             }
122         } //
123         else if (command.toLowerCase().startsWith("report-drone-nic")) {
124             reportsDroneNic(command);
125         } else if (command.toLowerCase().startsWith("export-drone-nic")) {
126             exportsDroneNic(command);
127         } else if (command.toLowerCase().startsWith("machine-del-bulk")) {
128             machineDelBulk(command);
129         } else if (command.toLowerCase().startsWith("machine-info")) {
130             printMachineInformation();
131         } else if (command.toLowerCase().startsWith("machine-add")) {
132             addAProcessToMonitor();
133         } else if (command.toLowerCase().startsWith("policy-get-xml")) {
134             getPolicyXml(getPolicy());
135         } else if (command.toLowerCase().startsWith("policy-del")) {
136             removePolicy();
137         } else if (command.toLowerCase().startsWith("dump")) {
138             dumpProperties();
139         } else if (command.toLowerCase().startsWith("exit") || command.toLowerCase().startsWith("quit")) {
140             System.exit(0);
141         } else {
142             return false;
143         }
144         return true;
145     }
146 
147     private void printCommands() {
148         System.out.println("---------[Listing]----------");
149         System.out.println("list services\t\tRetrieves a list of ALL services that you have access to");
150         System.out.println("list brokers\t\tRetrieves a list of services that you have access to");
151         System.out.println("list machine\t\tRetrieves a list of services that you have access to");
152         System.out.println("list process\t\tRetrieves a list of services that you have access to");
153         System.out.println("list ws\t\t\tRetrieves a list of services that you have access to");
154         System.out.println("list status\t\tRetrieves a list of services that you have access to");
155         System.out.println("---------[Performance]----------");
156         System.out.println("agg\t\t\tRetrieves a list of aggregated web service data");
157         // System.out.println("perf-wslogs-search\t\tSearch for transactions by URL and timestamp");
158         System.out.println("perf-wslogs-detail\tGet the payloads and headers for a transaction");
159         System.out.println("perf-broker\t\tCurrent Broker data");
160         System.out.println("perf-proc\t\tCurrent Process data");
161         System.out.println("perf-machine\t\tCurrent Process data");
162         System.out.println("perf-wslogs\t\tGets recent transaction logs for a web service");
163         System.out.println("perf-wslogs-faulting\tGets recent failing transaction logs for a web service");
164         System.out.println("perf-wslogs-sla\t\tGets recent SLA fault transaction logs for a web service");
165         System.out.println("---------[Status]----------");
166         System.out.println("status-all\t\tRetrieves the status of all avaiable services");
167         System.out.println("status\t\t\tRetrieves the status of a specific");
168         System.out.println("---------[Configuration]----------");
169         System.out.println("dump\t\t\tDumps the configuration of this application to console");
170         System.out.println("machine-info\t\tRetrieves all availalble configuration info on a machine (OS Agent)");
171         System.out.println("machine-net-bulk\tMonitors network ETH0 on a group of machines (OS Agent)");
172         System.out.println("machine-net-loop\tMonitors network ETH0 on a group of machines (OS Agent) looping");
173         System.out.println("machine-del-bulk\tDeletes a group of machines (OS Agent)");
174         System.out.println("machine-add\t\tMonitor another process on a machine");
175         System.out.println("gen-settings-get\tRetrieves all general settings from fgsms");
176         System.out.println("gen-setting-add\t\tAdds a general settings from fgsms");
177         System.out.println("gen-setting-remove\tRemoves a general settings from fgsms");
178         System.out.println("email-settings-get\tRetrieves all email settings from fgsms");
179         System.out.println("policy-get-basic\tRetrieves a service policy from fgsms");
180         System.out.println("policy-get-xml\t\tRetrieves a service policy writes the raw xml to screen");
181         System.out.println("policy-delete\t\tRemoves a service policy from fgsms and deletes all data");
182         System.out.println("refresh\t\t\tRetrieves a new copy of the list of monitored services");
183         System.out.println("---------[Reporting]----------");
184         System.out.println("export-drone-nic\t(prefix) (startTime) (endTime) (nic) returns reports for the given time period");
185         System.out.println("report-drone-nic\t(prefix) (startTime) (endTime) (nic) returns reports for the given time period");
186         System.out.println("exit\t\t\tExits the program");
187 
188     }
189 
190     private void printServiceList() {
191         for (int i = 0; i < GetListOfMonitoredServices.size(); i++) {
192             System.out.println("=======================================");
193             System.out.println("URL: " + GetListOfMonitoredServices.get(i).getURL());
194             System.out.println("Display Name: " + GetListOfMonitoredServices.get(i).getDisplayName());
195             System.out.println("Type: " + GetListOfMonitoredServices.get(i).getPolicyType().value());
196             System.out.println("Domain: " + GetListOfMonitoredServices.get(i).getDomainname());
197             System.out.println("Hostname: " + GetListOfMonitoredServices.get(i).getHostname());
198             System.out.println("Pavrent: " + GetListOfMonitoredServices.get(i).getParentobject());
199 
200         }
201     }
202 
203     private void printServiceList(PolicyType t) {
204         for (int i = 0; i < GetListOfMonitoredServices.size(); i++) {
205             if (GetListOfMonitoredServices.get(i).getPolicyType().equals(t)) {
206                 System.out.println("=======================================");
207                 System.out.println("URL: " + GetListOfMonitoredServices.get(i).getURL());
208                 System.out.println("Display Name: " + GetListOfMonitoredServices.get(i).getDisplayName());
209                 System.out.println("Type: " + GetListOfMonitoredServices.get(i).getPolicyType().value());
210                 System.out.println("Domain: " + GetListOfMonitoredServices.get(i).getDomainname());
211                 System.out.println("Hostname: " + GetListOfMonitoredServices.get(i).getHostname());
212                 System.out.println("Parent: " + GetListOfMonitoredServices.get(i).getParentobject());
213             }
214         }
215     }
216 
217     private int getServiceFromSelection(PolicyType t) {
218         int count = 0;
219         for (int i = 0; i < GetListOfMonitoredServices.size(); i++) {
220             if (GetListOfMonitoredServices.get(i).getPolicyType().equals(t)) {
221                 System.out.println("[" + i + "] " + GetListOfMonitoredServices.get(i).getURL());
222                 count++;
223             }
224         }
225         int k = -1;
226         while (k < 0 || k > GetListOfMonitoredServices.size()) {
227             System.out.print("Enter Selection: ");
228             String s = System.console().readLine();
229             try {
230                 k = Integer.parseInt(s);
231             } catch (Exception ex) {
232                 System.out.println("operating canceled");
233                 return -1;
234             }
235         }
236         return k;
237     }
238 
239     private int getServiceFromSelection() {
240         for (int i = 0; i < GetListOfMonitoredServices.size(); i++) {
241             System.out.println("[" + i + "] " + GetListOfMonitoredServices.get(i).getURL());
242         }
243         int k = -1;
244         while (k < 0 || k > GetListOfMonitoredServices.size()) {
245             System.out.print("Enter Selection: ");
246             String s = System.console().readLine();
247             k = Integer.parseInt(s);
248         }
249         return k;
250     }
251 
252     private void getServiceList() throws Exception {
253         GetListOfMonitoredServices = sdk.GetListOfMonitoredServices();
254         System.out.println("Refreshed..." + GetListOfMonitoredServices.size() + " items returned");
255     }
256 
257     private void enterLoop() throws Exception {
258         while (true) {
259             System.out.print(">");
260             String command = System.console().readLine();
261             if (!process(command)) {
262                 System.out.println("Unknown command, try 'help' for a list");
263             }
264         }
265     }
266 
267     private void start() throws Exception {
268         System.out.println("Starting up");
269         Properties p = new Properties();
270         FileInputStream fis = null;
271         try {
272             fis = new FileInputStream("config.properties");
273             p.load(fis);
274         } catch (Exception ex) {
275             System.err.println("problem reading from config.properties, check to make sure it is present and readable");
276             try {
277                 fis.close();
278             } catch (Exception e) {
279             }
280             return;
281         } finally {
282             try {
283                 fis.close();
284             } catch (Exception ex) {
285             }
286         }
287         context = new HashMap<String, Object>();
288         context.put(FgsmsSDK.ARS_ENDPOINT, p.get(FgsmsSDK.ARS_ENDPOINT));
289         context.put(FgsmsSDK.DAS_ENDPOINT, p.get(FgsmsSDK.DAS_ENDPOINT));
290         context.put(FgsmsSDK.PCS_ENDPOINT, p.get(FgsmsSDK.PCS_ENDPOINT));
291         context.put(FgsmsSDK.SS_ENDPOINT, p.get(FgsmsSDK.SS_ENDPOINT));
292         context.put(FgsmsSDK.RS_ENDPOINT, p.get(FgsmsSDK.RS_ENDPOINT));
293 
294         context.put(FgsmsSDK.CLASSIFICATION_LEVEL, ClassificationType.fromValue((String) p.get(FgsmsSDK.CLASSIFICATION_LEVEL)));
295         context.put(FgsmsSDK.CLASSIFICATION_CAVEAT, p.get(FgsmsSDK.CLASSIFICATION_CAVEAT));
296         AuthMode auth = org.miloss.fgsms.common.Constants.AuthMode.valueOf((String) p.get(FgsmsSDK.AUTH_MODE));
297         context.put(FgsmsSDK.AUTH_MODE, auth);
298         if (auth == AuthMode.UsernamePassword) {
299             String username = System.getenv("USERNAME");
300             String pass = System.getenv("PASSWORD");
301             if (Utility.stringIsNullOrEmpty(pass) || Utility.stringIsNullOrEmpty(username)) {
302                 System.out.println("You can also specify the username and password via environment variables USERNAME and PASSWORD");
303                 System.out.print("Username: ");
304                 username = System.console().readLine();
305                 System.out.print("Password: ");
306                 pass = new String(System.console().readPassword());
307             }
308             context.put(FgsmsSDK.USERNAME_PROPERTY, username);
309             context.put(FgsmsSDK.PASSWORD_PROPERTY, pass);
310         }
311         sdk = new FgsmsSDK(context);
312         System.out.println("Configuration appears to be ok...");
313 
314         System.out.println("Logging in...");
315         GetGlobalPolicyResponseMsg GetGlobalPolicy = sdk.GetGlobalPolicy();
316         System.out.println("Current classification level is " + GetGlobalPolicy.getClassification().getClassification().value() + " " + GetGlobalPolicy.getClassification().getCaveats());
317         if (GetGlobalPolicy.getPolicy().isAgentsEnabled()) {
318             System.out.println("Web Service Agents are enabled");
319         } else {
320             System.out.println("Web Service Agents are disabled!");
321         }
322 
323         System.out.println("Retrieving the list of monitored services");
324         GetListOfMonitoredServices = sdk.GetListOfMonitoredServices();
325         System.out.println("done. For a list of commands, enter 'help' and press enter");
326         enterLoop();
327     }
328 
329     private void getAggregatedStats(String command) throws Exception {
330         int x = getServiceFromSelection(PolicyType.TRANSACTIONAL);
331         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
332             return;
333         }
334         GetQuickStatsResponseMsg agg = sdk.GetAggregatedStatistics(GetListOfMonitoredServices.get(x).getURL());
335         DatatypeFactory df = DatatypeFactory.newInstance();
336         GregorianCalendar gcal = new GregorianCalendar();
337         gcal.setTimeInMillis(System.currentTimeMillis());
338 
339         for (int i = 0; i < agg.getQuickStatWrapper().size(); i++) {
340             System.out.println("Action: " + agg.getQuickStatWrapper().get(i).getAction() + " Uptime " + Utility.durationToString(agg.getQuickStatWrapper().get(i).getUptime()));
341             System.out.println("Range\tAvail\tAvgResTime\tSuccess\tFaults\tSLA\tMTBF\tMaxReq\tMaxRes\tMaxResTime\tAge");
342             for (int k = 0; k < agg.getQuickStatWrapper().get(i).getQuickStatData().size(); k++) {
343                 System.out.println(agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getTimeInMinutes().intValue() + "\t"
344                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getAvailabilityPercentage() + "\t"
345                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getAverageResponseTime() + "\t"
346                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getSuccessCount() + "\t"
347                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getFailureCount() + "\t"
348                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getSLAViolationCount() + "\t"
349                         + Utility.durationToString(agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getMTBF()) + "\t"
350                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getMaximumRequestSize() + "\t"
351                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getMaximumResponseSize() + "\t"
352                         + agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getMaximumResponseTime() + "\t"
353                         + Utility.durationLargestUnitToString(df.newDuration(System.currentTimeMillis() - agg.getQuickStatWrapper().get(i).getQuickStatData().get(k).getUpdatedAt().getTimeInMillis())));
354 
355             }
356             System.out.println("Uptime: " + Utility.durationToString(agg.getQuickStatWrapper().get(i).getUptime()));
357 
358             System.out.println("-----------------------------");
359         }
360     }
361 
362     private void getStatusAll() throws Exception {
363         List<GetStatusResponseMsg> GetStatusAll = sdk.GetStatusAll();
364         for (int x = 0; x < GetStatusAll.size(); x++) {
365             System.out.print(GetStatusAll.get(x).getURI());
366             if (GetStatusAll.get(x).isOperational()) {
367                 System.out.print(" OK ");
368             } else {
369                 System.out.print(" NG ");
370             }
371             System.out.println(GetStatusAll.get(x).getMessage() + " as of "
372                     + GetStatusAll.get(x).getTimeStamp().getTime() + " last status change was at " + GetStatusAll.get(x).getLastStatusChangeTimeStamp().getTime());
373         }
374     }
375 
376     private void getStatus() throws Exception {
377         int x = getServiceFromSelection();
378         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
379             return;
380         }
381         GetStatusResponseMsg s = sdk.GetStatus(GetListOfMonitoredServices.get(x).getURL());
382         if (s.isOperational()) {
383             System.out.print("OK ");
384         } else {
385             System.out.print("NG ");
386         }
387         if (s.getTimeStamp() == null) {
388             System.out.println(s.getMessage() + " as last status change was at " + (s.getLastStatusChangeTimeStamp() != null ? s.getLastStatusChangeTimeStamp().getTime() : " never"));
389         } else {
390             System.out.println(s.getMessage() + " as of " + s.getTimeStamp().toString() + " last status change was at " + (s.getLastStatusChangeTimeStamp() != null ? s.getLastStatusChangeTimeStamp().getTime() : " never"));
391         }
392     }
393 
394     private void getEmail() throws Exception {
395         GetMailSettingsResponseMsg emailsettings = sdk.getEmailsettings();
396         for (int i = 0; i < emailsettings.getPropertiesList().size(); i++) {
397             System.out.println(emailsettings.getPropertiesList().get(i).getPropertyName() + " = " + emailsettings.getPropertiesList().get(i).getPropertyValue());
398 
399         }
400     }
401 
402     private void getBrokerPerf() throws Exception {
403         int x = getServiceFromSelection(PolicyType.STATISTICAL);
404         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
405             return;
406         }
407         GetCurrentBrokerDetailsResponseMsg GetBrokerStatistics = sdk.GetBrokerStatistics(GetListOfMonitoredServices.get(x).getURL());
408         System.out.println("URL: " + GetBrokerStatistics.getUri());
409         System.out.println("Name: " + GetBrokerStatistics.getDisplayName());
410         if (GetBrokerStatistics.isOperational()) {
411             System.out.println("ONLINE");
412         } else {
413             System.out.println("OFFLINE");
414         }
415         System.out.println("Name\tType\tConsumers\tMsgCnt\tMsgDrp\tQueueDepth\tTimestamp");
416         for (int i = 0; i < GetBrokerStatistics.getQueueORtopicDetails().size(); i++) {
417             System.out.println(GetBrokerStatistics.getQueueORtopicDetails().get(i).getCanonicalname() + "\t"
418                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getItemtype() + "\t"
419                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getActiveconsumercount() + "\t"
420                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getMessagecount() + "\t"
421                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getMessagesdropped() + "\t"
422                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getQueueDepth() + "\t"
423                     + GetBrokerStatistics.getQueueORtopicDetails().get(i).getTimestamp().toString());
424         }
425     }
426 
427     private void getProcessPerf() throws Exception {
428         int x = getServiceFromSelection(PolicyType.PROCESS);
429         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
430             return;
431         }
432         GetMostRecentProcessDataResponseMsg GetProcessStatistics = sdk.GetProcessStatistics(GetListOfMonitoredServices.get(x).getURL());
433         System.out.println("URL: " + GetProcessStatistics.getPerformanceData().getUri());
434         System.out.println("Status Message: " + GetProcessStatistics.getPerformanceData().getStatusmessage());
435         System.out.println("Status: " + GetProcessStatistics.getPerformanceData().isOperationalstatus());
436         System.out.println("Threads: " + GetProcessStatistics.getPerformanceData().getNumberofActiveThreads());
437         System.out.println("CPU%: " + GetProcessStatistics.getPerformanceData().getPercentusedCPU());
438         System.out.println("Open Files: " + GetProcessStatistics.getPerformanceData().getOpenFileHandles());
439         System.out.println("Memory: " + GetProcessStatistics.getPerformanceData().getBytesusedMemory());
440         System.out.println("Started at: " + GetProcessStatistics.getPerformanceData().getStartedAt());
441         System.out.println("Updated at: " + GetProcessStatistics.getPerformanceData().getTimestamp());
442 
443     }
444 
445     private void getMachinePerf() throws Exception {
446         int x = getServiceFromSelection(PolicyType.MACHINE);
447         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
448             return;
449         }
450         GetMostRecentMachineDataResponseMsg GetMachineStatistics = sdk.GetMachineStatistics(GetListOfMonitoredServices.get(x).getURL());
451         System.out.println("Domain: " + GetMachineStatistics.getMachineData().getDomainName());
452         System.out.println("Hostname: " + GetMachineStatistics.getMachineData().getHostname());
453         System.out.println("Status Message: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getStatusmessage());
454         System.out.println("Status: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().isOperationalstatus());
455         System.out.println("Memory: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getBytesusedMemory());
456         System.out.println("Threads: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getNumberofActiveThreads());
457         System.out.println("CPU%: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getPercentusedCPU());
458         System.out.println("ID: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getId());
459         System.out.println("Updated at: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getTimestamp());
460         System.out.println("Started at: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getStartedAt());
461         for (int i = 0; i < GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().size(); i++) {
462             System.out.println("Partition: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().get(i).getPartition());
463             System.out.println("\tStatus: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().get(i).getOperationalstatus());
464             System.out.println("\tFreespace: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().get(i).getFreespace());
465             System.out.println("\tRead: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().get(i).getKilobytespersecondDiskRead());
466             System.out.println("\tWrite: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getDriveInformation().get(i).getKilobytespersecondDiskWrite());
467         }
468         for (int i = 0; i < GetMachineStatistics.getMachineData().getMachinePerformanceData().getNetworkAdapterPerformanceData().size(); i++) {
469             System.out.println("NIC: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getNetworkAdapterPerformanceData().get(i).getAdapterName());
470             System.out.println("\tStatus: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getNetworkAdapterPerformanceData().get(i).getKilobytespersecondNetworkReceive());
471             System.out.println("\tFreespace: " + GetMachineStatistics.getMachineData().getMachinePerformanceData().getNetworkAdapterPerformanceData().get(i).getKilobytespersecondNetworkTransmit());
472         }
473 
474     }
475 
476     private void getWSLogs() throws Exception {
477         int x = getServiceFromSelection(PolicyType.TRANSACTIONAL);
478         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
479             return;
480         }
481         String url = GetListOfMonitoredServices.get(x).getURL();
482         int records = getInt("Records: ", 1, 10000);
483         int offset = getInt("Offset: ", 0, 1000000);
484         long now = System.currentTimeMillis();
485         List<TransactionLog> transactionLogs = sdk.getTransactionLogs(url, false, false, records, offset);
486         now = System.currentTimeMillis() - now;
487         System.out.println(transactionLogs.size() + " logs fetched in " + now + " ms");
488         printWSLogs(transactionLogs);
489     }
490 
491     private void printWSLogs(List<TransactionLog> transactionLogs) {
492         System.out.println("Timestamp\tID\tRequest\tResponse\tResTime\tFault\tSLA");
493         for (int i = 0; i < transactionLogs.size(); i++) {
494             System.out.print(transactionLogs.get(i).getTimestamp().toString() + "\t" + transactionLogs.get(i).getTransactionId() + "\t" + transactionLogs.get(i).getRequestSize()
495                     + "\t" + transactionLogs.get(i).getResponseSize() + "\t" + transactionLogs.get(i).getResponseTime() + "\t");
496             if (!transactionLogs.get(i).isIsFault()) {
497                 System.out.print("yes");
498             } else {
499                 System.out.print("no");
500             }
501             System.out.print("\t");
502             if (transactionLogs.get(i).isIsSLAFault()) {
503                 System.out.print("yes");
504             } else {
505                 System.out.print("no");
506             }
507             System.out.println();
508         }
509     }
510 
511     private void getWSLogsFault() throws Exception {
512         int x = getServiceFromSelection(PolicyType.TRANSACTIONAL);
513         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
514             return;
515         }
516         String url = GetListOfMonitoredServices.get(x).getURL();
517         int records = getInt("Records: ", 1, 1000);
518         int offset = getInt("Offset: ", 0, 1000000);
519         long now = System.currentTimeMillis();
520         List<TransactionLog> transactionLogs = sdk.getTransactionLogs(url, true, false, records, offset);
521         now = System.currentTimeMillis() - now;
522         System.out.println(transactionLogs.size() + " logs fetched in " + now + " ms");
523         printWSLogs(transactionLogs);
524     }
525 
526     private void getWSLogsSLA() throws Exception {
527         int x = getServiceFromSelection(PolicyType.TRANSACTIONAL);
528         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
529             return;
530         }
531         String url = GetListOfMonitoredServices.get(x).getURL();
532         int records = getInt("Records: ", 1, 10000);
533         int offset = getInt("Offset: ", 0, 1000000);
534         long now = System.currentTimeMillis();
535         List<TransactionLog> transactionLogs = sdk.getTransactionLogs(url, false, true, records, offset);
536         now = System.currentTimeMillis() - now;
537         System.out.println(transactionLogs.size() + " logs fetched in " + now + " ms");
538         printWSLogs(transactionLogs);
539     }
540 
541     private void GetGenSettings() throws Exception {
542         GetGeneralSettingsResponseMsg generalSettings = sdk.getGeneralSettings();
543         System.out.println("Key\tName\tValue");
544         for (int i = 0; i < generalSettings.getKeyNameValue().size(); i++) {
545             System.out.println(generalSettings.getKeyNameValue().get(i).getPropertyKey() + "\t"
546                     + generalSettings.getKeyNameValue().get(i).getPropertyName() + "\t"
547                     + generalSettings.getKeyNameValue().get(i).getPropertyValue());
548 
549         }
550     }
551 
552     private void addGenSetting() throws Exception {
553         System.out.print("Key = ");
554         String key = System.console().readLine();
555 
556         System.out.print("Name = ");
557         String name = System.console().readLine();
558 
559         System.out.print("Value = ");
560         String value = System.console().readLine();
561         sdk.addGeneralSetting(key, name, value, false);
562         System.out.println("Settings added");
563     }
564 
565     private void removeGenSetting() throws Exception {
566         GetGeneralSettingsResponseMsg generalSettings = sdk.getGeneralSettings();
567         System.out.println("Key\tName\tValue");
568         for (int i = 0; i < generalSettings.getKeyNameValue().size(); i++) {
569             System.out.println("[" + i + "]" + generalSettings.getKeyNameValue().get(i).getPropertyKey() + "\t"
570                     + generalSettings.getKeyNameValue().get(i).getPropertyName() + "\t"
571                     + generalSettings.getKeyNameValue().get(i).getPropertyValue());
572         }
573         int k = -1;
574         while (k < 0 || k > generalSettings.getKeyNameValue().size()) {
575             System.out.print("Enter Selection: ");
576             String s = System.console().readLine();
577             try {
578                 k = Integer.parseInt(s);
579             } catch (Exception ex) {
580                 System.out.println("operating canceled");
581                 return;
582             }
583         }
584         sdk.removeGeneralSetting(generalSettings.getKeyNameValue().get(k));
585     }
586 
587     private ServicePolicy getPolicy() throws Exception {
588         return sdk.GetServicePolicy(GetListOfMonitoredServices.get(getServiceFromSelection()).getURL());
589     }
590 
591     private void removePolicy() throws Exception {
592         int x = getServiceFromSelection();
593         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
594             return;
595         }
596         sdk.RemoveServicePolicyAndData(GetListOfMonitoredServices.get(x).getURL());
597         System.out.println("Removed");
598     }
599 
600     private void printPolicy(ServicePolicy p) {
601         System.out.println("URL: " + p.getURL());
602         System.out.println("Parent: " + p.getParentObject());
603         System.out.println("Display name: " + p.getDisplayName());
604         System.out.println("Description: " + p.getDescription());
605         System.out.println("Domain: " + p.getDomainName());
606         System.out.println("Machine: " + p.getMachineName());
607         System.out.println("POC: " + p.getPOC());
608         System.out.println("Type: " + p.getPolicyType().value());
609         System.out.println("External URL: " + p.getExternalURL());
610         System.out.println("Data TTL: " + Utility.durationToString(p.getDataTTL()));
611         if (p.getServiceLevelAggrements() != null && p.getServiceLevelAggrements() != null
612                 && !p.getServiceLevelAggrements().getSLA().isEmpty()) {
613             System.out.println("SLA Defined: " + p.getServiceLevelAggrements().getSLA().size());
614         }
615         if (p.getFederationPolicyCollection() != null && !p.getFederationPolicyCollection().getFederationPolicy().isEmpty()) {
616             System.out.println("Federation Defined: " + p.getFederationPolicyCollection().getFederationPolicy().size());
617         }
618     }
619 
620     private void getPolicyXml(ServicePolicy GetPolicy) throws JAXBException {
621         JAXBContext GetSerializationContext = Utility.getSerializationContext();
622         Marshaller createMarshaller = GetSerializationContext.createMarshaller();
623         createMarshaller.marshal(GetPolicy, System.out);
624         System.out.println();
625     }
626 
627     private void printMachineInformation() throws Exception {
628         int x = getServiceFromSelection(PolicyType.MACHINE);
629         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
630             return;
631         }
632         GetProcessesListByMachineResponseMsg machineInformation = sdk.getMachineInformation(GetListOfMonitoredServices.get(x));
633         System.out.println("Cores: " + machineInformation.getMachineInformation().getCpucorecount());
634         System.out.println("OS: " + machineInformation.getMachineInformation().getOperatingsystem());
635         System.out.println("Memory: " + machineInformation.getMachineInformation().getMemoryinstalled());
636         System.out.println("Last updated at: " + machineInformation.getLastupdateat());
637         for (int i = 0; i < machineInformation.getMachineInformation().getPropertyPair().size(); i++) {
638             System.out.println(machineInformation.getMachineInformation().getPropertyPair().get(i).getPropertyname() + " = " + machineInformation.getMachineInformation().getPropertyPair().get(i).getPropertyvalue());
639         }
640         System.out.println("-----Processes-----");
641         for (int i = 0; i < machineInformation.getProcessName().size(); i++) {
642             System.out.println(machineInformation.getProcessName().get(i));
643         }
644         for (int i = 0; i < machineInformation.getMachineInformation().getAddresses().size(); i++) {
645             System.out.println("NIC: " + machineInformation.getMachineInformation().getAddresses().get(i).getAdapterName());
646             System.out.println("\tIPs: " + Utility.listStringtoString(machineInformation.getMachineInformation().getAddresses().get(i).getIp()));
647             System.out.println("\tDNS: " + Utility.listStringtoString(machineInformation.getMachineInformation().getAddresses().get(i).getDns()));
648             System.out.println("\tDescription: " + machineInformation.getMachineInformation().getAddresses().get(i).getAdapterDescription());
649             System.out.println("\tName: " + machineInformation.getMachineInformation().getAddresses().get(i).getAdapterName());
650             System.out.println("\tGateway: " + machineInformation.getMachineInformation().getAddresses().get(i).getDefaultGateway());
651             System.out.println("\tMAC: " + machineInformation.getMachineInformation().getAddresses().get(i).getMac());
652             System.out.println("\tSubnet: " + machineInformation.getMachineInformation().getAddresses().get(i).getSubnetMask());
653         }
654         for (int i = 0; i < machineInformation.getMachineInformation().getDriveInformation().size(); i++) {
655             System.out.println("Drive: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getPartition());
656             System.out.println("\tID: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getId());
657             System.out.println("\tStatus: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getOperationalstatus());
658             System.out.println("\tSystem ID: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getSystemid());
659             System.out.println("\tType: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getType());
660             System.out.println("\tTotal space: " + machineInformation.getMachineInformation().getDriveInformation().get(i).getTotalspace());
661 
662         }
663     }
664 
665     private void addAProcessToMonitor() throws Exception {
666         int x = getServiceFromSelection(PolicyType.MACHINE);
667         if (x == -1 || x < 0 || x >= this.GetListOfMonitoredServices.size()) {
668             return;
669         }
670         GetProcessesListByMachineResponseMsg machineInformation = sdk.getMachineInformation(GetListOfMonitoredServices.get(x));
671 
672         for (int i = 0; i < machineInformation.getProcessName().size(); i++) {
673             System.out.println("[" + i + "] " + machineInformation.getProcessName().get(i));
674         }
675         int k = -1;
676         while (k < 0 || k > machineInformation.getProcessName().size()) {
677             System.out.print("Enter Selection: ");
678             String s = System.console().readLine();
679             try {
680                 k = Integer.parseInt(s);
681             } catch (Exception ex) {
682                 System.out.println("operating canceled");
683                 return;
684             }
685         }
686         sdk.StartProcessMonitor(machineInformation.getProcessName().get(k),
687                 machineInformation.getMachineInformation().getHostname(),
688                 machineInformation.getMachineInformation().getDomain(),
689                 null, //display name
690                 machineInformation.getMachineInformation().getUri(), 30L * 24L * 60L * 60L * 1000L,
691                 null //additional SLAs other than status change, send an email
692         );
693         System.out.println("Process Policy Created. It may take 30 seconds or more to start recieving performance data.");
694     }
695 
696     private void dumpProperties() {
697         Iterator<Entry<String, Object>> iterator = context.entrySet().iterator();
698         while (iterator.hasNext()) {
699             Entry<String, Object> next = iterator.next();
700             if (next.getKey() == FgsmsSDK.PASSWORD_PROPERTY) {
701                 System.out.println(next.getKey() + " = *********");
702             } else {
703                 System.out.println(next.getKey() + " = " + next.getValue().toString());
704             }
705         }
706     }
707 
708     private int getInt(String msg, int min, int max) {
709         int k = -1;
710         do {
711             System.out.print(msg);
712             try {
713                 String s = System.console().readLine();
714                 k = Integer.parseInt(s);
715             } catch (Exception ex) {
716             }
717         } while (k > max || k < min);
718         return k;
719     }
720 
721     private void GetWSLogsDetails() throws Exception {
722         String x = "";
723         while (Utility.stringIsNullOrEmpty(x)) {
724             System.out.print("Transaction ID = ");
725             x = System.console().readLine();
726         }
727 
728         long now = System.currentTimeMillis();
729         GetMessageTransactionLogDetailsResponseMsg GetMessagePayload = sdk.GetMessagePayload(x);
730         now = System.currentTimeMillis() - now;
731         System.out.println("Details fetched in " + now + " ms");
732         printWSDetails(GetMessagePayload);
733     }
734 
735     private void printWSDetails(GetMessageTransactionLogDetailsResponseMsg pl) {
736         System.out.println("Corrected URL = " + pl.getCorrectedURL());
737         System.out.println("Requested URL = " + pl.getOriginalRequestURL());
738         System.out.println("Action = " + pl.getAction());
739 
740         System.out.println("Monitored at = " + pl.getMonitorHostname());
741         System.out.println("Service hosted at = " + pl.getServiceHostname());
742         System.out.println("Thread id = " + pl.getTransactionthreadId());
743         System.out.println("SLA fault = " + pl.getSlaFaultMsg());
744         System.out.println("Agent memo = " + pl.getAgentMemo());
745         System.out.println("Agent Type = " + pl.getAgentType());
746         System.out.println("Related transaction = " + pl.getRelatedTransactionID());
747         System.out.println("Thread id = " + pl.getTransactionthreadId());
748         System.out.println("Requestor = " + Utility.listStringtoString(pl.getIdentity()));
749         System.out.println("=============== Request");
750         for (int i = 0; i < pl.getHeadersRequest().size(); i++) {
751             System.out.println(pl.getHeadersRequest().get(i).getName() + " = " + Utility.listStringtoString(pl.getHeadersRequest().get(i).getValue()));
752         }
753         System.out.println(pl.getXmlRequestMessage());
754         System.out.println("=============== Response");
755         for (int i = 0; i < pl.getHeadersResponse().size(); i++) {
756             System.out.println(pl.getHeadersResponse().get(i).getName() + " = " + Utility.listStringtoString(pl.getHeadersResponse().get(i).getValue()));
757         }
758         System.out.println(pl.getXmlResponseMessage());
759     }
760 
761     private void machineNetBulk(String command) throws Exception {
762 
763         String split = command.toLowerCase().replace("machine-net-bulk", "");
764         split = split.toLowerCase().replace("machine-net-loop", "");
765         split = split.trim();
766         String[] inputs = split.split("\\s");
767         if (inputs.length != 2) {
768             System.out.println("need to enter: (hostname prefix) (nic id)");
769             return;
770         }
771         System.out.println("Parsed as " + inputs[0].trim() + " and " + inputs[1].trim());
772         List<ServiceType> data = new ArrayList<ServiceType>();
773         for (int i = 0; i < this.GetListOfMonitoredServices.size(); i++) {
774             if (this.GetListOfMonitoredServices.get(i).getPolicyType() == PolicyType.MACHINE
775                     && this.GetListOfMonitoredServices.get(i).getHostname().toLowerCase().startsWith(inputs[0])) {
776                 data.add(this.GetListOfMonitoredServices.get(i));
777             }
778         }
779 
780         List<ServicePolicy> pols = new ArrayList<ServicePolicy>();
781         for (int i = 0; i < data.size(); i++) {
782             ServicePolicy policy = sdk.GetServicePolicy(data.get(i).getURL());
783             MachinePolicy mp = (MachinePolicy) policy;
784             boolean ok = false;
785             for (int k = 0; k < mp.getRecordNetworkUsage().size(); k++) {
786                 if (mp.getRecordNetworkUsage().get(k).equalsIgnoreCase(inputs[1])) {
787                     ok = true;
788                 }
789             }
790             if (!ok) {
791                 mp.getRecordNetworkUsage().add(inputs[1]);
792                 pols.add(mp);
793             }
794         }
795         System.out.println(pols.size() + " to be altered");
796         sdk.SetServicePolicies(pols);
797         System.out.println("success");
798 
799     }
800 
801     private void machineDelBulk(String command) throws Exception {
802 
803         String split = command.toLowerCase().replace("machine-del-bulk", "");
804         split = split.trim();
805 
806         if (split.length() == 0) {
807             System.out.println("need to enter: (prefix) ");
808             return;
809         }
810 
811         System.out.println("Parsed as " + split);
812         List<String> urls = new ArrayList<String>();
813 
814         for (int i = 0; i < this.GetListOfMonitoredServices.size(); i++) {
815             if (this.GetListOfMonitoredServices.get(i).getPolicyType() == PolicyType.MACHINE
816                     && this.GetListOfMonitoredServices.get(i).getHostname().toLowerCase().startsWith(split)) {
817                 urls.add(this.GetListOfMonitoredServices.get(i).getURL());
818             }
819         }
820 
821         System.out.println(urls.size() + " to be altered");
822 
823         sdk.DeleteServicePolicies(urls);
824         System.out.println("success");
825 
826     }
827 
828     private void reportsDroneNic(String command) throws Exception {
829 
830         String split = command.toLowerCase().replace("report-drone-nic", "");
831         split = split.trim();
832 
833         if (split.length() == 0) {
834             System.out.println("need to enter: (prefix) (startTime) (endTime) (nic)");
835             return;
836         }
837 
838         System.out.println("Parsed as " + split);
839         String[] items = split.split(" ");
840 
841         List<String> urls = new ArrayList<String>();
842 
843         for (int i = 0; i < this.GetListOfMonitoredServices.size(); i++) {
844             if (this.GetListOfMonitoredServices.get(i).getPolicyType() == PolicyType.MACHINE
845                     && this.GetListOfMonitoredServices.get(i).getHostname().toLowerCase().startsWith(items[0])) {
846                 urls.add(this.GetListOfMonitoredServices.get(i).getURL());
847             }
848         }
849 
850         System.out.println(urls.size() + " to be fetched");
851         String filename = System.currentTimeMillis() + "CSVExport.zip";
852         sdk.GetHtmlReportNIC(urls, items[3], Long.parseLong(items[1]), Long.parseLong(items[2]), filename);
853 
854         System.out.println("success, written to " + new File(filename).getAbsolutePath());
855 
856     }
857 
858     private void exportsDroneNic(String command) throws Exception {
859 
860         String split = command.toLowerCase().replace("export-drone-nic", "");
861         split = split.trim();
862 
863         if (split.length() == 0) {
864             System.out.println("need to enter: (prefix) (startTime) (endTime) (nic)");
865             return;
866         }
867 
868         System.out.println("Parsed as " + split);
869         String[] items = split.split(" ");
870 
871         List<String> urls = new ArrayList<String>();
872 
873         for (int i = 0; i < this.GetListOfMonitoredServices.size(); i++) {
874             if (this.GetListOfMonitoredServices.get(i).getPolicyType() == PolicyType.MACHINE
875                     && this.GetListOfMonitoredServices.get(i).getHostname().toLowerCase().startsWith(items[0])) {
876                 urls.add(this.GetListOfMonitoredServices.get(i).getURL());
877             }
878         }
879 
880         System.out.println(urls.size() + " to be fetched");
881         String filename = System.currentTimeMillis() + "CSVExport.zip";
882         sdk.GetCSVExportNIC(urls, items[3], Long.parseLong(items[1]), Long.parseLong(items[2]), filename);
883 
884         System.out.println("success, written to " + new File(filename).getAbsolutePath());
885 
886     }
887 }