KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > project > CreatedModifiedFilesFactory


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.apisupport.project;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.InputStreamReader JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.io.OutputStreamWriter JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.io.Reader JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Arrays JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.Set JavaDoc;
39 import java.util.SortedSet JavaDoc;
40 import java.util.TreeSet JavaDoc;
41 import org.netbeans.api.project.Project;
42 import org.netbeans.api.project.ProjectManager;
43 import org.netbeans.modules.apisupport.project.layers.LayerUtils;
44 import org.netbeans.modules.apisupport.project.spi.NbModuleProvider;
45 import org.netbeans.spi.project.support.ant.EditableProperties;
46 import org.netbeans.spi.project.support.ant.PropertyUtils;
47 import org.openide.ErrorManager;
48 import org.openide.cookies.SaveCookie;
49 import org.openide.filesystems.FileLock;
50 import org.openide.filesystems.FileObject;
51 import org.openide.filesystems.FileSystem;
52 import org.openide.filesystems.FileUtil;
53 import org.openide.loaders.DataObject;
54 import org.openide.loaders.DataObjectNotFoundException;
55 import org.openide.modules.SpecificationVersion;
56
57 /**
58  * See javadoc in {@link CreatedModifiedFiles} for what this class and its
59  * methods is supposed to do.
60  */

