KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > common > JMXFileTransfer


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.admin.common;
25
26
27 import java.io.File JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.RandomAccessFile JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Random JavaDoc;
35 import javax.management.InstanceNotFoundException JavaDoc;
36 import javax.management.ObjectName JavaDoc;
37 import javax.management.remote.JMXConnector JavaDoc;
38 import javax.management.remote.JMXConnectorFactory JavaDoc;
39 import javax.management.remote.JMXServiceURL JavaDoc;
40 import javax.management.MBeanServerConnection JavaDoc;
41 import javax.management.MBeanException JavaDoc;
42 import javax.management.ReflectionException JavaDoc;
43 import javax.management.MalformedObjectNameException JavaDoc;
44 import com.sun.enterprise.admin.jmx.remote.DefaultConfiguration;
45
46 import com.sun.enterprise.admin.util.ArgChecker;
47 import com.sun.enterprise.admin.util.StringValidator;
48 import com.sun.enterprise.admin.common.constant.DeploymentConstants;
49 import com.sun.enterprise.admin.common.exception.*;
50
51 import com.sun.enterprise.admin.common.constant.AdminConstants;
52 import com.sun.enterprise.util.SystemPropertyConstants;
53 import com.sun.enterprise.util.i18n.StringManager;
54
55 /** Utility class to transfer a given file from and to the server in chunks using jmx
56  * with s1ashttp protocol.
57  */

58 public class JMXFileTransfer implements FileTransfer {
59     
60     /** Provider package string for s1ashttp protocol */
61     public static final String JavaDoc S1ASHTTP_PROVIDER_PACKAGES = "com.sun.enterprise.admin.jmx.remote.protocol";
62     private static final String JavaDoc UPLOAD_OPERATION = "uploadToServer";
63     private static final String JavaDoc GET_STUB_FILE_LOCATION = "getClientStubJarLocation";
64     private static final String JavaDoc GET_WSDL_FILE_LOCATION = "getWsdlFileLocation";
65     private static final String JavaDoc PREPARE_DOWNLOAD = "prepareDownload";
66     private static final String JavaDoc MCPREPARE_DOWNLOAD = "mcPrepareDownload";
67     private static final String JavaDoc DOWNLOAD_FILE = "downloadFile";
68     private static final String JavaDoc MCDOWNLOAD_FILE = "mcDownloadFile";
69     
70     private JMXServiceURL JavaDoc url ;
71     private String JavaDoc user;
72     private String JavaDoc password;
73     private MBeanServerConnection JavaDoc mbsc;
74     private String JavaDoc targetServer = SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME;
75     private static final StringManager _localStrMgr =
76             StringManager.getManager(JMXFileTransfer.class);
77
78     /** uploads the given file to the server running at the url with
79      * authentication. Assumes jmx-remote with s1ashttp protocol.
80      * @param url the jmx url to the server in the format <CODE>service:jmx:s1ashttp://host:port</CODE>
81      * @param user user name to authenticate with the server
82      * @param password the password for the user
83      * @throws IOException for connectionrelated exceptions
84      */

85     public JMXFileTransfer(JMXServiceURL JavaDoc url, String JavaDoc user, String JavaDoc password) throws IOException JavaDoc {
86         this.url = url;
87         this.user = user;
88         this.password = password;
89         setConnection();
90     }
91        
92     /** uploads the given file to the server running at the url with
93      * authentication. Assumes jmx-remote with s1ashttp protocol.
94      * @param url the jmx url to the server in the format <CODE>service:jmx:s1ashttp://host:port</CODE>
95      * @param user user name to authenticate with the server
96      * @param password the password for the user
97      * @param doConnect true-- connect now. false-- connect when setConnection is called explicitly
98      * @throws IOException for connectionrelated exceptions
99      */

100     public JMXFileTransfer(JMXServiceURL JavaDoc url, String JavaDoc user, String JavaDoc password, boolean doConnect) throws IOException JavaDoc {
101         this.url = url;
102         this.user = user;
103         this.password = password;
104         if (doConnect == true)
105             setConnection();
106     }
107     
108     /** uploads the given file to the server running at the host:port with
109      * authentication. Assumes jmx-remote with s1ashttp protocol.
110      * @param mbsc the connection to the mbean server
111      * @throws IOException for connection related exceptions
112      */

113     public JMXFileTransfer(MBeanServerConnection JavaDoc mbsc) throws IOException JavaDoc{
114         this.mbsc = mbsc;
115     }
116     
117     /**
118      * This method returns whether JMXFileTransfer a valid connection
119      * to system services MBean
120      *
121      * @return boolean true- if there is connection, false, if not
122      */

123     public MBeanServerConnection JavaDoc getMBeanServerConnection () {
124         return mbsc;
125     }
126     
127     /**
128      * This method set the MBean Server connection
129      *
130      * @param mbsc The new MBean server connection value
131      */

132      public void setMBeanServerConnection(MBeanServerConnection JavaDoc mbsc) {
133         this.mbsc = mbsc;
134      }
135      
136     /**
137      * This method can be used to set the MBean server connection explicitly,
138      * instead of setting connection from constructor.
139      *
140      * This method is written to be used by SynchornizationClient.
141      *
142      */

143     public void setConnection() throws IOException JavaDoc {
144         final Map JavaDoc env = new HashMap JavaDoc();
145         env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, S1ASHTTP_PROVIDER_PACKAGES);
146         env.put(DefaultConfiguration.ADMIN_USER_ENV_PROPERTY_NAME, user);
147         env.put(DefaultConfiguration.ADMIN_PASSWORD_ENV_PROPERTY_NAME, password);
148         env.put(DefaultConfiguration.HTTP_AUTH_PROPERTY_NAME, DefaultConfiguration.DEFAULT_HTTP_AUTH_SCHEME);
149         env.put(JMXConnector.CREDENTIALS, new String JavaDoc[] {user, password});
150         JMXConnector JavaDoc conn = JMXConnectorFactory.connect(url, env);
151         mbsc = conn.getMBeanServerConnection();
152     }
153     
154     /** Sets the target server to the server where the transfer should occur from/to.
155      * May not be null.
156      * @param s String representing the name of server instance in a given domain
157      * that is the target for transfer (to/from). May not be null.
158      */

