KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > palette > PaletteItemDataObject


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.form.palette;
21
22 import java.util.*;
23 import java.io.*;
24 import java.beans.*;
25 import javax.swing.Action JavaDoc;
26
27 import org.xml.sax.*;
28 import org.xml.sax.helpers.DefaultHandler JavaDoc;
29
30 import org.openide.loaders.*;
31 import org.openide.filesystems.*;
32 import org.openide.nodes.*;
33 import org.openide.xml.XMLUtil;
34 import org.openide.actions.*;
35 import org.openide.util.Utilities;
36 import org.openide.util.NbBundle;
37 import org.openide.ErrorManager;
38
39 import org.netbeans.modules.form.project.ClassSource;
40
41 /**
42  * DataObject for palette item file. It reads the file and creates PaletteItem
43  * and node from it.
44  *
45  * @author Tomas Pavek
46  */

47
48 class PaletteItemDataObject extends MultiDataObject {
49
50     static final String JavaDoc XML_ROOT = "palette_item"; // NOI18N
51
static final String JavaDoc ATTR_VERSION = "version"; // NOI18N
52
static final String JavaDoc TAG_COMPONENT = "component"; // NOI18N
53
static final String JavaDoc ATTR_CLASSNAME = "classname"; // NOI18N
54
static final String JavaDoc ATTR_TYPE = "type"; // NOI18N
55
// static final String ATTR_IS_CONTAINER = "is-container"; // NOI18N
56
static final String JavaDoc TAG_CLASSPATH = "classpath"; // NOI18N
57
static final String JavaDoc TAG_RESOURCE= "resource"; // NOI18N
58
static final String JavaDoc ATTR_NAME = "name"; // NOI18N
59
static final String JavaDoc TAG_DESCRIPTION = "description"; // NOI18N
60
static final String JavaDoc ATTR_BUNDLE = "localizing-bundle"; // NOI18N
61
static final String JavaDoc ATTR_DISPLAY_NAME_KEY = "display-name-key"; // NOI18N
62
static final String JavaDoc ATTR_TOOLTIP_KEY = "tooltip-key"; // NOI18N
63
static final String JavaDoc TAG_ICON16 = "icon16"; // NOI18N
64
static final String JavaDoc ATTR_URL = "urlvalue"; // NOI18N
65
static final String JavaDoc TAG_ICON32 = "icon32"; // NOI18N
66
// component types: "visual", "menu", "layout", "border"
67
// classpath resource types: "jar", "library", "project" (defined in ClassSource)
68

69     private static final Node.PropertySet[] NO_PROPERTIES = new Node.PropertySet[0];
70
71     private boolean fileLoaded; // at least tried to load
72

73     private PaletteItem paletteItem;
74
75     // some raw data read from the file (other passed to PaletteItem)
76
private String JavaDoc displayName_key;
77     private String JavaDoc tooltip_key;
78     private String JavaDoc bundleName;
79     private String JavaDoc icon16URL;
80     private String JavaDoc icon32URL;
81
82     // resolved data (derived from raw data)
83
String JavaDoc displayName;
84     String JavaDoc tooltip;
85     java.awt.Image JavaDoc icon16;
86     java.awt.Image JavaDoc icon32;
87
88     // --------
89

90     PaletteItemDataObject(FileObject fo, MultiFileLoader loader)
91         throws DataObjectExistsException
92     {
93         super(fo, loader);
94     }
95
96     boolean isFileRead() {
97         return fileLoaded;
98     }
99
100     boolean isItemValid() {
101         return paletteItem != null;
102     }
103
104     void reloadFile() {
105         if (paletteItem != null) {
106             paletteItem.reset(); // resets resolved data (but not raw data)
107

108             paletteItem.componentClassSource = null;
109 // paletteItem.isContainer_explicit = null;
110
paletteItem.componentType_explicit = null;
111         }
112
113         displayName = null;
114         tooltip = null;
115         icon16 = null;
116         icon32 = null;
117
118         displayName_key = null;
119         tooltip_key = null;
120         bundleName = null;
121         icon16URL = null;
122         icon32URL = null;
123
124         loadFile();
125     }
126
127     // ------
128

129     public Node createNodeDelegate() {
130         return new ItemNode();
131     }
132
133     public Node.Cookie getCookie(Class JavaDoc cookieClass) {
134         if (PaletteItem.class.equals(cookieClass)) {
135             if (!fileLoaded)
136                 loadFile();
137             return paletteItem;
138         }
139         return super.getCookie(cookieClass);
140     }
141
142     // -------
143

144     private void loadFile() {
145         fileLoaded = true;
146         PaletteItem item = paletteItem;
147         if (item == null)
148             item = new PaletteItem(this);
149
150         FileObject file = getPrimaryFile();
151         if (file.getSize() == 0L) { // item file is empty
152
// just derive the component class name from the file name
153
item.setComponentClassSource(file.getName().replace('-', '.'),
154                                          null, null);
155             paletteItem = item;
156             return;
157         }
158         
159         // parse the XML file
160
try {
161             XMLReader reader = XMLUtil.createXMLReader();
162             PaletteItemHandler handler = new PaletteItemHandler();
163             reader.setContentHandler(handler);
164             InputSource input = new InputSource(getPrimaryFile().getURL().toExternalForm());
165             reader.parse(input);
166             // TODO report errors, validate using DTD?
167

168             item.setComponentExplicitType(handler.componentExplicitType);
169             if (handler.componentClassName != null || displayName_key != null) {
170                 String JavaDoc[] cpTypes;
171                 String JavaDoc[] cpNames;
172                 if (handler.cpTypeList.size() > 0) {
173                     cpTypes = new String JavaDoc[handler.cpTypeList.size()];
174                     handler.cpTypeList.toArray(cpTypes);
175                     cpNames = new String JavaDoc[handler.cpNameList.size()];
176                     handler.cpNameList.toArray(cpNames);
177                 } else {
178                     cpTypes = cpNames = null;
179                 }
180                 
181                 item.setComponentClassSource(handler.componentClassName, cpTypes, cpNames);
182                 
183                 paletteItem = item;
184             }
185         } catch (SAXException saxex) {
186             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, saxex);
187         } catch (IOException ioex) {
188             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioex);
189         }
190     }
191
192     /**
193      * @param folder folder of category where to create new file
194      * @param classname name of the component class
195      * @param source classpath source type - "jar", "library", "project"
196      * @param classpath names of classpath roots - e.g. JAR file paths
197      */