61 public final class CreatedModifiedFilesFactory {
62     
63     static CreatedModifiedFiles.Operation addLoaderSection(
64             Project project, String JavaDoc dataLoaderClass, String JavaDoc installBefore) {
65         return new AddLoaderSection(project, dataLoaderClass, installBefore);
66     }
67     
68     static CreatedModifiedFiles.Operation addLookupRegistration(
69             Project project, String JavaDoc interfaceClass, String JavaDoc implClass, boolean inTests) {
70         return new AddLookupRegistration(project, interfaceClass, implClass, inTests);
71     }
72     
73     static CreatedModifiedFiles.Operation addModuleDependency(Project project,
74             String JavaDoc codeNameBase, String JavaDoc releaseVersion, SpecificationVersion version, boolean useInCompiler) {
75         return new AddModuleDependency(project, codeNameBase, releaseVersion, version, useInCompiler);
76     }
77     
78     static CreatedModifiedFiles.Operation bundleKey(Project project,
79             String JavaDoc key, String JavaDoc value, String JavaDoc bundlePath) {
80         return new BundleKey(project, key, value, bundlePath);
81     }
82     
83     static CreatedModifiedFiles.Operation bundleKeyDefaultBundle(
84             Project project, String JavaDoc key, String JavaDoc value) {
85         return new BundleKey(project, key, value);
86     }
87     
88     static CreatedModifiedFiles.Operation createFile(Project project,
89             String JavaDoc path, URL JavaDoc content) {
90         return new CreateFile(project, path, content);
91     }
92     
93     static CreatedModifiedFiles.Operation createFileWithSubstitutions(Project project,
94             String JavaDoc path, URL JavaDoc content, Map JavaDoc<String JavaDoc,String JavaDoc> tokens) {
95         return new CreateFile(project, path, content, tokens);
96     }
97     
98     static CreatedModifiedFiles.Operation layerModifications(Project project, CreatedModifiedFiles.LayerOperation op, Set JavaDoc<String JavaDoc> externalFiles, CreatedModifiedFiles cmf) {
99         return new LayerModifications(project, op, externalFiles, cmf);
100     }
101     
102     static CreatedModifiedFiles.Operation createLayerEntry(CreatedModifiedFiles cmf, Project project,
103             String JavaDoc layerPath, URL JavaDoc content,
104             Map JavaDoc<String JavaDoc,String JavaDoc> substitutionTokens, String JavaDoc localizedDisplayName, Map JavaDoc attrs) {
105         return new CreateLayerEntry(cmf, project, layerPath, content,
106                 substitutionTokens, localizedDisplayName, attrs);
107     }
108     
109     static CreatedModifiedFiles.Operation manifestModification(Project project, String JavaDoc section,
110             Map JavaDoc<String JavaDoc,String JavaDoc> attributes) {
111         CreatedModifiedFilesFactory.ModifyManifest retval =
112                 new CreatedModifiedFilesFactory.ModifyManifest(project);
113         for (Iterator JavaDoc it = attributes.entrySet().iterator(); it.hasNext();) {
114             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
115             String JavaDoc name = (String JavaDoc) entry.getKey();
116             String JavaDoc value = (String JavaDoc) entry.getValue();
117             retval.setAttribute(name, value, section);
118         }
119         return retval;
120     }
121     
122     static CreatedModifiedFiles.Operation propertiesModification(Project project,
123             String JavaDoc propertyPath, Map JavaDoc<String JavaDoc,String JavaDoc> properties) {
124         CreatedModifiedFilesFactory.ModifyProperties retval =
125                 new CreatedModifiedFilesFactory.ModifyProperties(project, propertyPath);
126         for (Iterator JavaDoc it = properties.entrySet().iterator(); it.hasNext();) {
127             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
128             String JavaDoc name = (String JavaDoc) entry.getKey();
129             String JavaDoc value = (String JavaDoc) entry.getValue();
130             retval.setProperty(name, value);
131         }
132         return retval;
133     }
134     
135     
136     public static abstract class OperationBase implements CreatedModifiedFiles.Operation {
137         
138         private Project project;
139         private SortedSet JavaDoc<String JavaDoc> createdPaths;
140         private SortedSet JavaDoc<String JavaDoc> modifiedPaths;
141         private SortedSet JavaDoc<String JavaDoc> invalidPaths;
142         
143         protected OperationBase(Project project) {
144             this.project = project;
145         }
146         
147         protected Project getProject() {
148             return project;
149         }
150         
151         protected NbModuleProvider getModuleInfo() {
152             return getProject().getLookup().lookup(NbModuleProvider.class);
153         }
154         
155         public String JavaDoc[] getModifiedPaths() {
156             String JavaDoc[] s = new String JavaDoc[getModifiedPathsSet().size()];
157             return (String JavaDoc[]) getModifiedPathsSet().toArray(s);
158         }
159         
160         public String JavaDoc[] getCreatedPaths() {
161             String JavaDoc[] s = new String JavaDoc[getCreatedPathsSet().size()];
162             return (String JavaDoc[]) getCreatedPathsSet().toArray(s);
163         }
164         
165         public String JavaDoc[] getInvalidPaths() {
166             String JavaDoc[] s = new String JavaDoc[getInvalidPathsSet().size()];
167             return (String JavaDoc[]) getInvalidPathsSet().toArray(s);
168             
169         }
170         
171         protected void addCreatedOrModifiedPath(String JavaDoc relPath, boolean allowFileModification) {
172             // XXX this is probably wrong, since it might be created by an earlier op:
173
if (getProject().getProjectDirectory().getFileObject(relPath) == null) {
174                 getCreatedPathsSet().add(relPath);
175             } else {
176                 if (allowFileModification) {
177                     getModifiedPathsSet().add(relPath);
178                 } else {
179                     getInvalidPathsSet().add(relPath);
180                 }
181             }
182         }
183         
184         protected void addPaths(CreatedModifiedFiles.Operation o) {
185             getCreatedPathsSet().addAll(Arrays.asList(o.getCreatedPaths()));
186             getModifiedPathsSet().addAll(Arrays.asList(o.getModifiedPaths()));
187             getInvalidPathsSet().addAll(Arrays.asList(o.getInvalidPaths()));
188         }
189         
190         protected SortedSet JavaDoc<String JavaDoc> getCreatedPathsSet() {
191             if (createdPaths == null) {
192                 createdPaths = new TreeSet JavaDoc();
193             }
194             return createdPaths;
195         }
196         
197         protected SortedSet JavaDoc<String JavaDoc> getInvalidPathsSet() {
198             if (invalidPaths == null) {
199                 invalidPaths = new TreeSet JavaDoc();
200             }
201             return invalidPaths;
202         }
203         
204         protected SortedSet JavaDoc<String JavaDoc> getModifiedPathsSet() {
205             if (modifiedPaths == null) {
206                 modifiedPaths = new TreeSet JavaDoc();
207             }
208             return modifiedPaths;
209         }
210         
211         protected boolean addCreatedFileObject(FileObject fo) {
212             return getCreatedPathsSet().add(getProjectPath(fo));
213         }
214         
215         protected boolean addModifiedFileObject(FileObject fo) {
216             return getModifiedPathsSet().add(getProjectPath(fo));
217         }
218         
219         /**
220          * Doesn't check given arguments. Be sure they are valid as supposed by
221          * {@link PropertyUtils#relativizeFile(File, File)} method.
222          */

223         private String JavaDoc getProjectPath(FileObject file) {
224             return PropertyUtils.relativizeFile(
225                     FileUtil.toFile(getProject().getProjectDirectory()),
226                     FileUtil.normalizeFile(FileUtil.toFile(file)));
227         }
228         
229     }
230     
231     private static final class CreateFile extends OperationBase {
232         
233         private String JavaDoc path;
234         private URL JavaDoc content;
235         private Map JavaDoc<String JavaDoc,String JavaDoc> tokens;
236         
237         public CreateFile(Project project, String JavaDoc path, URL JavaDoc content) {
238             this(project, path, content, null);
239         }
240         
241         public CreateFile(Project project, String JavaDoc path, URL JavaDoc content, Map JavaDoc<String JavaDoc,String JavaDoc> tokens) {
242             super(project);
243             this.path = path;
244             this.content = content;
245             this.tokens = tokens;
246             addCreatedOrModifiedPath(path, false);
247         }
248         
249         public void run() throws IOException JavaDoc {
250             FileObject targetFO = FileUtil.createData(getProject().getProjectDirectory(), path);
251             FileLock lock = targetFO.lock();
252             try {
253                 if (tokens == null) {
254                     copyByteAfterByte(content, lock, targetFO);
255                 } else {
256                     copyAndSubstituteTokens(content, lock, targetFO, tokens);
257                 }
258             } finally {
259                 lock.releaseLock();
260             }
261         }
262         
263     }
264     
265     private static void copyByteAfterByte(URL JavaDoc content, FileLock lock, FileObject targetFO) throws IOException JavaDoc {
266         OutputStream JavaDoc os = targetFO.getOutputStream(lock);
267         InputStream JavaDoc is = content.openStream();
268         try {
269             FileUtil.copy(is, os);
270         } finally {
271             is.close();
272             os.close();
273         }
274     }
275     
276     private static void copyAndSubstituteTokens(URL JavaDoc content, FileLock lock, FileObject targetFO, Map JavaDoc<String JavaDoc,String JavaDoc> tokens) throws IOException JavaDoc {
277         // #64023: at least XML files must always use UTF-8; but user probably expects *.java to use platform default?
278
boolean useUTF8 = targetFO.hasExt("xml"); // NOI18N
279
OutputStream JavaDoc os = targetFO.getOutputStream(lock);
280         try {
281             PrintWriter JavaDoc pw;
282             if (useUTF8) {
283                 pw = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(os, "UTF-8")); // NOI18N
284
} else {
285                 pw = new PrintWriter JavaDoc(os);
286             }
287             try {
288                 InputStream JavaDoc is = content.openStream();
289                 try {
290                     Reader JavaDoc r;
291                     if (useUTF8) {
292                         r = new InputStreamReader JavaDoc(is, "UTF-8"); // NOI18N
293
} else {
294                         r = new InputStreamReader JavaDoc(is);
295                     }
296                     BufferedReader JavaDoc br = new BufferedReader JavaDoc(r);
297                     String JavaDoc line;
298                     while ((line = br.readLine()) != null) {
299                         pw.println(tokens == null ? line : replaceTokens(tokens, line));
300                     }
301                 } finally {
302                     is.close();
303                 }
304             } finally {
305                 pw.close();
306             }
307         } finally {
308             os.close();
309         }
310     }
311     
312     private static String JavaDoc replaceTokens(Map JavaDoc<String JavaDoc,String JavaDoc> tokens, String JavaDoc line) {
313         for (Iterator JavaDoc it = tokens.entrySet().iterator(); it.hasNext(); ) {
314             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
315             line = line.replaceAll((String JavaDoc) entry.getKey(), (String JavaDoc) entry.getValue());
316         }
317         return line;
318     }
319     
320     private static final class BundleKey extends OperationBase {
321         
322         private final String JavaDoc bundlePath;
323         private final String JavaDoc key;
324         private final String JavaDoc value;
325         
326         public BundleKey(Project project, String JavaDoc key, String JavaDoc value) {
327             this(project, key, value, null);
328         }
329         
330         public BundleKey(Project project, String JavaDoc key, String JavaDoc value, String JavaDoc bundlePath) {
331             super(project);
332             this.key = key;
333             this.value = value;
334             if (bundlePath == null) {
335                 
336                 ManifestManager mm = ManifestManager.getInstance(Util.getManifest(getModuleInfo().getManifestFile()), false);
337                 String JavaDoc srcDir = getModuleInfo().getResourceDirectoryPath(false);
338                 this.bundlePath = srcDir + "/" + mm.getLocalizingBundle(); // NOI18N
339
} else {
340                 this.bundlePath = bundlePath;
341             }
342             addCreatedOrModifiedPath(this.bundlePath, true);
343         }
344         
345         public void run() throws IOException JavaDoc {
346             FileObject prjDir = getProject().getProjectDirectory();
347             FileObject bundleFO = FileUtil.createData(prjDir, bundlePath);
348             EditableProperties ep = Util.loadProperties(bundleFO);
349             ep.setProperty(key, value);
350             Util.storeProperties(bundleFO, ep);
351         }
352         
353     }
354     
355     private static final class AddLoaderSection extends OperationBase {
356         
357         private FileObject mfFO;
358         
359         private String JavaDoc dataLoaderClass;
360         private String JavaDoc installBefore;
361         
362         public AddLoaderSection(Project project, String JavaDoc dataLoaderClass, String JavaDoc installBefore) {
363             super(project);
364             this.dataLoaderClass = dataLoaderClass + ".class"; // NOI18N
365
this.installBefore = installBefore;
366             this.mfFO = getModuleInfo().getManifestFile();
367             addModifiedFileObject(mfFO);
368         }
369         
370         public void run() throws IOException JavaDoc {
371             //#65420 it can happen the manifest is currently being edited. save it
372
// and cross fingers because it can be in inconsistent state
373
try {
374                 DataObject dobj = DataObject.find(mfFO);
375                 SaveCookie safe = (SaveCookie)dobj.getCookie(SaveCookie.class);
376                 if (safe != null) {
377                     safe.save();
378                 }
379             } catch (DataObjectNotFoundException ex) {
380                 Util.err.notify(ErrorManager.WARNING, ex);
381             }
382             
383             EditableManifest em = Util.loadManifest(mfFO);
384             em.addSection(dataLoaderClass);
385             em.setAttribute("OpenIDE-Module-Class", "Loader", dataLoaderClass); // NOI18N
386
if (installBefore != null) {
387                 em.setAttribute("Install-Before", installBefore, dataLoaderClass); //NOI18N
388
}
389             Util.storeManifest(mfFO, em);
390         }
391         
392     }
393     
394     private static final class AddModuleDependency extends OperationBase {
395         
396         private String JavaDoc codeNameBase;
397         private String JavaDoc releaseVersion;
398         private SpecificationVersion specVersion;
399         private boolean useInCompiler;
400         
401         public AddModuleDependency(Project project, String JavaDoc codeNameBase,
402                 String JavaDoc releaseVersion, SpecificationVersion specVersion, boolean useInCompiler) {
403             super(project);
404             this.codeNameBase = codeNameBase;
405             this.releaseVersion = releaseVersion;
406             this.specVersion = specVersion;
407             this.useInCompiler = useInCompiler;
408             getModifiedPathsSet().add(getModuleInfo().getProjectFilePath()); // NOI18N
409
}
410         
411         public void run() throws IOException JavaDoc {
412             getModuleInfo().addDependency(codeNameBase, releaseVersion, specVersion, useInCompiler);
413             // XXX consider this carefully
414
ProjectManager.getDefault().saveProject(getProject());
415         }
416         
417     }
418     
419     private static final class AddLookupRegistration extends OperationBase {
420         
421         private String JavaDoc interfaceClassPath;
422         private String JavaDoc implClass;
423         
424         public AddLookupRegistration(Project project, String JavaDoc interfaceClass, String JavaDoc implClass, boolean inTests) {
425             super(project);
426             this.implClass = implClass;
427             this.interfaceClassPath = getModuleInfo().getResourceDirectoryPath(inTests) + // NOI18N
428
"/META-INF/services/" + interfaceClass; // NOI18N
429
addCreatedOrModifiedPath(interfaceClassPath, true);
430         }
431         
432         public void run() throws IOException JavaDoc {
433             FileObject service = FileUtil.createData(
434                     getProject().getProjectDirectory(),interfaceClassPath);
435             
436             String JavaDoc line = null;
437             List JavaDoc lines = new ArrayList JavaDoc();
438             InputStream JavaDoc serviceIS = service.getInputStream();
439             try {
440                 BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(serviceIS, "UTF-8")); // NOI18N
441
while ((line = br.readLine()) != null) {
442                     lines.add(line);
443                 }
444             } finally {
445                 serviceIS.close();
446             }
447             
448             FileLock lock = service.lock();
449             try {
450                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(service.getOutputStream(lock), "UTF-8")); // NOI18N
451
try {
452                     for (int i = 0; i < lines.size(); i++) {
453                         line = (String JavaDoc) lines.get(i);
454                         if (i != lines.size() - 1 || !line.trim().equals("")) {
455                             pw.println(line);
456                         }
457                     }
458                     pw.println(implClass);
459                 } finally {
460                     pw.close();
461                 }
462             } finally {
463                 lock.releaseLock();
464             }
465             
466         }
467     }
468     
469     private static final class CreateLayerEntry extends OperationBase {
470         
471         private CreatedModifiedFiles.Operation createBundleKey;
472         private CreatedModifiedFiles.Operation layerOp;
473         
474         public CreateLayerEntry(CreatedModifiedFiles cmf, Project project, final String JavaDoc layerPath,
475                 final URL JavaDoc content,
476                 final Map JavaDoc<String JavaDoc,String JavaDoc> tokens, final String JavaDoc localizedDisplayName, final Map JavaDoc attrs) {
477             
478             super(project);
479             CreatedModifiedFiles.LayerOperation op = new CreatedModifiedFiles.LayerOperation() {
480                 public void run(FileSystem layer) throws IOException JavaDoc {
481                     FileObject targetFO = FileUtil.createData(layer.getRoot(), layerPath);
482                     if (content != null) {
483                         FileLock lock = targetFO.lock();
484                         try {
485                             if (tokens == null) {
486                                 copyByteAfterByte(content, lock, targetFO);
487                             } else {
488                                 copyAndSubstituteTokens(content, lock, targetFO, tokens);
489                             }
490                         } finally {
491                             lock.releaseLock();
492                         }
493                     }
494                     if (localizedDisplayName != null) {
495                         String JavaDoc bundlePath = ManifestManager.getInstance(Util.getManifest(getModuleInfo().getManifestFile()), false).getLocalizingBundle();
496                         String JavaDoc suffix = ".properties"; // NOI18N
497
if (bundlePath != null && bundlePath.endsWith(suffix)) {
498                             String JavaDoc name = bundlePath.substring(0, bundlePath.length() - suffix.length()).replace('/', '.');
499                             targetFO.setAttribute("SystemFileSystem.localizingBundle", name); // NOI18N
500
} else {
501                             // XXX what?
502
}
503                     }
504                     if (attrs != null) {
505                         Iterator JavaDoc it = attrs.entrySet().iterator();
506                         while (it.hasNext()) {
507                             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
508                             targetFO.setAttribute((String JavaDoc) entry.getKey(), entry.getValue());
509                         }
510                     }
511                 }
512             };
513             Set JavaDoc<String JavaDoc> externalFiles;
514             if (content != null) {
515                 FileObject xml = LayerUtils.layerForProject(project).getLayerFile();
516                 FileObject parent = xml != null ? xml.getParent() : null;
517                 // XXX this is not fully accurate since if two ops would both create the same file,
518
// really the second one would automatically generate a uniquified name... but close enough!
519
externalFiles = Collections.singleton(LayerUtils.findGeneratedName(parent, layerPath));
520             } else {
521                 externalFiles = Collections.EMPTY_SET;
522             }
523             layerOp = new LayerModifications(project, op, externalFiles, cmf);
524             addPaths(layerOp);
525             if (localizedDisplayName != null) {
526                 this.createBundleKey = new BundleKey(getProject(), layerPath, localizedDisplayName);
527                 addPaths(this.createBundleKey);
528             }
529         }
530         
531         public void run() throws IOException JavaDoc{
532             layerOp.run();
533             if (createBundleKey != null) {
534                 createBundleKey.run();
535             }
536         }
537     }
538     
539     private static final class LayerModifications implements CreatedModifiedFiles.Operation {
540         
541         private final Project project;
542         private final CreatedModifiedFiles.LayerOperation op;
543         private final Set JavaDoc<String JavaDoc> externalFiles;
544         private final CreatedModifiedFiles cmf;
545         
546         public LayerModifications(Project project, CreatedModifiedFiles.LayerOperation op, Set JavaDoc<String JavaDoc> externalFiles, CreatedModifiedFiles cmf) {
547             this.project = project;
548             this.op = op;
549             this.externalFiles = externalFiles;
550             this.cmf = cmf;
551         }
552         
553         public void run() throws IOException JavaDoc {
554             op.run(cmf.getLayerHandle().layer(true));
555         }
556         
557         private String JavaDoc layerPrefix() {
558             FileObject layer = cmf.getLayerHandle().getLayerFile();
559             if (layer == null) {
560                 return null;
561             }
562             return FileUtil.getRelativePath(project.getProjectDirectory(), layer);
563         }
564         
565         public String JavaDoc[] getModifiedPaths() {
566             String JavaDoc layerPath = layerPrefix();
567             if (layerPath == null) {
568                 return new String JavaDoc[0];
569             }
570             return new String JavaDoc[] {layerPath};
571         }
572         
573         public String JavaDoc[] getCreatedPaths() {
574             String JavaDoc layerPath = layerPrefix();
575             if (layerPath == null) {
576                 return new String JavaDoc[0];
577             }
578             int slash = layerPath.lastIndexOf('/');
579             String JavaDoc prefix = layerPath.substring(0, slash + 1);
580             SortedSet JavaDoc s = new TreeSet JavaDoc();
581             Iterator JavaDoc it = externalFiles.iterator();
582             while (it.hasNext()) {
583                 s.add(prefix + (String JavaDoc) it.next());
584             }
585             return (String JavaDoc[]) s.toArray(new String JavaDoc[s.size()]);
586         }
587         
588         public String JavaDoc[] getInvalidPaths() {
589             //TODO applicable here?
590
return new String JavaDoc[0];
591         }
592         
593     }
594     
595     /**
596      * Operation for making changes in manifest
597      */