159     public void setTargetServer(final String JavaDoc s) {
160         this.targetServer = s;
161     }
162     // Begin EE: 4946914 - cluster deployment support
163
public String JavaDoc uploadFile(String JavaDoc filePath) throws IOException JavaDoc {
164
165         return uploadFile(filePath, null);
166     }
167     // End EE: 4946914 - cluster deployment support
168

169     public String JavaDoc uploadFile (String JavaDoc filePath, String JavaDoc targetDir)
170             throws IOException JavaDoc {
171             
172         final File JavaDoc f = new File JavaDoc(filePath);
173         if(!f.exists() || !f.canRead())
174             throw new FileNotFoundException JavaDoc(filePath);
175        
176        return uploadFile(f, targetDir);
177     }
178     
179     public String JavaDoc uploadFile(File JavaDoc f, String JavaDoc targetDir )
180             throws IOException JavaDoc {
181
182
183         if( !f.isFile() || (mbsc==null))
184             throw new IllegalArgumentException JavaDoc();
185         
186         String JavaDoc remoteLocation = null;
187
188         ObjectName JavaDoc mbeanName = ObjectNames.getPerInstanceSystemServicesObjectName(targetServer);
189         String JavaDoc operationName = UPLOAD_OPERATION;
190
191         final RandomAccessFile JavaDoc file = new RandomAccessFile JavaDoc(f, "r");
192         byte[] bytes = new byte[ByteChunk.kChunkMaxSize];
193         int bytesRead = 0;
194         long totalBytesRead = 0;
195         boolean isFirstChunk = true;
196         boolean isLastChunk = false;
197         final long fileSize = file.length();
198         Random JavaDoc random = new Random JavaDoc();
199         final String JavaDoc id = String.valueOf(random.nextInt(9999999));
200
201         try {
202             int index = 0;
203             while ((bytesRead = file.read(bytes)) != -1)
204             {
205                 totalBytesRead += bytesRead;
206                 if (bytesRead < bytes.length)
207                 {
208                     byte[] realBytes = new byte[bytesRead];
209                     for (int i = 0; i < bytesRead; i++)
210                     {
211                         realBytes[i] = bytes[i];
212                     }
213                     bytes = realBytes;
214                 }
215                 if (totalBytesRead == fileSize)
216                 {
217                     isLastChunk = true;
218                 }
219                 ByteChunk aChunk = new ByteChunk(bytes, f.getName(),
220                                                  isFirstChunk, isLastChunk, id, fileSize);
221                 // Begin EE: 4946914 - cluster deployment support
222
aChunk.setTargetDir(targetDir);
223                 // End EE: 4946914 - cluster deployment support
224

225                 ParamInfo paramInfo = new ParamInfo(operationName, aChunk);
226                 try {
227                     remoteLocation = (String JavaDoc)mbsc.invoke(mbeanName,
228                                             paramInfo.getOperationName(),
229                                             paramInfo.getParams(),
230                                             paramInfo.getSignature());
231                 }catch(Exception JavaDoc e){
232                     e.printStackTrace();
233                     throw (IOException JavaDoc)(new IOException JavaDoc(e.getLocalizedMessage()).initCause(e));
234                 }
235                 index++;
236                 isFirstChunk = false;
237             }
238         }
239         catch(Exception JavaDoc e) {
240             e.printStackTrace();
241             throw new IOException JavaDoc(e.getClass().getName() + ":" + e.getMessage());
242         }
243         finally {
244             try {
245                 file.close();
246             }
247             catch(Exception JavaDoc e){}
248        }
249  
250         return remoteLocation;
251     }
252     
253     
254     public String JavaDoc downloadClientStubs(String JavaDoc appName, String JavaDoc destDir)
255         throws IOException JavaDoc
256     {
257
258         if (mbsc == null )
259             throw new IllegalArgumentException JavaDoc("MBean Server connection not set");
260      
261         ArgChecker.checkValid(appName, "appName", //noi18n
262
StringValidator.getInstance());
263         String JavaDoc msg="";
264         File JavaDoc f = new File JavaDoc(destDir);
265         if (!f.exists())
266         {
267             //String msg = localizedStrMgr.getString( "admin.servermodel.controller.desstdir_does_not_exist", destDir );
268
throw new FileNotFoundException JavaDoc( msg );
269         }
270         else if (!f.isDirectory())
271         {
272             //String msg = localizedStrMgr.getString( "admin.servermodel.controller.desstdir_is_not_directory", destDir );
273
throw new IllegalArgumentException JavaDoc( msg );
274         }
275         else if (!f.canWrite())
276         {
277             //String msg = localizedStrMgr.getString( "admin.servermodel.controller.cannot_write_to_destdir", destDir );
278
throw new IllegalArgumentException JavaDoc( msg );
279         }
280
281         Object JavaDoc[] params = new Object JavaDoc[] {appName};
282         String JavaDoc[] signature = new String JavaDoc[] {"java.lang.String"};
283         ObjectName JavaDoc mbeanName = ObjectNames.getPerInstanceSystemServicesObjectName(targetServer);
284         try {
285             String JavaDoc filePath = (String JavaDoc) mbsc.invoke(mbeanName, GET_STUB_FILE_LOCATION, params, signature);
286             //String fileName = appName + AdminConstants.CLIENT_JAR;
287
downloadFile(filePath, destDir);
288             String JavaDoc exportedFileLocation = new File JavaDoc(destDir, new File JavaDoc(filePath).getName()).getAbsolutePath();
289             return exportedFileLocation;
290         }catch(Exception JavaDoc e) {
291             throw (IOException JavaDoc)(new IOException JavaDoc(e.getLocalizedMessage()).initCause(e));
292         }
293     }
294     
295      /**
296      * Exports a wsdl file that is created by the server during deployment time
297      *
298      * @param appName the name of the application of EJB/WAR module that is
299      * deployed to the server
300      * @param moduleName if application this is the
301      * module uri within the application, null otherwise
302      * @param wsdlFileName the requested wsdl uri
303      * @param destDir the absolute path to the directory where the wsdl file
304      * should be copied
305      * @throws IOException
306      */