198     static void createFile(FileObject folder, ClassSource classSource)
199         throws IOException
200     {
201         String JavaDoc classname = classSource.getClassName();
202
203         int idx = classname.lastIndexOf('.');
204         String JavaDoc fileName = FileUtil.findFreeFileName(
205             folder,
206             idx >= 0 ? classname.substring(idx+1) : classname,
207             PaletteItemDataLoader.ITEM_EXT);
208
209         FileObject itemFile = folder.createData(fileName,
210                                                 PaletteItemDataLoader.ITEM_EXT);
211
212         StringBuffer JavaDoc buff = new StringBuffer JavaDoc(512);
213         buff.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n"); // NOI18N
214
buff.append("<palette_item version=\"1.0\">\n"); // NOI18N
215
buff.append(" <component classname=\""); // NOI18N
216
buff.append(classname);
217         buff.append("\" />\n"); // NOI18N
218
buff.append(" <classpath>\n"); // NOI18N
219
for (int i=0, n=classSource.getCPRootCount(); i < n; i++) {
220             buff.append(" <resource type=\""); // NOI18N
221
buff.append(classSource.getCPRootType(i));
222             buff.append("\" name=\""); // NOI18N
223
buff.append(classSource.getCPRootName(i));
224             buff.append("\" />\n"); // NOI18N
225
buff.append(" </classpath>\n"); // NOI18N
226
buff.append("</palette_item>\n"); // NOI18N
227
}
228
229         FileLock lock = itemFile.lock();
230         OutputStream os = itemFile.getOutputStream(lock);
231         try {
232             os.write(buff.toString().getBytes());
233         }
234         finally {
235             os.close();
236             lock.releaseLock();
237         }
238     }
239
240     // -------
241

242     /** DataLoader for the palette item files. */
243     public static final class PaletteItemDataLoader extends UniFileLoader {
244
245         static final String JavaDoc ITEM_EXT = "palette_item"; // NOI18N
246

247         PaletteItemDataLoader() {
248             super("org.netbeans.modules.form.palette.PaletteItemDataObject"); // NOI18N
249

250             ExtensionList ext = new ExtensionList();
251             ext.addExtension(ITEM_EXT);
252             setExtensions(ext);
253         }
254         
255         /** Gets default display name. Overides superclass method. */
256         protected String JavaDoc defaultDisplayName() {
257             return NbBundle.getBundle(PaletteItemDataObject.class)
258             .getString("PROP_PaletteItemLoader_Name"); // NOI18N
259
}
260         
261
262         protected MultiDataObject createMultiObject(FileObject primaryFile)
263             throws DataObjectExistsException, IOException
264         {
265             return new PaletteItemDataObject(primaryFile, this);
266         }
267     }
268     
269     public static final class PaletteItemDataLoaderBeanInfo extends SimpleBeanInfo {
270         private static String JavaDoc iconURL = "org/netbeans/modules/form/resources/palette_manager.png"; // NOI18N
271

272         public BeanInfo[] getAdditionalBeanInfo() {
273             try {
274                 return new BeanInfo[] { Introspector.getBeanInfo(UniFileLoader.class) };
275             } catch (IntrospectionException ie) {
276                 org.openide.ErrorManager.getDefault().notify(ie);
277                 return null;
278             }
279         }
280         
281         public java.awt.Image JavaDoc getIcon(final int type) {
282             return Utilities.loadImage(iconURL);
283         }
284         
285     }
286
287     // --------
288

