KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > mbeans > SystemServicesMBean


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
25 package com.sun.enterprise.admin.mbeans;
26
27 import java.io.File JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.RandomAccessFile JavaDoc;
32 import java.util.logging.Level JavaDoc;
33 import java.util.logging.Logger JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.Hashtable JavaDoc;
36 import java.lang.reflect.Method JavaDoc;
37
38 import javax.management.MBeanInfo JavaDoc;
39 import javax.management.MBeanException JavaDoc;
40 import javax.management.MBeanServer JavaDoc;
41 import javax.management.ObjectName JavaDoc;
42 import javax.management.DynamicMBean JavaDoc;
43 import javax.management.Attribute JavaDoc;
44 import javax.management.AttributeList JavaDoc;
45 import javax.management.AttributeNotFoundException JavaDoc;
46 import javax.management.MBeanAttributeInfo JavaDoc;
47 import javax.management.MBeanConstructorInfo JavaDoc;
48 import javax.management.MBeanOperationInfo JavaDoc;
49 import javax.management.MBeanNotificationInfo JavaDoc;
50 import javax.management.MBeanParameterInfo JavaDoc;
51 import javax.management.MBeanException JavaDoc;
52
53 import com.sun.enterprise.admin.common.ByteChunk;
54 import com.sun.enterprise.admin.common.DownloadRequestInfo;
55 import com.sun.enterprise.admin.server.core.AdminService;
56 import com.sun.enterprise.util.io.FileUtils;
57 import com.sun.enterprise.admin.common.constant.AdminConstants;
58 import com.sun.enterprise.admin.server.core.mbean.meta.MBeanInfoBuilder;
59 import com.sun.enterprise.admin.common.exception.*;
60 import com.sun.enterprise.admin.common.MBeanServerFactory;
61 //i18n import
62
import com.sun.enterprise.util.i18n.StringManager;
63
64 import com.sun.enterprise.admin.server.core.AdminService;
65
66
67 import com.sun.enterprise.config.*;
68 import com.sun.enterprise.config.serverbeans.*;
69 import com.sun.enterprise.admin.common.constant.AdminConstants;
70 import com.sun.enterprise.deployment.phasing.DeploymentServiceUtils;
71 import com.sun.enterprise.instance.InstanceEnvironment;
72 import com.sun.enterprise.instance.AppsManager;
73 import com.sun.enterprise.instance.EjbModulesManager;
74 import com.sun.enterprise.instance.WebModulesManager;
75 import com.sun.enterprise.instance.AppclientModulesManager;
76 import com.sun.enterprise.util.SystemPropertyConstants;
77
78 import com.sun.enterprise.admin.mbeanapi.ISystemServicesMBean;
79
80 import com.sun.enterprise.util.RelativePathResolver;
81
82 /** This mbean provides system services. Currently it provides uploading of a file
83  * to server and downloading of client stubs in chunks.
84  * @since 8.0
85  */