307     public String JavaDoc exportWsdlFile(String JavaDoc appName,
308                                  String JavaDoc moduleName,
309                                  String JavaDoc wsdlFileUri,
310                                  String JavaDoc destDir)
311         throws IOException JavaDoc
312     {
313         if (mbsc == null )
314             throw new IllegalArgumentException JavaDoc("MBean Server connection not set");
315  
316         ArgChecker.checkValid(appName, "appName", //noi18n
317
StringValidator.getInstance());
318         File JavaDoc f = new File JavaDoc(destDir);
319         String JavaDoc msg="";
320         String JavaDoc exportedFileLocation;
321         f.mkdirs();
322         if (!f.exists()) {
323             throw new FileNotFoundException JavaDoc( f.toString() );
324         }
325         else if (!f.isDirectory())
326         {
327             throw new IllegalArgumentException JavaDoc( f.toString() );
328         }
329         else if (!f.canWrite())
330         {
331             throw new IllegalArgumentException JavaDoc( f.toString() );
332         }
333         String JavaDoc filePath = null;
334         
335         
336         Object JavaDoc[] params = new Object JavaDoc[] {appName, moduleName, wsdlFileUri};
337         String JavaDoc[] signature = new String JavaDoc[] {"java.lang.String", "java.lang.String","java.lang.String"};
338         ObjectName JavaDoc mbeanName = ObjectNames.getPerInstanceSystemServicesObjectName(targetServer);
339         try{
340             filePath = (String JavaDoc) mbsc.invoke(mbeanName, GET_WSDL_FILE_LOCATION, params, signature);
341             if (wsdlFileUri.lastIndexOf('/')!=-1) {
342                 String JavaDoc wsdlDir ;
343                 if (wsdlFileUri.startsWith("META-INF/wsdl")) {
344                     wsdlDir = "META-INF/wsdl/";
345                 } else {
346                     wsdlDir = "WEB-INF/wsdl/";
347                 }
348                 File JavaDoc absolutePath;
349                 if (wsdlDir.length()<wsdlFileUri.lastIndexOf('/')) {
350                     String JavaDoc intermediateDirs = wsdlFileUri.substring(wsdlDir.length(), wsdlFileUri.lastIndexOf('/'));
351                     absolutePath = new File JavaDoc(destDir, intermediateDirs);
352                 } else {
353                 absolutePath = new File JavaDoc(destDir);
354                 }
355                 absolutePath.mkdirs();
356                 destDir = absolutePath.getAbsolutePath();
357                 wsdlFileUri = wsdlFileUri.substring(wsdlFileUri.lastIndexOf('/')+1);
358             }
359             downloadFile(filePath, destDir, wsdlFileUri);
360             exportedFileLocation = new File JavaDoc(destDir, wsdlFileUri).getAbsolutePath();
361         }catch(Exception JavaDoc e) {
362             throw (IOException JavaDoc)(new IOException JavaDoc(e.getLocalizedMessage()).initCause(e));
363         }
364         
365         return exportedFileLocation;
366     }
367     
368     public String JavaDoc downloadFile(String JavaDoc filePath, String JavaDoc destinationDirPath)
369         throws IOException JavaDoc
370     {
371         return downloadFile(filePath, destinationDirPath, null) ;
372     }
373     
374     public String JavaDoc downloadFile(String JavaDoc filePath, String JavaDoc destinationDirPath, String JavaDoc appName)
375         throws IOException JavaDoc
376     {
377         File JavaDoc destDir = new File JavaDoc(destinationDirPath);
378         File JavaDoc destPath = null;
379         
380         if(appName == null)
381             destPath = new File JavaDoc(destinationDirPath, new File JavaDoc(filePath).getName());
382         else
383             destPath = new File JavaDoc(destinationDirPath,appName);
384
385         return downloadFile(filePath, destPath);
386     }
387     
388     public String JavaDoc downloadFile(String JavaDoc filePath,File JavaDoc destPath )
389         throws IOException JavaDoc
390     {
391         if (mbsc == null )
392             throw new IllegalArgumentException JavaDoc("MBean Server connection not set");
393  
394          
395         String JavaDoc msg="";
396         final File JavaDoc destDir = destPath.getParentFile();
397         if (!destDir.exists())
398         {
399             throw new FileNotFoundException JavaDoc(destDir.getName());
400         }
401         FileOutputStream JavaDoc fos = null;
402         try
403         {
404             ObjectName JavaDoc mbeanName = ObjectNames.getPerInstanceSystemServicesObjectName(targetServer);
405             mbsc.invoke(mbeanName, PREPARE_DOWNLOAD,
406                               new Object JavaDoc[] {filePath},
407                               new String JavaDoc[] {"java.lang.String"});
408             fos = new FileOutputStream JavaDoc(destPath);
409             boolean lastChunk = false;
410             int chunkIndex = 0;
411             int curSize = 0;
412             long totalFileSize = 0;
413             while (!lastChunk)
414             {
415                 Object JavaDoc[] params = new Object JavaDoc[] {new Integer JavaDoc(chunkIndex)};
416                 String JavaDoc[] signature = new String JavaDoc[] {"java.lang.Integer"};
417                 ByteChunk chunk = (ByteChunk)mbsc.invoke(mbeanName,
418                                         DOWNLOAD_FILE,
419                                         params,
420                                         signature);
421                 ++chunkIndex;
422                 lastChunk = chunk.isLast();
423                 byte[] bytes = chunk.getBytes();
424                 fos.write(bytes, 0, bytes.length);
425                 curSize =+ bytes.length;
426                 totalFileSize = chunk.getTotalFileSize();
427             }
428
429             if ( curSize < totalFileSize)
430                 throw new IOException JavaDoc("Checksum error, download incomplete, total file size is " + totalFileSize + " only gotton " + curSize + " bytes.");
431         } catch (Exception JavaDoc e) {
432             throw (IOException JavaDoc)(new IOException JavaDoc(e.getLocalizedMessage()).initCause(e));
433         }
434         finally
435         {
436             if (fos != null)
437             {
438                 try { fos.close(); }
439                 catch (Exception JavaDoc e) {}
440             }
441
442         }
443         return destPath.getPath();
444     }
445  
446     public synchronized String JavaDoc mcDownloadFile(String JavaDoc filePath, File JavaDoc destPath)
447         throws IOException JavaDoc
448     {
449         // verifies that mbean server connection is set
450
if (mbsc == null )
451         {
452             String JavaDoc msg = _localStrMgr.getString("admin.common.nombsc");
453             throw new IllegalArgumentException JavaDoc(msg);
454         }
455          
456         // verifies that the parent dir exists
457
final File JavaDoc destDir = destPath.getParentFile();
458         if (!destDir.exists())
459         {
460             throw new FileNotFoundException JavaDoc(destDir.getName());
461         }
462
463         FileOutputStream JavaDoc fos = null;
464         try
465         {
466             ObjectName JavaDoc mbeanName =
467               ObjectNames.getPerInstanceSystemServicesObjectName(targetServer);
468
469             DownloadRequestInfo info = (DownloadRequestInfo)
470                     mbsc.invoke(mbeanName, MCPREPARE_DOWNLOAD,
471                               new Object JavaDoc[] {filePath},
472                               new String JavaDoc[] {"java.lang.String"});
473
474             fos = new FileOutputStream JavaDoc(destPath);
475             boolean lastChunk = false;
476             int chunkIndex = 0;
477             long curSize = 0;
478             long totalFileSize = info.getTotalFileSize();
479
480             while (!lastChunk)
481             {
482                 Object JavaDoc[] params = new Object JavaDoc[] {info};
483                 String JavaDoc[] signature = new String JavaDoc[] {
484                     "com.sun.enterprise.admin.common.DownloadRequestInfo"};
485
486                 info = (DownloadRequestInfo) mbsc.invoke(mbeanName,
487                                     MCDOWNLOAD_FILE, params, signature);
488
489                 if (chunkIndex != info.getChunkIndex()) {
490                     String JavaDoc msg = _localStrMgr.getString("admin.common.chunkidx",
491                                     Integer.toString(chunkIndex),
492                                     Integer.toString(info.getChunkIndex()));
493                     throw new IOException JavaDoc(msg);
494                 }
495
496                 ByteChunk chunk = info.getChunk();
497
498                 // sets the chunk index for next iteration
499
++chunkIndex;
500                 info.setChunkIndex(chunkIndex);
501
502                 lastChunk = chunk.isLast();
503
504                 byte[] bytes = chunk.getBytes();
505                 fos.write(bytes, 0, bytes.length);
506
507                 // increment the current size
508
curSize = (long) (curSize + bytes.length);
509
510                 // total size of this download
511
long tFileSize = chunk.getTotalFileSize();
512                 if (tFileSize != totalFileSize) {
513                     String JavaDoc msg = _localStrMgr.getString("admin.common.totalfs",
514                                     Long.toString(totalFileSize),
515                                     Long.toString(tFileSize));
516                     throw new IOException JavaDoc(msg);
517                 }
518
519                 // verifies current number of received bytes
520
if (curSize != info.getNumberOfBytesSent())
521                 {
522                     String JavaDoc msg = _localStrMgr.getString("admin.common.curfs",
523                                     Long.toString(curSize),
524                                     Long.toString(info.getNumberOfBytesSent()));
525                     throw new IOException JavaDoc(msg);
526                 }
527             }
528
529             // verifies total number of received bytes
530
if ( curSize < totalFileSize)
531             {
532                 String JavaDoc msg=_localStrMgr.getString("admin.common.checksumerror",
533                                 Long.toString(totalFileSize),
534                                 Long.toString(curSize));
535                 throw new IOException JavaDoc(msg);
536             }
537
538         }
539         catch (Exception JavaDoc e)
540         {
541             throw (IOException JavaDoc)(new IOException JavaDoc(e.getLocalizedMessage())
542                                 .initCause(e));
543         }
544         finally
545         {
546             if (fos != null)
547             {
548                 try { fos.close(); }
549                 catch (Exception JavaDoc e) {}
550             }
551
552         }
553
554         return destPath.getPath();
555     }
556 }
557
Popular Tags