289     /** Node representing the palette item (node delegate for the DataObject). */
290     class ItemNode extends DataNode {
291
292         ItemNode() {
293             super(PaletteItemDataObject.this, Children.LEAF);
294         }
295
296         public String JavaDoc getDisplayName() {
297             if (!fileLoaded)
298                 loadFile();
299
300             if (displayName == null) {
301                 displayName = getExplicitDisplayName();
302                 if (displayName == null) { // no explicit name
303
if (isItemValid()) {
304                         displayName = paletteItem.getDisplayName();
305                         if (displayName == null) { // no name from BeanDescriptor
306
String JavaDoc classname = paletteItem.getComponentClassName();
307                             if (classname != null) {
308                                 int i = classname.lastIndexOf('.'); // NOI18N
309
displayName = i >= 0 ?
310                                     classname.substring(i+1) : classname;
311                             }
312                         }
313                     }
314                     if (displayName == null) // no name derived from the item
315
displayName = super.getDisplayName();
316                 }
317             }
318             return displayName;
319         }
320
321         public String JavaDoc getShortDescription() {
322             if (!fileLoaded)
323                 loadFile();
324
325             if (tooltip == null) {
326                 tooltip = getExplicitTooltip();
327                 if (tooltip == null) { // no explicit tooltip
328
if (isItemValid()) {
329                         tooltip = paletteItem.getTooltip();
330                         if (tooltip == null) // no tooltip from BeanDescriptor
331
tooltip = paletteItem.getComponentClassName();
332                     }
333                     if (tooltip == null) // no tooltip derived from the item
334
tooltip = getDisplayName();
335                 }
336             }
337             return tooltip;
338         }
339
340         public boolean canRename() {
341             return false;
342         }
343
344         public java.awt.Image JavaDoc getIcon(int type) {
345             if (!fileLoaded)
346                 loadFile();
347
348             if (type == BeanInfo.ICON_COLOR_32x32
349                     || type == BeanInfo.ICON_MONO_32x32)
350             {
351                 if (icon32 == null) {
352                     icon32 = getExplicitIcon(type);
353                     if (icon32 == null && isItemValid())
354                         icon32 = paletteItem.getIcon(type);
355                     if (icon32 == null)
356                         icon32 = Utilities.loadImage("org/netbeans/modules/form/resources/palette/unknown32.gif"); // NOI18N
357
}
358                 return icon32;
359             }
360             else { // small icon by default
361
if (icon16 == null) {
362                     icon16 = getExplicitIcon(type);
363                     if (icon16 == null && isItemValid())
364                         icon16 = paletteItem.getIcon(type);
365                     if (icon16 == null)
366                         icon16 = Utilities.loadImage("org/netbeans/modules/form/resources/palette/unknown.gif"); // NOI18N
367
}
368                 return icon16;
369             }
370             // TODO badged icon for invalid item?
371
}
372
373         // TODO properties
374
public Node.PropertySet[] getPropertySets() {
375             return NO_PROPERTIES;
376         }
377
378         // ------
379

380         private String JavaDoc getExplicitDisplayName() {
381             String JavaDoc displayName = null;
382             if (displayName_key != null) {
383                 if (bundleName != null) {
384                     try {
385                         displayName = NbBundle.getBundle(bundleName)
386                                                 .getString(displayName_key);
387                     }
388                     catch (Exception JavaDoc ex) {} // ignore failure
389
}
390                 if (displayName == null)
391                     displayName = displayName_key;
392             }
393             return displayName;
394         }
395
396         private String JavaDoc getExplicitTooltip() {
397             String JavaDoc tooltip = null;
398             if (tooltip_key != null) {
399                 if (bundleName != null) {
400                     try {
401                         tooltip = NbBundle.getBundle(bundleName)
402                                             .getString(tooltip_key);
403                     }
404                     catch (Exception JavaDoc ex) {} // ignore failure
405
}
406                 if (tooltip == null)
407                     tooltip = tooltip_key;
408             }
409             return tooltip;
410         }
411
412         private java.awt.Image JavaDoc getExplicitIcon(int type) {
413             if (type == BeanInfo.ICON_COLOR_32x32
414                     || type == BeanInfo.ICON_MONO_32x32)
415             {
416                 if (icon32URL != null) { // explicit icon specified in file
417
try {
418                         return java.awt.Toolkit.getDefaultToolkit().getImage(
419                                                  new java.net.URL JavaDoc(icon32URL));
420                     }
421                     catch (java.net.MalformedURLException JavaDoc ex) {} // ignore
422
}
423                 else if (getPrimaryFile().getAttribute("SystemFileSystem.icon32") != null) // NOI18N
424
return super.getIcon(type);
425             }
426             else { // get small icon in other cases
427
if (icon16URL != null) { // explicit icon specified in file
428
try {
429                         return java.awt.Toolkit.getDefaultToolkit().getImage(
430                                                  new java.net.URL JavaDoc(icon16URL));
431                     }
432                     catch (java.net.MalformedURLException JavaDoc ex) {} // ignore
433
}
434                 else if (getPrimaryFile().getAttribute("SystemFileSystem.icon") != null) // NOI18N
435
return super.getIcon(type);
436             }
437             return null;
438         }
439     }
440     
441     private class PaletteItemHandler extends DefaultHandler JavaDoc {
442         List cpTypeList; // list for classpath type entries
443
List cpNameList; // list for classpath root name entries
444
String JavaDoc componentClassName;
445         String JavaDoc componentExplicitType;
446         
447         public void startDocument() throws SAXException {
448             cpTypeList = new ArrayList();
449             cpNameList = new ArrayList();
450             componentClassName = null;
451             componentExplicitType = null;
452         }
453                 
454         public void startElement(String JavaDoc uri, String JavaDoc localName, String JavaDoc qName,
455             Attributes attributes) throws SAXException {
456             if (XML_ROOT.equals(qName)) {
457                 String JavaDoc version = attributes.getValue(ATTR_VERSION);
458                 if (version == null) {
459                     String JavaDoc message = NbBundle.getBundle(PaletteItemDataObject.class)
460                         .getString("MSG_UnknownPaletteItemVersion"); // NOI18N
461
throw new SAXException(message);
462                 } else if (!version.startsWith("1.")) { // NOI18N
463
String JavaDoc message = NbBundle.getBundle(PaletteItemDataObject.class)
464                         .getString("MSG_UnsupportedPaletteItemVersion"); // NOI18N
465
throw new SAXException(message);
466                 }
467                 // TODO item ID (for now we take the class name as the ID)
468
} else if (TAG_COMPONENT.equals(qName)) {
469                 String JavaDoc className = attributes.getValue(ATTR_CLASSNAME);
470                 componentClassName = className;
471                 componentExplicitType = attributes.getValue(ATTR_TYPE);
472             } else if (TAG_CLASSPATH.equals(qName)) {
473                 // Content is processed in the next branch
474
} else if (TAG_RESOURCE.equals(qName)) {
475                 String JavaDoc type = attributes.getValue(ATTR_TYPE);
476                 String JavaDoc name = attributes.getValue(ATTR_NAME);
477                 if ((type != null) && (name != null)) {
478                     cpTypeList.add(type);
479                     cpNameList.add(name);
480                 }
481             } else if (TAG_DESCRIPTION.equals(qName)) {
482                 String JavaDoc bundle = attributes.getValue(ATTR_BUNDLE);
483                 if (bundle != null) {
484                     PaletteItemDataObject.this.bundleName = bundle;
485                 }
486                 String JavaDoc displayNameKey = attributes.getValue(ATTR_DISPLAY_NAME_KEY);
487                 if (displayNameKey != null) {
488                     PaletteItemDataObject.this.displayName_key = displayNameKey;
489                 }
490                 String JavaDoc tooltipKey = attributes.getValue(ATTR_TOOLTIP_KEY);
491                 if (tooltipKey != null) {
492                     PaletteItemDataObject.this.tooltip_key = tooltipKey;
493                 }
494             } else if (TAG_ICON16.equals(qName)) {
495                 String JavaDoc url = attributes.getValue(ATTR_URL);
496                 if (url != null) {
497                     PaletteItemDataObject.this.icon16URL = url;
498                 }
499                 // TODO support also class resource name for icons
500
} else if (TAG_ICON32.equals(qName)) {
501                 String JavaDoc url = attributes.getValue(ATTR_URL);
502                 if (url != null) {
503                     PaletteItemDataObject.this.icon32URL = url;
504                 }
505                 // TODO support also class resource name for icons
506
}
507         }
508     }
509     
510 }
511
Popular Tags