KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > deployment > impl > ServerFileDistributor


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.deployment.impl;
21
22 import org.openide.filesystems.FileObject;
23 import org.openide.filesystems.FileLock;
24 import org.openide.filesystems.FileUtil;
25 import java.io.*;
26 import java.util.*;
27 import org.netbeans.modules.j2ee.deployment.plugins.api.*;
28 import org.netbeans.modules.j2ee.deployment.common.api.*;
29 import org.netbeans.modules.j2ee.deployment.devmodules.api.*;
30 import javax.enterprise.deploy.model.*;
31 import javax.enterprise.deploy.spi.*;
32 import javax.enterprise.deploy.shared.*;
33 import org.netbeans.modules.j2ee.deployment.config.ConfigSupportImpl;
34 import org.netbeans.modules.j2ee.deployment.config.DeployableObjectImpl;
35 import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
36 import org.openide.util.NbBundle;
37 import org.openide.ErrorManager;
38 import org.netbeans.modules.j2ee.deployment.execution.DeploymentTarget;
39 import org.netbeans.modules.j2ee.deployment.execution.DeploymentConfigurationProvider;
40
41 /**
42  *
43  * @author nn136682
44  */

45 public class ServerFileDistributor extends ServerProgress {
46     ServerInstance instance;
47     DeploymentTarget dtarget;
48     IncrementalDeployment incremental;
49 // DeploymentPlanSplitter splitter;
50

51     // valued by RootedEntry's
52
Iterator rootModuleFiles;
53     // keyed by child module URL, valued by collection of RootedEntry's
54
Map childModuleFiles;
55     // keyed by child module URL, valued by collection of J2eeModule's
56
Map childModuleMap;
57     
58     /** Creates a new instance of ServerFileDistributor */
59     public ServerFileDistributor(ServerInstance instance, DeploymentTarget dtarget){
60         super(instance);
61         this.instance = instance;
62         this.dtarget = dtarget;
63         incremental = instance.getIncrementalDeployment ();
64 // splitter = instance.getServer().getDeploymentPlanSplitter();
65

66         //init contents
67
try {
68             J2eeModule source = dtarget.getModule();
69             rootModuleFiles = source.getArchiveContents();
70             if (source instanceof J2eeModuleContainer) {
71                 childModuleFiles = new HashMap();
72                 childModuleMap = new HashMap();
73                 J2eeModule[] childModules = ((J2eeModuleContainer)source).getModules(null);
74                 for (int i=0; i<childModules.length; i++) {
75                     Iterator contents = childModules[i].getArchiveContents();
76                     if (contents != null)
77                         childModuleFiles.put(childModules[i].getUrl(), contents);
78                     childModuleMap.put(childModules[i].getUrl(), childModules[i]);
79                 }
80             }
81         } catch (Exception JavaDoc e) {
82             throw new RuntimeException JavaDoc(e);
83         }
84     }
85     
86     static Map j2eeTypeMap = null;
87     static List getDescriptorPath(J2eeModule module) {
88         if (j2eeTypeMap == null) {
89             j2eeTypeMap = new HashMap();
90             j2eeTypeMap.put(J2eeModule.EJB, Arrays.asList(new String JavaDoc[]{J2eeModule.EJBJAR_XML, J2eeModule.EJBSERVICES_XML}));
91             j2eeTypeMap.put(J2eeModule.WAR, Arrays.asList(new String JavaDoc[]{J2eeModule.WEB_XML, J2eeModule.WEBSERVICES_XML}));
92             j2eeTypeMap.put(J2eeModule.CLIENT, Arrays.asList(new String JavaDoc[]{J2eeModule.CLIENT_XML}));
93             j2eeTypeMap.put(J2eeModule.CONN, Arrays.asList(new String JavaDoc[]{J2eeModule.CONNECTOR_XML}));
94             j2eeTypeMap.put(J2eeModule.EAR, Arrays.asList(new String JavaDoc[]{J2eeModule.APP_XML}));
95         }
96         return (List) j2eeTypeMap.get(module.getModuleType());
97     }
98     
99     private J2eeModule getJ2eeModule(TargetModuleID target) {
100         if (target.getParentTargetModuleID() == null)
101             return dtarget.getModule();
102         else {
103             String JavaDoc moduleUrl = incremental.getModuleUrl(target);
104             return (J2eeModule) childModuleMap.get(moduleUrl);
105         }
106     }
107     
108     private AppChanges createModuleChangeDescriptor(TargetModuleID target) {
109         J2eeModule module = getJ2eeModule(target);
110         List descriptorRelativePaths = getDescriptorPath(module);
111         
112         ModuleType moduleType = (ModuleType) module.getModuleType ();
113         List serverDescriptorRelativePaths = Arrays.asList(instance.getServer().getDeploymentPlanFiles(moduleType));
114         return new AppChanges(descriptorRelativePaths, serverDescriptorRelativePaths, (ModuleType) dtarget.getModule ().getModuleType ());
115     }
116     
117     public AppChangeDescriptor distribute(TargetModule targetModule, ModuleChangeReporter mcr) throws IOException {
118         long lastDeployTime = targetModule.getTimestamp();
119         TargetModuleID[] childModules = targetModule.getChildTargetModuleID();
120         AppChanges changes = new AppChanges();
121         File destDir = null;
122         
123             //PENDING: whether module need to be stop first
124
for (int i=0; childModules != null && i<childModules.length; i++) {
125                 String JavaDoc url = incremental.getModuleUrl(targetModule.delegate());
126                 destDir = incremental.getDirectoryForModule(childModules[i]);
127                 Iterator source = (Iterator) childModuleFiles.get(url);
128                 if (destDir == null)
129                     changes.record(_distribute(childModules[i], lastDeployTime));
130                 else
131                     changes.record(_distribute(source, destDir, targetModule.delegate(), url, lastDeployTime));
132             }
133             
134             //PENDING: whether ordering of copying matters
135
destDir = incremental.getDirectoryForModule(targetModule.delegate());
136             if (destDir == null)
137                 changes.record(_distribute(targetModule.delegate(), lastDeployTime));
138             else
139                 changes.record(_distribute(rootModuleFiles, destDir, targetModule.delegate(), null, lastDeployTime));
140             
141             if (mcr != null)
142                 changes.record(mcr, lastDeployTime);
143             
144             setStatusDistributeCompleted(NbBundle.getMessage(
145                 ServerFileDistributor.class, "MSG_DoneIncrementalDeploy", targetModule.getModuleID()));
146             
147         return changes;
148     }
149     
150     public AppChanges _test_distribute(Iterator source, File destDir, TargetModuleID target, long lastDeployTime) throws IOException {
151         return _distribute(source, destDir, target, null, lastDeployTime);
152     }
153     
154     private AppChanges _distribute(TargetModuleID target, long lastDeployTime) throws IOException {
155         AppChanges mc = createModuleChangeDescriptor(target);
156         setStatusDistributeRunning(NbBundle.getMessage(
157         ServerFileDistributor.class, "MSG_RunningIncrementalDeploy", target));
158         
159         Iterator content = getJ2eeModule(target).getArchiveContents ();
160         
161         Date lastDeployed = new Date(lastDeployTime);
162         while (content.hasNext ()) {
163             J2eeModule.RootedEntry re = (J2eeModule.RootedEntry) content.next ();
164             FileObject file = re.getFileObject ();
165             if (file.isFolder())
166                 continue;
167             //jar file are created externally and timestamp may not be refreshed
168
file.refresh ();
169             if (file.lastModified().after(lastDeployed)) {
170                 String JavaDoc relativePath = re.getRelativePath ();
171                 mc.record(relativePath);
172             }
173         }
174
175         return mc;
176     }
177     
178     private AppChanges _distribute(Iterator source, File destDir, TargetModuleID target, String JavaDoc moduleUrl, long lastDeployTime) throws IOException {
179         AppChanges mc = createModuleChangeDescriptor(target);
180         if (source == null) {
181             ErrorManager.getDefault().log(ErrorManager.ERROR, "There is no contents for "+target); //NOI18N
182
throw new IOException(NbBundle.getMessage(ServerFileDistributor.class, "MSG_NoContents", target));
183         }
184         setStatusDistributeRunning(NbBundle.getMessage(
185         ServerFileDistributor.class, "MSG_RunningIncrementalDeploy", target));
186         FileLock lock = null;
187         try {
188             //get relative-path-key map from FDL
189
File dir = incremental.getDirectoryForModule(target);
190             destDir.mkdirs();
191             File parent = destDir.getParentFile();
192             FileObject destRoot = FileUtil.toFileObject(destDir);
193             
194             // create target FOs map keyed by relative paths
195
java.util.Enumeration JavaDoc destFiles = destRoot.getChildren(true);
196             Map destMap = new HashMap();
197             int rootPathLen = destRoot.getPath().length();
198             for (; destFiles.hasMoreElements(); ) {
199                 FileObject destFO = (FileObject) destFiles.nextElement();
200                 destMap.put(destFO.getPath().substring(rootPathLen + 1), destFO);
201             }
202             
203             // iterate through source changes
204
for (Iterator j=source; j.hasNext();) {
205                 J2eeModule.RootedEntry entry = (J2eeModule.RootedEntry) j.next();
206                 String JavaDoc relativePath = entry.getRelativePath();
207                 FileObject sourceFO = entry.getFileObject();
208                 FileObject targetFO = (FileObject) destMap.get(relativePath);
209                 FileObject destFolder;
210                 if (sourceFO.isFolder()) {
211                     destMap.remove(relativePath);
212                     //System.out.println("entering folder:"+relativePath);
213
continue;
214                 }
215                 if (targetFO == null) {
216                     destFolder = findOrCreateParentFolder(destRoot, relativePath);
217                 } else {
218                     // remove from map to form of to-remove-target-list
219
destMap.remove(relativePath);
220                     
221                     //check timestamp
222
if (! sourceFO.lastModified().after(targetFO.lastModified())) {
223                         //System.out.println("Skipping file "+sourceFO.getPath());
224
continue;
225                     }
226                     destFolder = targetFO.getParent();
227                     
228                     //System.out.println("Prepare for copy by deleting old target file: "+targetFO.getPath());
229
targetFO.delete();
230                 }
231                 mc.record(relativePath);
232                 //PENDING: update progress object or should we not for performance?
233
//System.out.println("Copying "+sourceFO.getPath()+" to "+destFolder.getPath());
234

235                 FileUtil.copyFile(sourceFO, destFolder, sourceFO.getName());
236             }
237             
238             ModuleType moduleType = (ModuleType) dtarget.getModule ().getModuleType ();
239             String JavaDoc[] rPaths = instance.getServer().getDeploymentPlanFiles(moduleType);
240             /*for (int n=0; n < rPaths.length; n++) {
241                 FileObject removedFO = (FileObject)destMap.remove(rPaths[n]);
242                 System.out.println("Sparing plan file: "+rPaths[n]+" removedFO="+removedFO);
243             }
244              
245             // Cleanup destination
246             for (Iterator k=destMap.values().iterator(); k.hasNext();) {
247                 FileObject remainingFO = (FileObject) k.next();
248                 lock = remainingFO.lock();
249                 System.out.println("Deleting remaining file "+remainingFO.getPath());
250                 remainingFO.delete(lock);
251                 System.out.println("File "+remainingFO.getPath()+" deleted");
252                 lock.releaseLock();
253                 lock = null;
254             }*/

255             
256             // copying serverconfiguration files if changed
257
File configFile = dtarget.getConfigurationFile();
258             if (rPaths == null || rPaths.length == 0)
259                 return mc;
260             
261             File[] paths = new File[rPaths.length];
262             for (int n=0; n<rPaths.length; n++) {
263                 paths[n] = new File(FileUtil.toFile(destRoot), rPaths[n]);
264                 if (! paths[n].exists() || paths[n].lastModified() < configFile.lastModified())
265                     mc.record(rPaths[n]);
266             }
267             
268             return mc;
269             
270         } catch (Exception JavaDoc e) {
271             String JavaDoc msg = NbBundle.getMessage(ServerFileDistributor.class, "MSG_IncrementalDeployFailed", e);
272             setStatusDistributeFailed(msg);
273             throw new RuntimeException JavaDoc(e);
274         } finally {
275             if (lock != null) {
276                 try { lock.releaseLock(); } catch(Exception JavaDoc ex) {}
277             }
278         }
279     }
280     
281     /**
282      * Find or create parent folder of a file given its root and its relative path.
283      * The target file does not need to exist.
284      *
285      * @param dest FileObject for the root of the target file
286      * @param relativePaht relative path of the target file
287      * @return the FileObject for the parent folder target file.
288      */

289     public static FileObject findOrCreateParentFolder(FileObject dest, String JavaDoc relativePath) throws IOException {
290         File parentRelativePath = (new File(relativePath)).getParentFile();
291         if (parentRelativePath == null)
292             return dest;
293         
294         FileObject folder = dest.getFileSystem().findResource(parentRelativePath.getPath());
295         if (folder == null)
296             folder = FileUtil.createFolder(dest, parentRelativePath.getPath());
297         
298         //System.out.println("Created folder "+folder.getPath());
299
return folder;
300     }
301     
302     //ServerProgress methods
303
private void setStatusDistributeRunning(String JavaDoc message) {
304         notify(createRunningProgressEvent(CommandType.DISTRIBUTE, message));
305     }
306     private void setStatusDistributeFailed(String JavaDoc message) {
307         notify(createFailedProgressEvent(CommandType.DISTRIBUTE, message));
308     }
309     private void setStatusDistributeCompleted(String JavaDoc message) {
310         notify(createCompletedProgressEvent(CommandType.DISTRIBUTE, message));
311     }
312     
313     
314     static class AppChanges implements AppChangeDescriptor {
315         
316         boolean descriptorChanged = false;
317         boolean serverDescriptorChanged = false;
318         boolean classesChanged = false;
319         boolean manifestChanged = false;
320         boolean ejbsChanged = false;
321         List changedEjbs = Collections.EMPTY_LIST;
322         ModuleType moduleType = null;
323         List changedFiles = new ArrayList();
324         List descriptorRelativePaths;
325         List serverDescriptorRelativePaths;
326         AppChanges() {
327         }
328         AppChanges(List descriptorRelativePaths, List serverDescriptorRelativePaths, ModuleType moduleType) {
329             this.descriptorRelativePaths = descriptorRelativePaths;
330             this.serverDescriptorRelativePaths = serverDescriptorRelativePaths;
331             this.moduleType = moduleType;
332         }
333         private void record(AppChanges changes) {
334             if (!descriptorChanged) descriptorChanged = changes.descriptorChanged();
335             if (!serverDescriptorChanged) serverDescriptorChanged = changes.serverDescriptorChanged();
336             if (!classesChanged) classesChanged = changes.classesChanged();
337             if (!manifestChanged) manifestChanged = changes.manifestChanged();
338             if (!ejbsChanged) ejbsChanged = changes.ejbsChanged();
339             List ejbs = Arrays.asList(changes.getChangedEjbs());
340             if (ejbs.size() > 0)
341                 changedEjbs.addAll(ejbs);
342             changedFiles.addAll(changes.changedFiles);
343         }
344         
345         private void record(String JavaDoc relativePath) {
346             if (! classesChanged) {
347                 boolean classes = !moduleType.equals (ModuleType.WAR) || relativePath.startsWith ("WEB-INF/classes/"); //NOI18N
348
boolean importantLib = !moduleType.equals (ModuleType.WAR) || relativePath.startsWith ("WEB-INF/lib/"); //NOI18N
349
boolean libs = importantLib && (relativePath.endsWith(".jar") || relativePath.endsWith(".zip")); //NOI18N
350
if (classes || libs) {
351                     classesChanged = true;
352                     return;
353                 }
354             }
355             if (! descriptorChanged && (
356                 ((descriptorRelativePaths != null && descriptorRelativePaths.contains(relativePath)) ||
357                  (relativePath.startsWith ("WEB-INF") && (relativePath.endsWith (".tld") || relativePath.endsWith (".xml") || relativePath.endsWith (".dtd")))))) {
358                 descriptorChanged = true;
359                 return;
360             }
361             if (! serverDescriptorChanged && serverDescriptorRelativePaths != null && serverDescriptorRelativePaths.contains(relativePath)) {
362                 serverDescriptorChanged = true;
363                 return;
364             }
365             changedFiles.add(new File(relativePath));
366         }
367         
368         private void record(ModuleChangeReporter mcr, long since) {
369             EjbChangeDescriptor ecd = mcr.getEjbChanges(since);
370             ejbsChanged = ecd.ejbsChanged();
371             String JavaDoc[] ejbs = ecd.getChangedEjbs();
372             if (ejbs != null && ejbs.length > 0)
373                 changedEjbs.addAll(Arrays.asList(ejbs));
374             if (! manifestChanged)
375                 manifestChanged = mcr.isManifestChanged(since);
376         }
377         public boolean classesChanged() { return classesChanged; }
378         public boolean descriptorChanged() { return descriptorChanged; }
379         public boolean manifestChanged() { return manifestChanged; }
380         public boolean serverDescriptorChanged() { return serverDescriptorChanged; }
381         
382         public boolean ejbsChanged() { return ejbsChanged; }
383         public String JavaDoc[] getChangedEjbs() {
384             return (String JavaDoc[]) changedEjbs.toArray(new String JavaDoc[]{});
385         }
386         public File[] getChangedFiles() {
387             return (File[]) changedFiles.toArray(new File[changedFiles.size()]);
388         }
389     }
390 }
391
Popular Tags