KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > upgrade > Copy


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.upgrade;
21
22 import java.io.*;
23 import java.util.*;
24 import java.util.regex.Matcher JavaDoc;
25 import java.util.regex.Pattern JavaDoc;
26 import org.openide.util.*;
27
28 import org.openide.filesystems.*;
29
30 /** Does copy of objects on filesystems.
31  *
32  * @author Jaroslav Tulach
33  */

34 final class Copy extends Object JavaDoc {
35
36
37     /** Does a selective copy of one source tree to another.
38      * @param source file object to copy from
39      * @param target file object to copy to
40      * @param thoseToCopy set on which contains (relativeNameOfAFileToCopy)
41      * is being called to find out whether to copy or not
42      * @throws IOException if coping fails
43      */

44     public static void copyDeep (FileObject source, FileObject target, Set thoseToCopy)
45     throws IOException {
46         copyDeep (source, target, thoseToCopy, null);
47     }
48     
49     private static void copyDeep (
50         FileObject source, FileObject target, Set thoseToCopy, String JavaDoc prefix
51     ) throws IOException {
52         FileObject src = prefix == null ? source : FileUtil.createFolder (source, prefix);
53         
54         FileObject[] arr = src.getChildren();
55         for (int i = 0; i < arr.length; i++) {
56             String JavaDoc fullname;
57             if (prefix == null) {
58                 fullname = arr[i].getNameExt ();
59             } else {
60                 fullname = prefix + "/" + arr[i].getNameExt ();
61             }
62             if (arr[i].isData ()) {
63                 if (!thoseToCopy.contains (fullname)) {
64                     continue;
65                 }
66             }
67
68             
69             if (arr[i].isFolder()) {
70                 copyDeep (source, target, thoseToCopy, fullname);
71                 if (thoseToCopy.contains (fullname) && arr[i].getAttributes ().hasMoreElements ()) {
72                     FileObject tg = FileUtil.createFolder (target, fullname);
73                     FileUtil.copyAttributes (arr[i], tg);
74                 }
75             } else {
76                 FileObject folder = prefix == null ? target : FileUtil.createFolder (target, prefix);
77                 FileObject tg = folder.getFileObject (arr[i].getNameExt ());
78                 try {
79                     if (tg == null) {
80                         // copy the file otherwise keep old content
81
tg = FileUtil.copyFile (arr[i], folder, arr[i].getName(), arr[i].getExt ());
82                     }
83                 } catch (IOException ex) {
84                     if (arr[i].getNameExt().endsWith("_hidden")) {
85                         continue;
86                     }
87                     throw ex;
88                 }
89                 FileUtil.copyAttributes (arr[i], tg);
90             }
91         }
92         
93         
94     }
95     
96     public static void appendSelectedLines(File sourceFile, File targetFolder, String JavaDoc[] regexForSelection)
97     throws IOException {
98         if (!sourceFile.exists()) {
99             return;
100         }
101         Pattern JavaDoc[] linePattern = new Pattern JavaDoc[regexForSelection.length];
102         for (int i = 0; i < linePattern.length; i++) {
103             linePattern[i] = Pattern.compile(regexForSelection[i]);
104         }
105         ByteArrayOutputStream bos = new ByteArrayOutputStream();
106         File targetFile = new File(targetFolder,sourceFile.getName());
107         if (!targetFolder.exists()) {
108             targetFolder.mkdirs();
109         }
110         assert targetFolder.exists();
111         
112         if (!targetFile.exists()) {
113             targetFile.createNewFile();
114         } else {
115             //read original content into ByteArrayOutputStream
116
FileInputStream targetIS = new FileInputStream(targetFile);
117             try {
118                 FileUtil.copy(targetIS, bos);
119             } finally {
120                 targetIS.close();
121             }
122         }
123         assert targetFile.exists();
124
125         
126         //append lines into ByteArrayOutputStream
127
String JavaDoc line = null;
128         BufferedReader sourceReader = new BufferedReader(new FileReader(sourceFile));
129         try {
130             while ((line = sourceReader.readLine()) != null) {
131                 if (linePattern != null) {
132                     for (int i = 0; i < linePattern.length; i++) {
133                         Matcher JavaDoc m = linePattern[i].matcher(line);
134                         if (m.matches()) {
135                             bos.write(line.getBytes());
136                             bos.write('\n');
137                             break;
138                         }
139                     }
140                 } else {
141                     bos.write(line.getBytes());
142                     bos.write('\n');
143                 }
144             }
145         } finally {
146             sourceReader.close();
147         }
148
149         ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
150         FileOutputStream targetOS = new FileOutputStream(targetFile);
151         try {
152             FileUtil.copy(bin, targetOS);
153         } finally {
154             bin.close();
155             targetOS.close();
156         }
157     }
158     
159     
160     
161
162     /** Updates the IDE.
163      * @param sourceDir original instalation of the IDE
164      * @param targetSystem target system to copy files to
165      * @param backupSystem filesystem to do backupSystemFo to (or null)
166      * @exception IOException if the copying fails
167      *
168     protected final void upgradeIde (String ver, File src, File trg) throws Exception {
169         
170         
171         int version = getIdeVersion (ver);
172         if (version < 0 || version >= versions.length) {
173             message (getString ("MSG_BAD_IDE"));
174             for (int i = 0 ; i < versions.length ; i++ ) {
175                 message (versions[i]);
176             }
177             throw new Exception ("Invalid IDE version"); //NOI18N
178         }
179
180         message (getString ("MSG_UPDATE_FROM", versions[version]));
181
182         FileSystem srcFS = null;
183         FileSystem trgFS = null;
184         FileSystem tmpFS = null;
185         Object filter [] = null;
186
187         if (-1 != ver.indexOf (DIRTYPE_INST)) {
188             File srcFile = new File (src, "system"); //NOI18N
189             File trgFile = new File (trg, "system"); //NOI18N
190             srcFS = createFileSystem (srcFile);
191             trgFS = createFileSystem (trgFile);
192
193             if (srcFS == null) {
194                 message (getString ("MSG_directory_not_exist", srcFile.getAbsolutePath ())); //NOI18N
195                 throw new Exception ("Directory doesn't exist - " + srcFile.getAbsolutePath ()); //NOI18N
196             }
197
198             if (trgFS == null) {
199                 message (getString ("MSG_directory_not_exist", trgFile.getAbsolutePath ()));
200                 throw new Exception ("Directory doesn't exist - " + trgFile.getAbsolutePath ()); //NOI18N
201             }
202
203             File tmpRoot = new File (trg, "system_backup"); //NOI18N
204             if (!tmpRoot.exists ()) {
205 // message (getString ("MSG_BackupDir_exists", tmpRoot.getAbsolutePath ())); //NOI18N
206 // throw new Exception ("Backup directory already exists - " + tmpRoot.getAbsolutePath ()); //NOI18N
207 // } else {
208                 tmpRoot.mkdirs ();
209             }
210             tmpFS = createFileSystem (tmpRoot);
211
212             filter = originalFiles (nonCpFiles[version]);
213         } else {
214             srcFS = createFileSystem (src); //NOI18N
215             trgFS = createFileSystem (trg); //NOI18N
216
217             if (srcFS == null) {
218                 message (getString ("MSG_directory_not_exist", src.getAbsolutePath ())); //NOI18N
219                 throw new Exception ("Directory doesn't exist - " + src.getAbsolutePath ()); //NOI18N
220             }
221
222             if (trgFS == null) {
223                 message (getString ("MSG_directory_not_exist", trg.getAbsolutePath ())); //NOI18N
224                 throw new Exception ("Directory doesn't exist - " + trg.getAbsolutePath ()); //NOI18N
225             }
226
227             File tmpRoot = new File (trg.getParentFile (), "userdir_backup"); //NOI18N
228             if (!tmpRoot.exists ()) {
229 // message (getString ("MSG_BackupDir_exists", tmpRoot.getAbsolutePath ())); //NOI18N
230 // throw new Exception ("Backup directory already exists - " + tmpRoot.getAbsolutePath ()); //NOI18N
231 // } else {
232                 tmpRoot.mkdirs ();
233             }
234             tmpFS = createFileSystem (tmpRoot);
235
236             filter = originalFiles (userdirNonCpFiles);
237         }
238
239         if (tmpFS != null) {
240             // clean up temporary filesystem
241             FileObject ch [] = tmpFS.getRoot ().getChildren ();
242             for (int i = 0; i < ch.length; i++) {
243                 deleteAll (ch[i]);
244             }
245             // make a backup copy
246             copyAttributes(trgFS.getRoot (), tmpFS.getRoot ());
247             recursiveCopy(trgFS.getRoot (), tmpFS.getRoot ());
248         }
249         
250         try {
251             update (srcFS, trgFS, getLastModified (src), filter);
252         }
253         catch (Exception e) {
254             if (tmpFS != null) {
255                 message (getString ("MSG_recovery_started")); //NOI18N
256                 deleteAll (trgFS.getRoot ());
257                 copyAttributes (tmpFS.getRoot (), trgFS.getRoot ());
258                 recursiveCopy (tmpFS.getRoot (), trgFS.getRoot ());
259                 message (getString ("MSG_recovery_finished")); //NOI18N
260             }
261             throw e;
262         }
263     }
264     
265     private FileSystem createFileSystem (File root) {
266         LocalFileSystem lfs = null;
267
268         if (root.exists () && root.isDirectory ()) {
269             try {
270                 lfs = new LocalFileSystem ();
271                 lfs.setRootDirectory (root);
272             }
273             catch (Exception e) {
274                 lfs = null;
275             }
276         }
277   
278         return lfs == null ? null : new AttrslessLocalFileSystem (lfs);
279     }
280
281     private void update(
282         FileSystem src, FileSystem trg, long sourceBaseTime, Object[] filter
283     ) throws IOException {
284
285         items = 0;
286         maxItems = 0;
287
288         copyAttributes (src.getRoot (),trg.getRoot ());
289         recursiveCopyWithFilter (
290             src.getRoot (),
291             trg.getRoot (),
292             filter,
293             sourceBaseTime
294         );
295     }
296     
297     /** copies recursively directory, skips files existing in target location
298      * @param source source directory
299      * @param dest destination directory
300      */

301     private void recursiveCopy (FileObject sourceFolder, FileObject destFolder) throws IOException {
302         FileObject childrens [] = sourceFolder.getChildren();
303         for (int i = 0 ; i < childrens.length ; i++ ) {
304             final FileObject subSourceFo = childrens[i];
305             FileObject subTargetFo = null;
306             
307             if (subSourceFo.isFolder()) {
308                 subTargetFo = destFolder.getFileObject(subSourceFo.getName());
309                 if (subTargetFo == null) {
310                     subTargetFo = destFolder.createFolder(subSourceFo.getName());
311                     
312                 }
313                 copyAttributes(subSourceFo,subTargetFo);
314                 recursiveCopy(subSourceFo,subTargetFo);
315             } else {
316                 subTargetFo = destFolder.getFileObject(subSourceFo.getNameExt());
317                 if (subTargetFo == null) {
318                      if ( Utilities.getOperatingSystem () == Utilities.OS_VMS
319                         && subSourceFo.getNameExt ().equalsIgnoreCase ( "_nbattrs.") )
320                         subTargetFo = FileUtil.copyFile(subSourceFo, destFolder, subSourceFo.getNameExt(), subSourceFo.getExt());
321                      else
322                         subTargetFo = FileUtil.copyFile(subSourceFo, destFolder, subSourceFo.getName(), subSourceFo.getExt());
323                 }
324                 copyAttributes(subSourceFo,subTargetFo);
325             }
326         }
327     }
328
329     private void message (String JavaDoc s) {
330         
331     }
332     private void progress (int x, int y) {
333         
334     }
335     private int maxItems;
336     private int items;
337     private int timeDev;
338     
339     /** Copies recursively dircectory. Files are copied when when basicTime + timeDev < time of file.
340      * @param source source directory
341      * @param #dest destination dirctory
342      */

343     private void recursiveCopyWithFilter (
344         FileObject source, FileObject dest, Object JavaDoc[] filter, long basicTime
345     ) throws IOException {
346         FileObject childrens [] = source.getChildren();
347         if (source.isFolder() == false ) {
348             message (getString("MSG_IS_NOT_FOLDER", source.getName()));
349         }
350
351         // adjust max number of items
352
maxItems += childrens.length;
353
354         for (int i = 0 ; i < childrens.length ; i++ ) {
355             FileObject subSourceFo = childrens[i];
356
357             // report progress
358
items++;
359             progress(items, maxItems);
360
361             if (!canCopy (subSourceFo, filter, basicTime))
362                 continue;
363             
364             FileObject subTargetFo = null;
365             if (subSourceFo.isFolder ()) {
366                 subTargetFo = dest.getFileObject (subSourceFo.getNameExt ());
367                 if (subTargetFo == null) {
368                     subTargetFo = dest.createFolder (subSourceFo.getNameExt ());
369                     
370                 }
371                 copyAttributes (subSourceFo, subTargetFo);
372                 recursiveCopyWithFilter (subSourceFo, subTargetFo, filter, basicTime);
373             } else {
374                 subTargetFo = dest.getFileObject (subSourceFo.getName (), subSourceFo.getExt ());
375                
376                 if (subTargetFo != null) {
377                     FileLock lock = subTargetFo.lock ();
378                     subTargetFo.delete (lock);
379                     lock.releaseLock ();
380                 }
381                 
382                 if ( Utilities.getOperatingSystem () == Utilities.OS_VMS
383                     && subSourceFo.getNameExt ().equalsIgnoreCase ( "_nbattrs.") )
384                     subTargetFo = copyFile (subSourceFo, dest, subSourceFo.getNameExt ());
385                 else
386                     subTargetFo = copyFile (subSourceFo, dest, subSourceFo.getName ());
387                 copyAttributes (subSourceFo, subTargetFo);
388             }
389         }
390     }
391
392     private FileObject copyFile (FileObject src, FileObject trg, String JavaDoc newName) throws IOException {
393         return FileUtil.copyFile (src, trg, newName);
394     }
395         
396     private static void copyAttributes (FileObject source, FileObject dest) throws IOException {
397         Enumeration attrKeys = source.getAttributes();
398         while (attrKeys.hasMoreElements()) {
399             String JavaDoc key = (String JavaDoc) attrKeys.nextElement();
400             Object JavaDoc value = source.getAttribute(key);
401             if (value != null) {
402                 dest.setAttribute(key, value);
403             }
404         }
405     }
406     /** test if file can be copied
407      */

408     private boolean canCopy (FileObject fo, Object JavaDoc[] filter, long basicTime) throws IOException {
409         String JavaDoc nonCopiedFiles [] = (String JavaDoc []) filter [0];
410         String JavaDoc wildcards [] = (String JavaDoc []) filter [1];
411         String JavaDoc name = fo.getPath();
412         
413         if (fo.isFolder ()) {
414             return Arrays.binarySearch (nonCopiedFiles, name + "/*") < 0; //NOI18N
415
}
416
417         for (int i = 0; i < wildcards.length; i++) {
418             if (name.endsWith (wildcards [i])) {
419                 return false;
420             }
421         }
422
423         long time = fo.lastModified().getTime();
424         
425         boolean canCopy = Arrays.binarySearch (nonCopiedFiles, name) < 0 &&
426                basicTime + timeDev <= time;
427         if (!canCopy) {
428             return false;
429         }
430         
431         // #31623 - the fastjavac settings should not be imported.
432
// In NB3.5 the fastjavac was separated into its own module.
433
// Its old settings (bounded to java module) must not be imported.
434
// For fastjavac settings created by NB3.5 this will work, because they
435
// will be bound to new "org.netbeans.modules.java.fastjavac" module.
436
if (fo.getExt().equals("settings")) { //NOI18N
437
boolean tag1 = false;
438             boolean tag2 = false;
439             BufferedReader reader = null;
440             try {
441                 reader = new BufferedReader(new InputStreamReader(fo.getInputStream()));
442                 String JavaDoc line;
443                 while (null != (line = reader.readLine())) {
444                     if (line.indexOf("<module name=") != -1) { //NOI18N
445
if (line.indexOf("<module name=\"org.netbeans.modules.java/1\"") != -1) { //NOI18N
446
tag1 = true; // it is java module setting
447
} else {
448                             break; // some other setting, ignore this file
449
}
450                     }
451                     if (line.indexOf("<serialdata class=") != -1) { //NOI18N
452
if (line.indexOf("<serialdata class=\"org.netbeans.modules.java.FastJavacCompilerType\">") != -1) { //NOI18N
453
tag2 = true; // it is fastjavac setting
454
if (tag1) {
455                                 break;
456                             }
457                         } else {
458                             break; // some other setting, ignore this file
459
}
460                     }
461                 }
462             } catch (IOException ex) {
463                 // ignore this problem.
464
// in worst case the fastjavac settings will be copied.
465
} finally {
466                 if (reader != null) {
467                     reader.close();
468                 }
469             }
470             if (tag1 && tag2) {
471                 return false; // ignore this file. it is fastjavac settings
472
}
473         }
474         
475         return true;
476     }
477     // ************************* version retrieving code ********************
478

479     
480     /** We support import just from release 3.6
481      * @param dir user dir to check for version
482      * @return either null or name of the version
483      */

484     public static String JavaDoc getIdeVersion (File dir) {
485         String JavaDoc version = null;
486         String JavaDoc dirType = null;
487         String JavaDoc branding = null;
488         
489         if (new File (dir, "system").exists ()) {
490             return "3.6";
491         }
492         return null;
493     }
494
495     // ************** strings from bundle ***************
496

497     protected static String JavaDoc getString (String JavaDoc key) {
498         return NbBundle.getMessage (Copy.class, key);
499     }
500
501     protected static String JavaDoc getString (String JavaDoc key,String JavaDoc param) {
502         return NbBundle.getMessage(Copy.class,key,param);
503     }
504     
505     private static class AttrslessLocalFileSystem extends AbstractFileSystem implements AbstractFileSystem.Attr {
506         public AttrslessLocalFileSystem (LocalFileSystem fs) {
507             super ();
508             this.change = new LocalFileSystem.Impl (fs);
509             this.info = (AbstractFileSystem.Info) this.change;
510             this.list = (AbstractFileSystem.List) this.change;
511             this.attr = this;
512         }
513         public boolean isReadOnly () {
514             return false;
515         }
516         public String JavaDoc getDisplayName () {
517             return getClass ().toString (); // this will never be shown to user
518
}
519
520         // ***** no-op implementation of AbstractFileSystem.Attr *****
521

522         public void deleteAttributes (String JavaDoc name) {
523         }
524         public Enumeration<String JavaDoc> attributes (String JavaDoc name) {
525             return org.openide.util.Enumerations.empty ();
526         }
527         public void renameAttributes (String JavaDoc oldName, String JavaDoc newName) {
528         }
529         public void writeAttribute (String JavaDoc name, String JavaDoc attrName, Object JavaDoc value) throws IOException {
530         }
531         public Object JavaDoc readAttribute (String JavaDoc name, String JavaDoc attrName) {
532             return null;
533         }
534     }
535 }
536
Popular Tags