86 public class SystemServicesMBean implements DynamicMBean JavaDoc, ISystemServicesMBean {
87     
88     private static final Logger JavaDoc sLogger = Logger.getLogger(AdminConstants.kLoggerName);
89     /** Map containing id and outputstream and name,value pair */
90     private Map JavaDoc mStreamTable = new Hashtable JavaDoc();
91     /** MBeanInfo for this MBean */
92     private MBeanInfo JavaDoc info = null;
93     private static StringManager localStrings = StringManager.getManager( SystemServicesMBean.class );
94     
95
96     /** Uploads the given ByteChunk to the Server. This will be saved
97      * in an area defined by the server and then the complete path
98      * where the file is saved is returned. This path can later be
99      * used for deployment to a specific Server Instance. Argument may not be
100      * null.
101      * @param byteChunk the ByteChunk instance that contains bytes of a file.
102      * @throws MBeanException jmx exception
103      * @return String representing the complete path of the file.
104      */

105     
106     public String JavaDoc uploadToServer(ByteChunk byteChunk) throws MBeanException JavaDoc {
107         if (byteChunk == null) {
108             throw new IllegalArgumentException JavaDoc();
109         }
110         String JavaDoc fileName = byteChunk.getChunkedFileName();
111         String JavaDoc id = byteChunk.getId();
112
113         File JavaDoc localDir = new File JavaDoc (AdminService.getAdminService().getTempDirPath(),id);
114         localDir.mkdirs();
115         String JavaDoc localPath = FileUtils.safeGetCanonicalPath(localDir);
116
117         // Begin EE: 4946914 - cluster deployment support
118

119         // use target dir from byte chunk obj
120
String JavaDoc targetDirName = byteChunk.getTargetDir();
121         if (targetDirName != null) {
122             //File targetDir = new File(localPath, targetDirName);
123
File JavaDoc targetDir = new File JavaDoc(targetDirName);
124
125             // if relative to the instance root
126
if (!targetDir.isAbsolute()) {
127                 String JavaDoc instanceRoot = System.getProperty(
128                     SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
129
130                 targetDir = new File JavaDoc(instanceRoot, targetDirName);
131             }
132             else {
133                 String JavaDoc msg = localStrings.getString( "admin.mbeans.ssmb.absolute_dirs_not_allowed" );
134                 throw new MBeanException JavaDoc( new IllegalAccessException JavaDoc(), msg );
135
136            }
137             if (!targetDir.exists()) {
138                 targetDir.mkdir();
139             }
140             localPath = FileUtils.safeGetCanonicalPath(targetDir);
141         }
142
143         // End EE: 4946914 - cluster deployment support
144

145         File JavaDoc uploadFile = new File JavaDoc(localPath, fileName);
146         localPath = FileUtils.safeGetCanonicalPath(uploadFile);
147         if (byteChunk.isFirst()) {
148             if (uploadFile.exists()) {
149                 sLogger.log(Level.INFO, "mbean.temp_upload_file_exists", localPath);
150                 boolean couldDelete = uploadFile.delete();
151                 if (couldDelete) {
152                     sLogger.log(Level.FINE, "mbean.delete_temp_file_ok", localPath);
153                 }
154                 else {
155                     sLogger.log(Level.INFO, "mbean.delete_temp_file_failed", localPath);
156                 }
157             }
158             OutputStream JavaDoc outStream = createOutputStream(localPath);
159             mStreamTable.put(id, outStream);
160             sLogger.log(Level.INFO, "mbean.begin_upload", localPath);
161         }
162         saveFile(localPath, byteChunk);
163         // check if this file is a zip file
164

165         return ( localPath );
166     }
167     
168     /**
169      * Returns infomation for the download of the file - mainly size and
170      * total number of chunks for this request. This method supports
171      * multiple distributed clients.
172      *
173      * @param filepath path to the download request
174      */

175     public DownloadRequestInfo mcPrepareDownload(String JavaDoc filePath)
176             throws MBeanException JavaDoc
177     {
178
179         filePath = RelativePathResolver.resolvePath(filePath);
180
181         File JavaDoc dFile = new File JavaDoc(filePath);
182
183         // the following is done for synchronization clients.
184
// If a request comes with a relative path,
185
// server install root is prefixed.
186
if (!dFile.isAbsolute())
187         {
188             String JavaDoc instanceRoot = System.getProperty(
189                     SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
190             sLogger.log(Level.CONFIG, "mbean.prep_download",
191                         instanceRoot + filePath);
192             dFile = new File JavaDoc(instanceRoot, filePath);
193         }
194         else
195         {
196             sLogger.log(Level.CONFIG, "mbean.prep_download", filePath);
197         }
198
199         // download file must exist
200
if (!dFile.exists())
201         {
202             String JavaDoc msg = localStrings.getString(
203                 "admin.mbeans.ssmb.file_doesnot_exist",
204                 dFile.getAbsolutePath() );
205             throw new MBeanException JavaDoc(new java.io.FileNotFoundException JavaDoc(), msg);
206         }
207
208         return new DownloadRequestInfo(dFile);
209     }
210
211     /**
212      * Prepares the download of the file
213      *
214      * @param filePath The path to the file to be downloaded
215      * @return DownloadInfo contains info about the file to be downloaded.
216      * @throws MBeanException when the mbean fails to acquire lock for
217      * the file to be downloaded
218      *
219      * @deprecated replaced by {@link #mcPrepareDownload(java.lang.String)}
220      */

221     public Object JavaDoc prepareDownload(String JavaDoc filePath) throws MBeanException JavaDoc
222     {
223         //Temporary fix - Ramakanth
224
filePath = RelativePathResolver.resolvePath(filePath);
225
226         File JavaDoc downloadFile = new File JavaDoc(filePath);
227         // the following is done for synchronization clients.
228
// If a request comes with a relative path, server install root is prefixed.
229
if (!downloadFile.isAbsolute())
230         {
231             String JavaDoc instanceRoot = System.getProperty(
232                     SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
233             sLogger.log(Level.CONFIG, "mbean.prep_download",
234                         instanceRoot + filePath);
235             downloadFile = new File JavaDoc(instanceRoot, filePath);
236         }
237         else {
238             sLogger.log(Level.CONFIG, "mbean.prep_download", filePath);
239         }
240         if (!downloadFile.exists())
241         {
242             String JavaDoc msg = localStrings.getString( "admin.mbeans.ssmb.file_doesnot_exist", downloadFile.getAbsolutePath() );
243             throw new MBeanException JavaDoc( new java.io.FileNotFoundException JavaDoc(), msg );
244         }
245         try
246         {
247             if (lock == null)
248             {
249                 lock = new Lock();
250             }
251             lock.attempt(1000);
252         }
253         catch (Exception JavaDoc ie)
254         {
255             String JavaDoc msg = localStrings.getString( "admin.server.core.mbean.config.could_not_acquire_lock", ie.toString() );
256             throw new MBeanException JavaDoc( ie, msg );
257         }
258         if (downloadInfo == null)
259         {
260             downloadInfo = new DownloadInfo();
261         }
262         downloadInfo.downloadFile = downloadFile;
263         long size = downloadInfo.downloadFile.length();
264         downloadInfo.numChunks = Math.round(size/ByteChunk.kChunkMaxSize);
265         if (downloadInfo.numChunks * ByteChunk.kChunkMaxSize < size)
266         {
267             downloadInfo.numChunks += 1;
268         }
269         /*
270           Debug.println("File=" + downloadInfo.downloadFile.getAbsolutePath() +
271                       ", " + "size=" + size + ", " +
272                       "Num chunks=" + downloadInfo.numChunks);
273         */

274         downloadInfo.isPrepared = true;
275         return null;
276     }
277
278     /**
279      * Downloads the file in chunks
280      *
281      * @param chunkInteger The index to the chunk array.
282      * @return ByteChunk the byte chunk corresponding to the passed chunk index
283      *
284      * @throws MBeanException when exceptions occur, the exception
285      * that caused will be in the exception chain.
286      *
287      * @deprecated replaced by {@link #mcDownloadFile(DownloadRequestInfo)}
288      */

289     public ByteChunk downloadFile(Integer JavaDoc chunkInteger) throws MBeanException JavaDoc
290     {
291         int chunkIndex = chunkInteger.intValue();
292         sLogger.log(Level.FINE, "mbean.begin_download");
293         if (downloadInfo == null)
294         {
295             String JavaDoc msg = localStrings.getString( "admin.mbeans.ssmb.call_preparedownload_first" );
296             throw new MBeanException JavaDoc( new java.lang.IllegalStateException JavaDoc( msg ) );
297         }
298         else if (!downloadInfo.isPrepared)
299         {
300             String JavaDoc msg = localStrings.getString( "admin.mbeans.ssmb.call_preparedownload_first" );
301             throw new MBeanException JavaDoc( new java.lang.IllegalStateException JavaDoc( msg ) );
302         }
303         // if it is a file of 0, return null bytes
304
ByteChunk byteChunk = null;
305         if (downloadInfo.downloadFile.length() == 0 ) {
306             byte[] bytes = new byte[ByteChunk.kChunkMinSize];
307             byteChunk = new ByteChunk(bytes,
308                              downloadInfo.downloadFile.getAbsolutePath(),
309                              true, true);
310             unlockAndReset();
311             return byteChunk;
312         }
313
314         if ((chunkIndex >= downloadInfo.numChunks) || (chunkIndex < 0))
315         {
316             String JavaDoc msg = localStrings.getString( "admin.mbeans.ssmb.invalid_chunk_index" );
317             unlockAndReset();
318             throw new MBeanException JavaDoc( new java.lang.IllegalStateException JavaDoc( msg ) );
319         }
320         RandomAccessFile JavaDoc raf = null;
321         try
322         {
323             raf = new RandomAccessFile JavaDoc(downloadInfo.downloadFile, "r");
324             byte[] bytes = new byte[ByteChunk.kChunkMaxSize];
325             raf.seek(downloadInfo.numBytesRead);
326             int actualBytesRead = raf.read(bytes, 0, ByteChunk.kChunkMaxSize);
327             /*
328             Debug.println("Read " + actualBytesRead + " from " +
329                           downloadInfo.numBytesRead);
330             */

331             if (actualBytesRead < bytes.length)
332             {
333                 byte[] newBytes = new byte[actualBytesRead];
334                 System.arraycopy(bytes, 0, newBytes, 0, newBytes.length);
335                 bytes = newBytes;
336             }
337             downloadInfo.numBytesRead += actualBytesRead;
338             boolean isFirstChunk = (chunkIndex == 0);
339             boolean isLastChunk =
340                 (chunkIndex == (downloadInfo.numChunks - 1));
341             sLogger.log(Level.FINEST, "chunkIndex = " + chunkIndex +
342                           " isFirstChunk = " + isFirstChunk +
343                           " isLastChunk = " + isLastChunk);
344             byteChunk = new ByteChunk(bytes,
345                              downloadInfo.downloadFile.getAbsolutePath(),
346                              isFirstChunk, isLastChunk);
347         }
348         catch (IOException JavaDoc ioe)
349         {
350             sLogger.log(Level.FINE, "mbean.download_failed", ioe);
351             unlockAndReset();
352             throw new MBeanException JavaDoc(ioe);
353         }
354         finally
355         {
356             if (raf != null)
357             {
358                 try { raf.close(); }
359                 catch (IOException JavaDoc ioe) {}
360             }
361             if ((byteChunk != null) && (byteChunk.isLast()))
362             {
363                 unlockAndReset();
364             }
365         }
366         return byteChunk;
367     }
368     
369     /**
370      * Downloads the file in chunks. This method supports multiple distributed
371      * clients.
372      *
373      * @param info download request information
374      *
375      * @return the byte chunk corresponding to the current chunk index
376      *
377      * @throws MBeanException when exceptions occur, the exception
378      * that caused will be in the exception chain.
379      */

380     public synchronized DownloadRequestInfo mcDownloadFile(
381             DownloadRequestInfo info) throws MBeanException JavaDoc
382     {
383         sLogger.log(Level.FINE, "mbean.begin_download");
384
385         // verifies the information for this download request
386
if (info == null)
387         {
388             String JavaDoc msg = localStrings.getString(
389                 "admin.mbeans.ssmb.call_preparedownload_first");
390             throw new MBeanException JavaDoc(new java.lang.IllegalStateException JavaDoc(msg));
391         }
392         else if (!info.isPrepared())
393         {
394             String JavaDoc msg = localStrings.getString(
395                 "admin.mbeans.ssmb.call_preparedownload_first");
396             throw new MBeanException JavaDoc(new java.lang.IllegalStateException JavaDoc(msg));
397         }
398
399         // download file
400
File JavaDoc targetFile = new File JavaDoc(info.getDownloadFilePath());
401
402         // if it is a file of 0, return null bytes
403
ByteChunk byteChunk = null;
404         if (targetFile.length() == 0)
405         {
406             byte[] bytes = new byte[ByteChunk.kChunkMinSize];
407             String JavaDoc fPath = info.getDownloadFilePath();
408             byteChunk = new ByteChunk(bytes, fPath, true, true, fPath, 0);
409             info.setChunk(byteChunk);
410
411             return info;
412         }
413
414         // verifies that chunk index is valid
415
if ( (info.getChunkIndex() >= info.getNumberOfChunks())
416                 || (info.getChunkIndex() < 0) )
417         {
418             String JavaDoc msg = localStrings.getString(
419                 "admin.mbeans.ssmb.invalid_chunk_index" );
420             throw new MBeanException JavaDoc(new java.lang.IllegalStateException JavaDoc(msg));
421         }
422
423         // reads the chunk into a byte chunk object
424
RandomAccessFile JavaDoc raf = null;
425         try
426         {
427             raf = new RandomAccessFile JavaDoc(targetFile, "r");
428             byte[] bytes = new byte[ByteChunk.kChunkMaxSize];
429             raf.seek(info.getNumberOfBytesSent());
430
431             int actualBytesRead = raf.read(bytes, 0, ByteChunk.kChunkMaxSize);
432             if (actualBytesRead < bytes.length)
433             {
434                 byte[] newBytes = new byte[actualBytesRead];
435                 System.arraycopy(bytes, 0, newBytes, 0, newBytes.length);
436                 bytes = newBytes;
437             }
438
439             // increments the counter
440
info.incrementNumberOfBytesSent(bytes.length);
441
442             String JavaDoc path = info.getDownloadFilePath();
443             byteChunk = new ByteChunk(bytes,
444                              path, info.isFirstChunk(), info.isLastChunk(),
445                              path, targetFile.length());
446         }
447         catch (IOException JavaDoc ioe)
448         {
449             sLogger.log(Level.FINE, "mbean.download_failed", ioe);
450             throw new MBeanException JavaDoc(ioe);
451         }
452         finally
453         {
454             if (raf != null)
455             {
456                 try { raf.close(); }
457                 catch (IOException JavaDoc ioe) {}
458             }
459         }
460         info.setChunk(byteChunk);
461
462         return info;
463     }
464     
465     // The following function releases the lock and reset the downloadinfo
466
// this clean up is needed in case of exceptions
467
private void unlockAndReset()
468     {
469         try
470         {
471             downloadInfo.reset();
472             lock.release();
473         }
474         catch (Exception JavaDoc e)
475         {
476             sLogger.log(Level.FINEST, "lock could not be released");
477         }
478     }
479     
480     /** Returns the location of the client stub jar that is generated by EJBC
481      * during deployment of the given application.
482      * @param appName application or module name by which an application
483      * or an EJB module has been deployed.
484      * @return Returns the absolute path to the client-stub-jar file.
485      * @throws MBeanException The wrapper exception for any exceptions. The getCause will return the causing
486      * exception.
487      */

488     public String JavaDoc getClientStubJarLocation(String JavaDoc appName)
489         throws MBeanException JavaDoc
490     {
491         String JavaDoc clientJarLocation = null;
492         
493         try
494         {
495             final com.sun.enterprise.server.ServerContext sc = com.sun.enterprise.server.ApplicationServer.getServerContext();
496             InstanceEnvironment iEnv = sc.getInstanceEnvironment();
497             ObjectName JavaDoc appsObjName = new ObjectName JavaDoc("com.sun.appserv:type=applications,category=config");
498             String JavaDoc appLocation = null;
499             ObjectName JavaDoc appObjName = null;
500             try {
501                 appObjName = (ObjectName JavaDoc)getMBeanServer().invoke(appsObjName, "getJ2eeApplicationByName", new Object JavaDoc[] {appName}, new String JavaDoc[] {"java.lang.String"});
502                 AppsManager appsManager = new AppsManager(iEnv);
503                 appLocation = appsManager.getGeneratedXMLLocation(appName);
504             } catch(Exception JavaDoc ee) {
505                 // no application by this name
506
}
507             if(appObjName == null) {
508                 try {
509                     appObjName = (ObjectName JavaDoc)getMBeanServer().invoke(appsObjName, "getEjbModuleByName", new Object JavaDoc[] {appName}, new String JavaDoc[] {"java.lang.String"});
510                     EjbModulesManager ejbManager = new EjbModulesManager(iEnv);
511                     appLocation = ejbManager.getGeneratedXMLLocation(appName);
512                 } catch (Exception JavaDoc ejbe) {
513                     // no ejb module by this name
514
}
515                 if(appObjName == null) {
516                     try {
517                         appObjName = (ObjectName JavaDoc)getMBeanServer().invoke(appsObjName, "getAppclientModuleByName", new Object JavaDoc[] {appName}, new String JavaDoc[] {"java.lang.String" });
518                         AppclientModulesManager appClientManager =
519                             new AppclientModulesManager(iEnv);
520                         appLocation =
521                             appClientManager.getGeneratedXMLLocation(appName);
522                     } catch(Exception JavaDoc ace) {
523                         // no appclient module by this name
524
}
525                 }
526                 // the app name matches none of the applicable modules
527
// throw an exception here
528
if(appObjName == null) {
529                     throw new IllegalArgumentException JavaDoc(localStrings.getString( "admin.mbeans.ssmb.invalid_appname", appName ));
530                 }
531             }
532  
533             // for upgrade scenario, we fall back to the original location
534
if (appLocation == null ||
535                 !FileUtils.safeIsDirectory(appLocation)) {
536                 appLocation = (String JavaDoc)getMBeanServer().getAttribute(appObjName,
537                     "location");
538             }
539             clientJarLocation = appLocation + java.io.File.separator +
540                                 DeploymentServiceUtils.getClientJarPath(appName);
541             
542             sLogger.log(Level.INFO, "mbean.cl_jar_loc", clientJarLocation);
543         }
544         catch (Exception JavaDoc e)
545         {
546             sLogger.log(Level.WARNING, e.toString(), e);
547             throw new MBeanException JavaDoc(e);
548         }
549         return clientJarLocation;
550     }
551     
552     protected MBeanServer JavaDoc getMBeanServer()
553     {
554         return com.sun.enterprise.admin.common.MBeanServerFactory.getMBeanServer();
555     }
556     
557     protected String JavaDoc getDomainName() {
558         return com.sun.enterprise.admin.server.core.AdminService.getAdminService().getAdminContext().getDomainName();
559     }
560     
561     
562     public Object JavaDoc getAttribute(String JavaDoc str) throws javax.management.AttributeNotFoundException JavaDoc, javax.management.MBeanException JavaDoc, javax.management.ReflectionException JavaDoc {
563         throw new AttributeNotFoundException JavaDoc(str);
564     }
565     
566     public javax.management.AttributeList JavaDoc getAttributes(String JavaDoc[] str) {
567         return new AttributeList JavaDoc();
568     }
569     
570     /** Even if a particular server's configuration is in server's configuration (domain.xml), the
571      * actual values that are taken by certain Java System Properties are always available in a server's runtime alone.
572      * For example, only running DAS knows what absolute location on the disk is, where DAS is installed, only
573      * running instance "server1" knows what absolute location on the disk is, where "server1"'s configuration
574      * is stored and so on and so forth.
575      * <P>
576      * This method is extremely useful in finding out the values of Java System Properties in the runtime of a process, from
577      * runtime of other processes.
578      * <P>
579      * It is recommended that remote callers use the "names" of the Java System Properties from ${link SystemPropertyConstants}
580      * class (rather than hardcoding), because for most of the properties, what changes is values, not names.
581      * @param name name of the Java System Property
582      * @retun the value of the given property in the context of host server that is usually (but not necessarily) remote
583      * to the caller.
584      */

585     public String JavaDoc getHostServerSystemPropertyValue(final String JavaDoc name) {
586         return ( System.getProperty(name) );
587     }
588     
589     public javax.management.MBeanInfo JavaDoc getMBeanInfo() {
590         MBeanConstructorInfo JavaDoc[] constructors = new MBeanConstructorInfo JavaDoc[ 1 ];
591         MBeanNotificationInfo JavaDoc[] notifications = null;
592         MBeanAttributeInfo JavaDoc[] attributes = null;
593         MBeanOperationInfo JavaDoc[] operations = new MBeanOperationInfo JavaDoc[ 4 ];
594         
595         try{
596             MBeanConstructorInfo JavaDoc cinfo = new MBeanConstructorInfo JavaDoc(
597             "Main constructor",
598             this.getClass().getConstructor() );
599             constructors[ 0 ] = cinfo;
600         }catch(Exception JavaDoc e){
601                 sLogger.log(Level.WARNING, e.getLocalizedMessage() );
602         }
603         
604         MBeanParameterInfo JavaDoc[] parameters = new MBeanParameterInfo JavaDoc[ 1 ];
605         parameters[ 0 ] = new MBeanParameterInfo JavaDoc( "byteChunk", ByteChunk.class.getName(),
606                                             "byte chunk" );
607         operations[ 0 ] = new MBeanOperationInfo JavaDoc( "uploadToServer", "upload file to admin server",
608                                             parameters, String JavaDoc.class.getName(), MBeanOperationInfo.ACTION );
609
610         MBeanParameterInfo JavaDoc[] parameters1 = new MBeanParameterInfo JavaDoc[ 1 ];
611         parameters1[ 0 ] = new MBeanParameterInfo JavaDoc( "fileName", String JavaDoc.class.getName(),
612                                             "file name" );
613         operations[ 1 ] = new MBeanOperationInfo JavaDoc( "prepareDownload", "prepare file download from admin server",
614                                             parameters1, Object JavaDoc.class.getName(), MBeanOperationInfo.ACTION );
615
616         MBeanParameterInfo JavaDoc[] parameters2 = new MBeanParameterInfo JavaDoc[ 1 ];
617         parameters2[ 0 ] = new MBeanParameterInfo JavaDoc( "chunkIndex", "java.lang.Integer",
618                                             "chunk index" );
619         operations[ 2 ] = new MBeanOperationInfo JavaDoc( "downloadFile", "download file from admin server",
620                                             parameters2, ByteChunk.class.getName(), MBeanOperationInfo.ACTION );
621
622         MBeanParameterInfo JavaDoc[] parameters3 = new MBeanParameterInfo JavaDoc[ 1 ];
623         parameters3[ 0 ] = new MBeanParameterInfo JavaDoc( "appName", String JavaDoc.class.getName(),
624                                             "application name" );
625         operations[ 3 ] = new MBeanOperationInfo JavaDoc( "getClientStubJarLocation", "get stub file location from admin server",
626                                             parameters3, String JavaDoc.class.getName(), MBeanOperationInfo.ACTION );
627
628         return new MBeanInfo JavaDoc( this.getClass().getName(),
629                                         "Manages System Services" , attributes, constructors, operations, notifications );
630     }
631     
632     public Object JavaDoc invoke(String JavaDoc str, Object JavaDoc[] args, String JavaDoc[] sig) throws javax.management.MBeanException JavaDoc, javax.management.ReflectionException JavaDoc {
633         try {
634             String JavaDoc methodName = str;
635             Class JavaDoc types[] = new Class JavaDoc[ sig.length ];
636             for( int i=0; i<types.length; i++ )
637                 types[i] = Class.forName(sig[i]);
638             
639             Method JavaDoc m = this.getClass().getMethod(methodName, types);
640             return m.invoke( this, args );
641         } catch ( Exception JavaDoc e ) {
642             sLogger.log(Level.WARNING,e.toString(),e);
643             throw new MBeanException JavaDoc( e );
644         }
645     }
646     
647     public void setAttribute(javax.management.Attribute JavaDoc attribute) throws javax.management.AttributeNotFoundException JavaDoc, javax.management.InvalidAttributeValueException JavaDoc, javax.management.MBeanException JavaDoc, javax.management.ReflectionException JavaDoc {
648         throw new AttributeNotFoundException JavaDoc();
649     }
650     
651     public javax.management.AttributeList JavaDoc setAttributes(javax.management.AttributeList JavaDoc attributeList) {
652         return new AttributeList JavaDoc();
653     }
654     
655     /** writes the bytes to the output stream got by lookup up the Map with the id as
656      * the key.
657      */

658     private void saveFile(String JavaDoc filePath, ByteChunk aChunk)
659     throws MBeanException JavaDoc {
660         OutputStream JavaDoc sOut = null;
661         String JavaDoc id = aChunk.getId();
662         try {
663             sOut = (OutputStream JavaDoc) mStreamTable.get(id);
664             byte[] bytes = aChunk.getBytes();
665             sOut.write(bytes);
666         }
667         catch(Exception JavaDoc e) {
668             sLogger.log(Level.WARNING,e.getLocalizedMessage(),e);
669             throw new MBeanException JavaDoc(e);
670         }
671         finally {
672             try {
673                 if (aChunk.isLast()) {
674                     sOut.close();
675                     mStreamTable.remove(id);
676                     if(aChunk.getTotalFileSize()>0) {
677                         if ( new File JavaDoc(filePath).length() != aChunk.getTotalFileSize() ) {
678                             sLogger.log(Level.WARNING, "mbean.upload_failed", filePath);
679                             String JavaDoc msg = localStrings.getString( "admin.mbeans.upload_failed", filePath );
680                             throw new MBeanException JavaDoc( new java.lang.RuntimeException JavaDoc (msg) );
681                         }
682                     } else {
683                         sLogger.log(Level.INFO, "mbean.filesize_notverified", filePath);
684                     }
685                     sLogger.log(Level.INFO, "mbean.upload_done", filePath);
686                 }
687             }
688             catch(Exception JavaDoc fe) {
689                 sLogger.log(Level.WARNING,fe.toString(),fe);
690                 throw new MBeanException JavaDoc(fe);
691             }
692         }
693     }
694     
695     /** creates the outputstream and puts it in the Map. */
696     private OutputStream JavaDoc createOutputStream(String JavaDoc filePath) throws MBeanException JavaDoc {
697         OutputStream JavaDoc fOut = null;
698         
699         try {
700             fOut = new FileOutputStream JavaDoc(filePath);
701         }
702         catch(Exception JavaDoc e) {
703             try {
704                 if (fOut != null) {
705                     fOut.close();
706                 }
707             }
708             catch (Exception JavaDoc ce) {
709                 sLogger.log(Level.WARNING, "mbean.upload_failed", filePath);
710             }
711             
712             throw new MBeanException JavaDoc(e);
713         }
714         return ( fOut );
715     }
716
717     private final class Lock
718     {
719         private boolean inUse;
720
721         private Lock()
722         {
723             inUse = false;
724         }
725
726         private synchronized void acquire()
727             throws InterruptedException JavaDoc, IllegalAccessException JavaDoc
728         {
729             while (inUse)
730             {
731                 wait();
732             }
733             inUse = true;
734         }
735
736         private synchronized void release() throws IllegalAccessException JavaDoc
737         {
738             inUse = false;
739             notify();
740         }
741
742         private synchronized void attempt(long milliseconds)
743             throws InterruptedException JavaDoc, IllegalAccessException JavaDoc
744         {
745             if (inUse)
746             {
747                 wait(milliseconds);
748                 if (inUse) //The lock is still in use. Give up.
749
{
750                     String JavaDoc msg = localStrings.getString( "admin.server.core.mbean.config.another_thread_holding_lock" );
751                     throw new IllegalAccessException JavaDoc( msg );
752                 }
753             }
754             inUse = true;
755         }
756     }
757
758     private static final class DownloadInfo
759     {
760         private File JavaDoc downloadFile;
761         private int numChunks;
762         private long numBytesRead;
763         private boolean isPrepared;
764
765         private DownloadInfo()
766         {
767             reset();
768         }
769
770         private synchronized void reset()
771         {
772             downloadFile = null;
773             numChunks = 0;
774             numBytesRead = 0;
775             isPrepared = false;
776         }
777     }
778
779     private Lock lock;
780     private DownloadInfo downloadInfo;
781     
782     
783 }
784
785
Popular Tags