598     public static class ModifyManifest extends CreatedModifiedFilesFactory.OperationBase {
599         private FileObject manifestFile;
600         private Map JavaDoc attributesToAdd;
601         
602         /**
603          * @param project
604          */

605         public ModifyManifest(final Project project) {
606             super(project);
607             this.attributesToAdd = new HashMap JavaDoc();
608             addModifiedFileObject(getManifestFile());
609         }
610         
611         /**
612          * Adds requirement for modifying attribute for the main section. How attribute
613          * will be modified depends on implementation of method {@link performModification}.
614          * @param name the attribute name
615          * @param value the new attribute value
616          */

617         public final void setAttribute(final String JavaDoc name, final String JavaDoc value) {
618             setAttribute(name, value, "null");//NOI18N
619
}
620         
621         /**
622          * Adds requirement for modifying attribute. How attribute
623          * will be modified depends on implementation of method {@link performModification}.
624          * @param name the attribute name
625          * @param value the new attribute value
626          * @param section the name of the section or null for the main section
627          */

628         public final void setAttribute(final String JavaDoc name, final String JavaDoc value, final String JavaDoc section) {
629             Map JavaDoc attribs = getAttributes(section);
630             if (attribs == null) {
631                 attribs = new HashMap JavaDoc();
632                 attributesToAdd.put(section, attribs);
633             }
634             attribs.put(name, value);
635         }
636         
637         /**
638          * Creates section if doesn't exists and set all attributes
639          * @param em EditableManifest where attribute represented by other
640          * parameters is going to be added
641          * @param name the attribute name
642          * @param value the new attribute value
643          * @param section the name of the section to add it to, or null for the main section
644          */

645         protected void performModification(final EditableManifest em,final String JavaDoc name,final String JavaDoc value,
646                 final String JavaDoc section) {
647             if (section != null && em.getSectionNames().contains(section)) {
648                 em.addSection(section);
649             }
650             em.setAttribute(name, value, section);
651         }
652         
653         public final void run() throws IOException JavaDoc {
654             ensureSavingFirst();
655             
656             EditableManifest em = Util.loadManifest(getManifestFile());
657             for (Iterator JavaDoc sectionsIterator = attributesToAdd.keySet().iterator(); sectionsIterator.hasNext();) {
658                 String JavaDoc section = (String JavaDoc) sectionsIterator.next();
659                 Map JavaDoc attributes = getAttributes(section);
660                 assert attributes != null;
661                 
662                 for (Iterator JavaDoc attrsIterator = attributes.entrySet().iterator(); attrsIterator.hasNext();) {
663                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc) attrsIterator.next();
664                     String JavaDoc name = (String JavaDoc) entry.getKey();
665                     String JavaDoc value = (String JavaDoc) entry.getValue();
666                     performModification(em, name, value, (("null".equals(section)) ? null : section)); // NOI18N
667
}
668             }
669             
670             Util.storeManifest(getManifestFile(), em);
671         }
672         
673         
674         private FileObject getManifestFile() {
675             if (manifestFile == null) {
676                 manifestFile = getModuleInfo().getManifestFile();
677             }
678             return manifestFile;
679         }
680         
681         private Map JavaDoc getAttributes(final String JavaDoc sectionName) {
682             Map JavaDoc attribs = (Map JavaDoc)attributesToAdd.get(sectionName);
683             return attribs;
684         }
685         
686         private void ensureSavingFirst() throws IOException JavaDoc {
687             //#65420 it can happen the manifest is currently being edited. save it
688
// and cross fingers because it can be in inconsistent state
689
try {
690                 DataObject dobj = DataObject.find(getManifestFile());
691                 SaveCookie safe = (SaveCookie)dobj.getCookie(SaveCookie.class);
692                 if (safe != null) {
693                     safe.save();
694                 }
695             } catch (DataObjectNotFoundException ex) {
696                 Util.err.notify(ErrorManager.WARNING, ex);
697             }
698         }
699     }
700     
701     /**
702      * Operation for making changes in properties
703      */

