KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > apisupport > project > ui > wizard > loader > NewLoaderIterator


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.ui.wizard.loader;
21
22 import java.io.CharConversionException JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Arrays JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35 import java.util.logging.Level JavaDoc;
36 import java.util.logging.Logger JavaDoc;
37 import java.util.regex.Pattern JavaDoc;
38 import org.netbeans.modules.apisupport.project.CreatedModifiedFiles;
39 import org.netbeans.modules.apisupport.project.ui.wizard.BasicWizardIterator;
40 import org.netbeans.modules.apisupport.project.universe.ModuleEntry;
41 import org.netbeans.modules.apisupport.project.universe.ModuleList;
42 import org.openide.WizardDescriptor;
43 import org.openide.filesystems.FileObject;
44 import org.openide.filesystems.FileSystem;
45 import org.openide.filesystems.FileUtil;
46 import org.openide.loaders.DataFolder;
47 import org.openide.loaders.DataObject;
48 import org.openide.modules.SpecificationVersion;
49 import org.openide.util.NbBundle;
50 import org.openide.xml.XMLUtil;
51
52 /**
53  * Wizard for creating new DataLoaders
54  *
55  * @author Milos Kleint
56  */

57 final class NewLoaderIterator extends BasicWizardIterator {
58     
59     private NewLoaderIterator.DataModel data;
60     
61     private NewLoaderIterator() { /* Use factory method. */ };
62     
63     public static NewLoaderIterator createIterator() {
64         return new NewLoaderIterator();
65     }
66     
67     public Set JavaDoc instantiate() throws IOException JavaDoc {
68         CreatedModifiedFiles cmf = data.getCreatedModifiedFiles();
69         cmf.run();
70         return getCreatedFiles(cmf, data.getProject());
71     }
72     
73     protected BasicWizardIterator.Panel[] createPanels(WizardDescriptor wiz) {
74         data = new NewLoaderIterator.DataModel(wiz);
75         return new BasicWizardIterator.Panel[] {
76             new FileRecognitionPanel(wiz, data),
77             new NameAndLocationPanel(wiz, data)
78         };
79     }
80     
81     public void uninitialize(WizardDescriptor wiz) {
82         super.uninitialize(wiz);
83         data = null;
84     }
85     
86     
87     static final class DataModel extends BasicWizardIterator.BasicDataModel {
88         
89         private String JavaDoc prefix;
90         private String JavaDoc iconPath;
91         private String JavaDoc mimeType;
92         private boolean extensionBased = true;
93         private String JavaDoc extension;
94         private String JavaDoc namespace;
95         
96         private CreatedModifiedFiles files;
97         
98         DataModel(WizardDescriptor wiz) {
99             super(wiz);
100         }
101         
102         public CreatedModifiedFiles getCreatedModifiedFiles() {
103             return files;
104         }
105         
106         public void setCreatedModifiedFiles(CreatedModifiedFiles files) {
107             this.files = files;
108         }
109         
110         public String JavaDoc getPrefix() {
111             return prefix;
112         }
113         
114         public void setPrefix(String JavaDoc prefix) {
115             this.prefix = prefix;
116         }
117         
118         public String JavaDoc getIconPath() {
119             return iconPath;
120         }
121         
122         public void setIconPath(String JavaDoc iconPath) {
123             this.iconPath = iconPath;
124         }
125         
126         public String JavaDoc getMimeType() {
127             return mimeType;
128         }
129         
130         public void setMimeType(String JavaDoc mimeType) {
131             this.mimeType = mimeType;
132         }
133         
134         public boolean isExtensionBased() {
135             return extensionBased;
136         }
137         
138         public void setExtensionBased(boolean extensionBased) {
139             this.extensionBased = extensionBased;
140         }
141         
142         public String JavaDoc getExtension() {
143             return extension;
144         }
145         
146         public void setExtension(String JavaDoc extension) {
147             this.extension = extension;
148         }
149         
150         public String JavaDoc getNamespace() {
151             return namespace;
152         }
153         
154         public void setNamespace(String JavaDoc namespace) {
155             this.namespace = namespace;
156         }
157         
158     }
159     
160     public static void generateFileChanges(DataModel model) {
161         CreatedModifiedFiles fileChanges = new CreatedModifiedFiles(model.getProject());
162         
163         String JavaDoc namePrefix = model.getPrefix();
164         String JavaDoc packageName = model.getPackageName();
165         final String JavaDoc mime = model.getMimeType();
166         HashMap JavaDoc replaceTokens = new HashMap JavaDoc();
167         replaceTokens.put("@@PREFIX@@", namePrefix);//NOI18N
168
replaceTokens.put("@@PACKAGENAME@@", packageName);//NOI18N
169
replaceTokens.put("@@MIMETYPE@@", mime);//NOI18N
170
replaceTokens.put("@@EXTENSIONS@@", formatExtensions(model.isExtensionBased(), model.getExtension(), mime));//NOI18N
171
replaceTokens.put("@@NAMESPACES@@", formatNameSpace(model.isExtensionBased(), model.getNamespace(), mime));//NOI18N
172

173         // Copy action icon
174
String JavaDoc origIconPath = model.getIconPath();
175         if (origIconPath != null && new File JavaDoc(origIconPath).exists()) {
176             String JavaDoc relativeIconPath = model.addCreateIconOperation(fileChanges, origIconPath);
177             replaceTokens.put("@@IMAGESNIPPET@@", formatImageSnippet(relativeIconPath));//NOI18N
178
replaceTokens.put("@@ICONPATH@@", relativeIconPath);//NOI18N
179
replaceTokens.put("@@COMMENTICON@@", "");//NOI18N
180

181         } else {
182             replaceTokens.put("@@IMAGESNIPPET@@", formatImageSnippet(null)); //NOI18N
183
replaceTokens.put("@@ICONPATH@@", "SET/PATH/TO/ICON/HERE"); //NOI18N
184
replaceTokens.put("@@COMMENTICON@@", "//");//NOI18N
185
}
186         
187         // 1. create dataloader file
188
String JavaDoc loaderName = model.getDefaultPackagePath(namePrefix + "DataLoader.java", false); // NOI18N
189
// XXX use nbresloc URL protocol rather than NewLoaderIterator.class.getResource(...):
190
URL JavaDoc template = NewLoaderIterator.class.getResource("templateDataLoader.javx");//NOI18N
191
fileChanges.add(fileChanges.createFileWithSubstitutions(loaderName, template, replaceTokens));
192         String JavaDoc loaderInfoName = model.getDefaultPackagePath(namePrefix + "DataLoaderBeanInfo.java", false); // NOI18N
193
template = NewLoaderIterator.class.getResource("templateDataLoaderBeanInfo.javx");//NOI18N
194
fileChanges.add(fileChanges.createFileWithSubstitutions(loaderInfoName, template, replaceTokens));
195         
196         // 2. dataobject file
197
final boolean isEditable = Pattern.matches("(application/([a-zA-Z0-9_.-])*\\+xml|text/([a-zA-Z0-9_.+-])*)", //NOI18N
198
mime);
199         if (isEditable) {
200             StringBuffer JavaDoc editorBuf = new StringBuffer JavaDoc();
201             editorBuf.append(" CookieSet cookies = getCookieSet();\n");//NOI18N
202
editorBuf.append(" cookies.add((Node.Cookie) DataEditorSupport.create(this, getPrimaryEntry(), cookies));"); // NOI18N
203
replaceTokens.put("@@EDITOR_SUPPORT_SNIPPET@@", editorBuf.toString());//NOI18N
204
replaceTokens.put("@@EDITOR_SUPPORT_IMPORT@@", "import org.openide.text.DataEditorSupport;");//NOI18N
205
} else {
206             // ignore the editor support snippet
207
replaceTokens.put("@@EDITOR_SUPPORT_SNIPPET@@", "");//NOI18N
208
replaceTokens.put("@@EDITOR_SUPPORT_IMPORT@@", "");//NOI18N
209
}
210         
211         String JavaDoc doName = model.getDefaultPackagePath(namePrefix + "DataObject.java", false); // NOI18N
212
template = null;
213         try {
214             SpecificationVersion current = model.getModuleInfo().getDependencyVersion("org.openide.loaders");
215             SpecificationVersion desired = new SpecificationVersion("6.0"); // NOI18N
216
if (current.compareTo(desired) >= 0) {
217                 template = NewLoaderIterator.class.getResource("templateDataObjectWithLookup.javx");//NOI18N
218
}
219         } catch (IOException JavaDoc ex) {
220             Logger.getLogger(NewLoaderIterator.class.getName()).log(Level.INFO, null, ex);
221         }
222         if (template == null) {
223             template = NewLoaderIterator.class.getResource("templateDataObject.javx");//NOI18N
224
}
225         fileChanges.add(fileChanges.createFileWithSubstitutions(doName, template, replaceTokens));
226         
227         // 3. node file
228
String JavaDoc nodeName = model.getDefaultPackagePath(namePrefix + "DataNode.java", false); // NOI18N
229
template = NewLoaderIterator.class.getResource("templateDataNode.javx");//NOI18N
230
fileChanges.add(fileChanges.createFileWithSubstitutions(nodeName, template, replaceTokens));
231         
232         // 4. mimetyperesolver file
233
template = NewLoaderIterator.class.getResource("templateresolver.xml");//NOI18N
234
fileChanges.add(fileChanges.createLayerEntry("Services/MIMEResolver/" + namePrefix + "Resolver.xml", //NOI18N
235
template,
236                 replaceTokens,
237                 NbBundle.getMessage(NewLoaderIterator.class, "LBL_LoaderName", namePrefix),//NOI18N
238
null));
239         
240         //5. update project.xml with dependencies
241
fileChanges.add(fileChanges.addModuleDependency("org.openide.filesystems")); //NOI18N
242
fileChanges.add(fileChanges.addModuleDependency("org.openide.loaders")); //NOI18N
243
fileChanges.add(fileChanges.addModuleDependency("org.openide.nodes")); //NOI18N
244
fileChanges.add(fileChanges.addModuleDependency("org.openide.util")); //NOI18N
245
if (isEditable) {
246             fileChanges.add(fileChanges.addModuleDependency("org.openide.text")); //NOI18N
247
}
248         if (isEditable) {
249             fileChanges.add(fileChanges.addModuleDependency("org.openide.windows")); //NOI18N
250
}
251         
252         // 6. update/create bundle file
253
String JavaDoc bundlePath = model.getDefaultPackagePath("Bundle.properties", true); // NOI18N
254
fileChanges.add(fileChanges.bundleKey(bundlePath, "LBL_" + namePrefix + "_loader_name", // NOI18N
255
NbBundle.getMessage(NewLoaderIterator.class, "LBL_LoaderName", namePrefix))); //NOI18N
256

257         // 7. register manifest entry
258
boolean isXml = Pattern.matches("(application/([a-zA-Z0-9_.-])*\\+xml|text/([a-zA-Z0-9_.-])*\\+xml)", //NOI18N
259
mime);
260         String JavaDoc installBefore = null;
261         if (isXml) {
262             installBefore = "org.openide.loaders.XMLDataObject, org.netbeans.modules.xml.core.XMLDataObject"; //NOI18N
263
}
264         
265         fileChanges.add(fileChanges.addLoaderSection(packageName.replace('.', '/') + "/" + namePrefix + "DataLoader", installBefore)); // NOI18N
266

267         // 7a. create matching test registration for convenience (#73202)
268
fileChanges.add(fileChanges.addLookupRegistration("org.openide.loaders.DataLoader", packageName + '.' + namePrefix + "DataLoader", true)); // NOI18N
269

270         //8. create layerfile actions subsection
271

272         fileChanges.add(fileChanges.layerModifications(new CreatedModifiedFiles.LayerOperation() {
273             public void run(FileSystem layer) throws IOException JavaDoc {
274                 List JavaDoc<String JavaDoc> actions = new ArrayList JavaDoc();
275                 if (isEditable) {
276                     actions.add("org.openide.actions.OpenAction"); // NOI18N
277
}
278                 actions.addAll(Arrays.asList(new String JavaDoc[] {
279                     "org.openide.actions.FileSystemAction", // NOI18N
280
null,
281                     "org.openide.actions.CutAction", // NOI18N
282
"org.openide.actions.CopyAction", // NOI18N
283
null,
284                     "org.openide.actions.DeleteAction", // NOI18N
285
"org.openide.actions.RenameAction", // NOI18N
286
null,
287                     "org.openide.actions.SaveAsTemplateAction", // NOI18N
288
null,
289                     "org.openide.actions.ToolsAction", // NOI18N
290
"org.openide.actions.PropertiesAction", // NOI18N
291
}));
292                 FileObject folder = FileUtil.createFolder(layer.getRoot(), "Loaders/" + mime + "/Actions"); // NOI18N
293
List JavaDoc<DataObject> kids = new ArrayList JavaDoc();
294                 Iterator JavaDoc it = actions.iterator();
295                 int i = 0;
296                 while (it.hasNext()) {
297                     String JavaDoc name = (String JavaDoc) it.next();
298                     FileObject kid;
299                     if (name != null) {
300                         kid = folder.createData(name.replace('.', '-') + ".instance"); // NOI18N
301
} else {
302                         kid = folder.createData("sep-" + (++i) + ".instance"); // NOI18N
303
kid.setAttribute("instanceClass", "javax.swing.JSeparator"); // NOI18N
304
}
305                     kids.add(DataObject.find(kid));
306                 }
307                 DataFolder.findFolder(folder).setOrder((DataObject[]) kids.toArray(new DataObject[kids.size()]));
308             }
309         }, Collections.EMPTY_SET));
310         
311         //9. create sample template
312
String JavaDoc suffix = null;
313         if (model.isExtensionBased()) {
314             suffix = "Template." + getFirstExtension(model.getExtension()); // NOI18N
315
template = NewLoaderIterator.class.getResource("templateNew1");//NOI18N
316
} else {
317             template = NewLoaderIterator.class.getResource("templateNew2");//NOI18N
318
suffix = "Template.xml"; // NOI18N
319
try {
320                 replaceTokens.put("@@NAMESPACE@@", XMLUtil.toElementContent(model.getNamespace())); // NOI18N
321
} catch (CharConversionException JavaDoc ex) {
322                 assert false: ex;
323             }
324         }
325         Map JavaDoc attrs = new HashMap JavaDoc();
326         attrs.put("template", Boolean.TRUE); // NOI18N
327
fileChanges.add(fileChanges.createLayerEntry("Templates/Other/" + namePrefix + suffix, //NOI18N
328
template,
329                 replaceTokens,
330                 NbBundle.getMessage(NewLoaderIterator.class, "LBL_fileTemplateName", namePrefix),
331                 attrs)); //NOI18N
332
model.setCreatedModifiedFiles(fileChanges);
333     }
334     
335     private static String JavaDoc formatExtensions(boolean isExtensionBased, String JavaDoc ext, String JavaDoc mime) {
336         if (!isExtensionBased) {
337             return "";
338         }
339         StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
340         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(ext, " ,"); // NOI18N
341
while (tokens.hasMoreTokens()) {
342             String JavaDoc element = tokens.nextToken().trim();
343             if (element.startsWith(".")) { // NOI18N
344
element = element.substring(1);
345             }
346             buff.append(" <ext name=\"").append(element).append("\"/>\n"); //NOI18N
347
}
348         buff.append(" <resolver mime=\"").append(mime).append("\"/>"); //NOI18N
349
return buff.toString();
350     }
351     
352     private static String JavaDoc getFirstExtension(String JavaDoc ext) {
353         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(ext," ,"); // NOI18N
354
String JavaDoc element = "someextension"; // NOI18N
355
if (tokens.hasMoreTokens()) {
356             element = tokens.nextToken().trim();
357             if (element.startsWith(".")) { //NOI18N
358
element = element.substring(1);
359             }
360         }
361         return element;
362     }
363     
364     private static String JavaDoc formatNameSpace(boolean isExtensionBased, String JavaDoc namespace, String JavaDoc mime) {
365         if (isExtensionBased) {
366             return "";
367         }
368         StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
369         buff.append(" <ext name=\"xml\"/>\n"); //NOI18N
370
buff.append(" <resolver mime=\"").append(mime).append("\">\n"); //NOI18N
371
buff.append(" <xml-rule>\n"); // NOI18N
372
try {
373             buff.append(" <element ns=\"").append(XMLUtil.toElementContent(namespace)).append("\"/>\n"); //NOI18N
374
} catch (CharConversionException JavaDoc ex) {
375             assert false : ex;
376         }
377         buff.append(" </xml-rule>\n"); //NOI18N
378
buff.append(" </resolver>"); //NOI18N
379
return buff.toString();
380     }
381     
382     private static String JavaDoc formatImageSnippet(String JavaDoc path) {
383         if (path == null) {
384             // XXX Utilities is unconditionally imported
385
return "return super.getIcon(type); // TODO add a custom icon here\n"; //NOI18N
386
}
387         StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
388         buff.append(" if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {\n"); //NOI18N
389
buff.append(" return Utilities.loadImage(\""); //NOI18N
390
buff.append(path).append("\");\n"); //NOI18N
391
buff.append(" } else {\n"); //NOI18N
392
buff.append(" return null;\n }\n"); //NOI18N
393
return buff.toString();
394     }
395     
396 }
397
398
Popular Tags