KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > commands > GenerateReportCommand


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.cli.commands;
25
26 import com.sun.enterprise.cli.framework.*;
27 import com.sun.enterprise.diagnostics.DiagnosticException;
28 import com.sun.enterprise.diagnostics.DiagnosticAgent;
29 import com.sun.enterprise.admin.common.JMXFileTransfer;
30
31 import javax.management.MBeanServerConnection JavaDoc;
32 import javax.management.ObjectName JavaDoc;
33 import java.io.File JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.HashMap JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41 import java.text.DateFormat JavaDoc;
42 import java.text.SimpleDateFormat JavaDoc;
43 import java.text.ParseException JavaDoc;
44 import java.io.FileNotFoundException JavaDoc;
45
46
47 /**
48  * This command will get the version of the application server
49  * @version $Revision: 1.10 $
50  */

51 public class GenerateReportCommand extends BaseLifeCycleCommand
52 {
53     private static final String JavaDoc LOG_START_DATE_OPTION = "logstartdate";
54     private static final String JavaDoc LOG_END_DATE_OPTION = "logenddate";
55     private static final String JavaDoc LOCAL_OPTION = "local";
56     private static final String JavaDoc OUTPUT_FILE_OPTION = "outputfile";
57     private static final String JavaDoc FILE_OPTION = "file";
58     private static final String JavaDoc BUGIDS_OPTION = "bugids";
59     private static final String JavaDoc TARGET_DIR_OPTION = "targetdir";
60     private static final String JavaDoc TARGET ="target";
61     private final String JavaDoc CONF_ATTR_MSG =
62                                 getLocalizedString("ConfidentialAttrMsg");
63     private final String JavaDoc INSTRUCTIONS =
64                                 getLocalizedString("ConfidentialAttrInstructions");
65     private final String JavaDoc PROMPT_STRING =
66                                 getLocalizedString("PromptToContinue");
67     private static final String JavaDoc YES_STRING = "y";
68     private static final String JavaDoc NO_STRING = "n";
69     
70     private String JavaDoc sOutputFile;
71     
72     /**
73      * An abstract method that validates the options
74      * on the specification in the xml properties file
75      * This method verifies for the correctness of number of
76      * operands and if all the required options are supplied by the client.
77      * @return boolean returns true if success else returns false
78      */

79     public boolean validateOptions() throws CommandValidationException
80     {
81         if (!super.validateOptions())
82             return false;
83         if (getBooleanOption(LOCAL_OPTION) == true)
84         {
85             if (getOption(TARGET_DIR_OPTION) == null)
86                 throw new CommandValidationException(
87                                 getLocalizedString("OptionRequiredInLocalMode",
88                                             new Object JavaDoc[] {TARGET_DIR_OPTION}));
89         }
90         if ((getOption(LOG_END_DATE_OPTION) != null) &&
91                 (getOption(LOG_START_DATE_OPTION) == null))
92         {
93             throw new CommandValidationException(
94                                 getLocalizedString("OptionRequiredWithOption",
95                                         new Object JavaDoc[] {LOG_START_DATE_OPTION,
96                                                       LOG_END_DATE_OPTION}));
97         }
98         sOutputFile = getOption(OUTPUT_FILE_OPTION);
99         return true;
100     }
101
102     /**
103      * An abstract method that Executes the command
104      * @throws CommandException
105      */

106     public void runCommand() throws CommandException, CommandValidationException
107     {
108         //if validateOptions is false, then it must be that --help option
109
//is provided and there is no need to execute the command since
110
//either manpage or usage text is displayed
111
if (!validateOptions())
112             return;
113         
114         try {
115             if (!isDateValid(getOption(LOG_START_DATE_OPTION)) ||
116                 !isDateValid(getOption(LOG_END_DATE_OPTION)) ||
117                 !compareDates(getOption(LOG_START_DATE_OPTION),
118                                 getOption(LOG_END_DATE_OPTION)) ||
119                 !isFileValid(getOption(FILE_OPTION)) ||
120                 !isOutputFileValid(sOutputFile) ||
121                 !isDirectoryValid(getOption(TARGET_DIR_OPTION)))
122             return;
123             
124             if (getBooleanOption(LOCAL_OPTION)) {
125                 executeCommandLocalMode();
126             }
127                 //Start the code for remote version of the command
128
//
129
else {
130                 executeCommandRemoteMode();
131             }
132         
133             CLILogger.getInstance().printDetailMessage(getLocalizedString(
134                                                        "CommandSuccessful",
135                                                        new Object JavaDoc[] {name}));
136         }
137         catch(Exception JavaDoc e) {
138             if (e.getLocalizedMessage() != null)
139                 displayExceptionMessage(e);
140             throw new CommandException(getLocalizedString("CommandUnSuccessful",
141                                                      new Object JavaDoc[] {name} ), e);
142         }
143      }
144
145
146         /**
147          * This routine will generate the diagnostic report remotely.
148          **/

149     private void executeCommandRemoteMode() throws Exception JavaDoc
150     {
151         final String JavaDoc objectName = getObjectName();
152         //use http connector
153
MBeanServerConnection JavaDoc mbsc = getMBeanServerConnection(getHost(),
154                                                               getPort(),
155                                                               getUser(),
156                                                               getPassword());
157
158         List JavaDoc<String JavaDoc> confidentialAttrs = (List JavaDoc)mbsc.getAttribute(new ObjectName JavaDoc(objectName),
159                                                                  "ConfidentialProperties");
160         printAttributes(confidentialAttrs);
161         final String JavaDoc input = printPromptToContinue();
162         if (input.equalsIgnoreCase("y"))
163             CLILogger.getInstance().printDebugMessage("continue");
164         else
165         {
166             CLILogger.getInstance().printDebugMessage("exiting");
167             return;
168         }
169         final String JavaDoc operationName = getOperationName();
170         final Object JavaDoc[] params = new Object JavaDoc[] {createCLIOptionsMap()};
171         final String JavaDoc[] types = getTypesInfo();
172
173         final String JavaDoc sServerLocation = (String JavaDoc)mbsc.invoke(new ObjectName JavaDoc(objectName),
174                                                  operationName, params, types);
175
176         getDiagnosticReport(mbsc, sServerLocation,
177                             new File JavaDoc(sOutputFile).getParent(),
178                             new File JavaDoc(sOutputFile).getName());
179     }
180     
181
182     
183     /**
184      * retrieve diagnostic report
185      */

186     private void getDiagnosticReport(MBeanServerConnection JavaDoc mbsc,
187                                        String JavaDoc sFileDownload,
188                                        String JavaDoc sDownloadPath, String JavaDoc sFileName)
189         throws CommandException
190     {
191         try
192         {
193             final String JavaDoc fileName = new JMXFileTransfer(mbsc).downloadFile(sFileDownload,
194                                                                            sDownloadPath,
195                                                                            sFileName);
196             CLILogger.getInstance().printDebugMessage("downloaded from : " + sFileDownload + " to : " + sDownloadPath);
197         }
198         catch (Exception JavaDoc e)
199         {
200             Throwable JavaDoc t = e.getCause();
201             while(t!=null && t.getCause()!=null)
202                 t=t.getCause();
203             if(t==null)
204                 t=e;
205             throw new CommandException(t.getLocalizedMessage(),t);
206         }
207     }
208
209
210     private void checkDiagnosticFile(final String JavaDoc sDownloadPath) throws Exception JavaDoc
211     {
212         final File JavaDoc dlDir = new File JavaDoc(sDownloadPath);
213         if (!dlDir.exists() )
214         {
215             dlDir.mkdirs();
216         }
217         if(!dlDir.exists() || !dlDir.canWrite() || !dlDir.isDirectory() ) {
218             throw new CommandValidationException(getLocalizedString(
219                          "InvalidDirectory",new Object JavaDoc [] {sDownloadPath}));
220         }
221     }
222
223     
224         /**
225          * This routine will generate the diagnostic report locally.
226          **/

227     private void executeCommandLocalMode() throws CommandException
228     {
229             final DiagnosticAgent agent = getFeatureFactory().getDiagnosticAgent();
230             final List JavaDoc<String JavaDoc> confidentialAttrs = getConfidentialAttributes(
231                 getOption(TARGET_DIR_OPTION),
232                 (String JavaDoc)operands.firstElement(), agent);
233             printAttributes(confidentialAttrs);
234             
235             final String JavaDoc input = printPromptToContinue();
236             
237             if (input.equalsIgnoreCase("y"))
238                 CLILogger.getInstance().printDebugMessage("continue");
239             else
240             {
241                 CLILogger.getInstance().printDebugMessage("exiting");
242                 return;
243             }
244       
245             final String JavaDoc reportFile = generateReport(createCLIOptionsMap(), agent);
246             CLILogger.getInstance().printMessage(
247                                 getLocalizedString("ReportFile",
248                                                 new Object JavaDoc[] {reportFile}));
249     }
250     
251
252     /**
253      * This method gets the Version locally
254      */

255     private boolean isDateValid(String JavaDoc dateStr) throws CommandException
256     {
257         if (dateStr == null) return true;
258         try
259         {
260             DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("MM/dd/yyyy");
261             Date JavaDoc date = df.parse(dateStr);
262             return true;
263         }
264         catch (ParseException JavaDoc pe)
265         {
266             throw new CommandException(
267                                 getLocalizedString("InvalidDate",
268                                                 new Object JavaDoc[] {dateStr}));
269         }
270     }
271    
272
273     private boolean compareDates(String JavaDoc startDateStr, String JavaDoc endDateStr)
274             throws CommandException
275     {
276         if ((startDateStr == null) || (endDateStr == null)) return true;
277         try
278         {
279             DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("MM/dd/yyyy");
280             Date JavaDoc startDate = df.parse(startDateStr);
281             Date JavaDoc endDate = df.parse(endDateStr);
282             if (startDate.compareTo(endDate) > 0)
283             {
284                 throw new CommandException(
285                                 getLocalizedString("InvalidDateBeforeDate"));
286             }
287         }
288         catch (ParseException JavaDoc pe)
289         {
290             throw new CommandException(
291                                 getLocalizedString("InvalidDateError"));
292         }
293         return true;
294     }
295     
296     
297     private boolean isFileValid(String JavaDoc fileStr) throws CommandException
298     {
299         if (fileStr == null) return true;
300         final File JavaDoc file = checkForFileExistence(null, fileStr);
301         if (file == null)
302             throw new CommandException(getLocalizedString("FileDoesNotExist",
303                                                       new Object JavaDoc[] {fileStr}));
304         return true;
305     }
306
307     
308     private boolean isDirectoryValid(String JavaDoc directory) throws CommandException
309     {
310         if (directory == null) return true;
311         File JavaDoc file = new File JavaDoc(directory);
312         if (!file.isDirectory() || !file.canRead())
313             throw new CommandException(getLocalizedString("InvalidDirectory",
314                                                 new Object JavaDoc[]{directory}));
315         return true;
316     }
317
318     
319     private boolean isOutputFileValid(String JavaDoc sFile) throws Exception JavaDoc
320     {
321         if (sFile == null) return false;
322         final File JavaDoc file = new File JavaDoc(sFile);
323         final String JavaDoc sFileName = file.getName();
324         
325         if (file.getParent()!=null) {
326             checkDiagnosticFile(file.getParent());
327         }
328
329         if (!sFileName.endsWith(".jar"))
330             throw new CommandException(getLocalizedString("InvalidOutputFile"));
331         return true;
332     }
333
334     
335     private String JavaDoc generateReport(Map JavaDoc clioptions, DiagnosticAgent agent) throws CommandException
336     {
337         
338         try {
339             return agent.generateReport(clioptions);
340         } catch (DiagnosticException de) {
341             de.printStackTrace();
342             throw new CommandException(de.getMessage());
343         }
344          
345         //return null;
346
}
347     
348     
349     private List JavaDoc<String JavaDoc> getConfidentialAttributes(String JavaDoc targetDir,
350             String JavaDoc targetName, DiagnosticAgent agent) throws CommandException
351     {
352         
353         try {
354             return agent.getConfidentialProperties(targetDir +
355                     File.separator + targetName);
356         } catch(DiagnosticException e) {
357             throw new CommandException(e.getMessage());
358         }
359          
360         //return null;
361

362     }
363     
364     
365     private Map JavaDoc createCLIOptionsMap()
366     {
367         Map JavaDoc cliOptions = new HashMap JavaDoc();
368         String JavaDoc target = (String JavaDoc)operands.firstElement();
369         CLILogger.getInstance().printDebugMessage(" Target : " + target);
370         cliOptions.put(LOCAL_OPTION, getOption(LOCAL_OPTION));
371         cliOptions.put(TARGET, target);
372         if (getOption(LOG_START_DATE_OPTION) != null)
373             cliOptions.put(LOG_START_DATE_OPTION,
374                             new Date JavaDoc(getOption(LOG_START_DATE_OPTION)));
375         if (getOption(LOG_END_DATE_OPTION) != null)
376             cliOptions.put(LOG_END_DATE_OPTION,
377                             new Date JavaDoc(getOption(LOG_END_DATE_OPTION)));
378         if (getOption(FILE_OPTION) != null)
379             cliOptions.put(FILE_OPTION, getOption(FILE_OPTION));
380         if (sOutputFile != null && getBooleanOption(LOCAL_OPTION))
381             cliOptions.put(OUTPUT_FILE_OPTION, sOutputFile);
382         cliOptions.put(TARGET_DIR_OPTION, getOption(TARGET_DIR_OPTION));
383         if (getOption(BUGIDS_OPTION) != null)
384             cliOptions.put(BUGIDS_OPTION, getOption(BUGIDS_OPTION));
385
386         return cliOptions;
387     }
388     
389     
390     private void printAttributes(List JavaDoc<String JavaDoc> attrs)
391     {
392         if(attrs != null)
393         {
394             CLILogger.getInstance().printMessage(CONF_ATTR_MSG);
395             
396             Iterator JavaDoc<String JavaDoc> iterator = attrs.iterator();
397             while(iterator.hasNext())
398             {
399                 CLILogger.getInstance().printMessage(iterator.next());
400             }
401         }
402     }
403
404     
405     private String JavaDoc printPromptToContinue() throws CommandException
406     {
407         try
408         {
409             String JavaDoc line = null;
410             while (!isValidInput(line))
411             {
412                 CLILogger.getInstance().printMessage(INSTRUCTIONS);
413                 InputsAndOutputs.getInstance().getUserOutput().print(PROMPT_STRING);
414                 line = InputsAndOutputs.getInstance().getUserInput().getLine().trim();
415             }
416             return line;
417         }
418         catch (IOException JavaDoc ioe)
419         {
420             throw new CommandException(getLocalizedString("CouldNotPrintOrRead"),
421                                        ioe);
422         }
423     }
424     
425     
426     private boolean isValidInput(final String JavaDoc line)
427     {
428         if ( line == null )
429         {
430             return false;
431         }
432         if ( line == null ||
433                 line.trim().equals("") ||
434                 line.length() < 1 ||
435                 (!line.equalsIgnoreCase(YES_STRING) &&
436                     !line.equalsIgnoreCase(NO_STRING)))
437             return false;
438         return true;
439     }
440 }
441
Popular Tags