704     private static class ModifyProperties extends CreatedModifiedFilesFactory.OperationBase {
705         private Map JavaDoc properties;
706         private final String JavaDoc propertyPath;
707         private EditableProperties ep;
708         private FileObject propertiesFile;
709         
710         private ModifyProperties(final Project project, final String JavaDoc propertyPath) {
711             super(project);
712             this.propertyPath= propertyPath;
713             addCreatedOrModifiedPath(propertyPath,true);
714         }
715         
716         public void run() throws IOException JavaDoc {
717             EditableProperties ep = getEditableProperties();
718             ep.putAll(getProperties());
719             Util.storeProperties(getPropertyFile(),ep);
720         }
721         
722         public final void setProperty(final String JavaDoc name, final String JavaDoc value) {
723             getProperties().put(name, value);
724         }
725         
726         protected final FileObject getPropertyFile() throws IOException JavaDoc {
727             if (propertiesFile == null) {
728                 FileObject projectDirectory = getProject().getProjectDirectory();
729                 propertiesFile = FileUtil.createData(projectDirectory, propertyPath);
730             }
731             return propertiesFile;
732         }
733         
734         protected final EditableProperties getEditableProperties() throws IOException JavaDoc {
735             if (ep == null) {
736                 ep = Util.loadProperties(getPropertyFile());
737             }
738             return ep;
739         }
740         
741         protected final Map JavaDoc getProperties() {
742             if (properties == null) {
743                 this.properties = new HashMap JavaDoc();
744             }
745             return properties;
746         }
747     }
748 }
749
750
Popular Tags