KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > i18n > form > FormI18nIntegerEditor


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
21 package org.netbeans.modules.i18n.form;
22
23
24 import java.awt.Component JavaDoc;
25 import java.beans.PropertyEditorSupport JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.ResourceBundle JavaDoc;
31 import org.netbeans.api.java.classpath.ClassPath;
32
33 import org.netbeans.modules.form.FormModel;
34 import org.netbeans.modules.form.FormAwareEditor;
35 import org.netbeans.modules.form.FormDataObject;
36 import org.netbeans.modules.form.NamedPropertyEditor;
37 import org.netbeans.modules.form.FormEditorSupport;
38 import org.netbeans.modules.i18n.I18nPanel;
39 import org.netbeans.modules.i18n.I18nString;
40 import org.netbeans.modules.i18n.I18nUtil;
41 import org.netbeans.modules.i18n.java.JavaI18nSupport;
42
43 import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor;
44 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
45 import org.openide.filesystems.FileObject;
46 import org.openide.filesystems.Repository;
47 import org.openide.loaders.DataObject;
48 import org.openide.NotifyDescriptor;
49 import org.openide.ErrorManager;
50 import org.openide.util.HelpCtx;
51 import org.openide.util.MapFormat;
52 import org.openide.util.NbBundle;
53
54 import org.w3c.dom.Element JavaDoc;
55 import org.w3c.dom.Document JavaDoc;
56 import org.w3c.dom.DOMException JavaDoc;
57 import org.w3c.dom.NamedNodeMap JavaDoc;
58 import org.w3c.dom.Node JavaDoc;
59 import org.w3c.dom.NodeList JavaDoc;
60 import org.netbeans.api.project.Project;
61
62
63 /**
64  * Property editor for editing <code>FormI18nInteger</code> value in form editor.
65  * This editor is registered during installing i18n module
66  * as editor for form properties of type <code>String</code>.
67  * It provides also a capability to store such object in XML form.
68  * <B>Note: </B>This class should be named FormI18nIntegerEditor, but due to forward compatibility
69  * remains that name.
70  *
71  * @author Petr Jiricka
72  * @see FormI18nInteger
73  * @see org.netbeans.modules.form.RADComponent
74  * @see org.netbeans.modules.form.RADProperty
75  */

76 public class FormI18nIntegerEditor extends PropertyEditorSupport JavaDoc implements FormAwareEditor, NamedPropertyEditor, XMLPropertyEditor {
77
78     /** Value of <code>ResourceBundleString</code> this editor is currently editing. */
79     private FormI18nInteger formI18nInteger;
80     
81     /** <code>DataObject</code> which have <code>SourceCookie</code>, and which document contains
82      * going-to-be-internatioanlized string.
83      */

84     private FormDataObject sourceDataObject;
85
86     /** Name of resource string XML element. */
87     public static final String JavaDoc XML_RESOURCESTRING = "ResourceString"; // NOI18N
88
/** Name of argument XML element (child element of resource string element). */
89     public static final String JavaDoc XML_ARGUMENT = "Argument"; // NOI18N
90
/** Name of attribute bundle of resource string XML element. */
91     public static final String JavaDoc ATTR_BUNDLE = "bundle"; // NOI18N
92
/** Name of attribute key of resource string XML element. */
93     public static final String JavaDoc ATTR_KEY = "key"; // NOI18N
94
/** Name of attribute identifier of resource string XML element. */
95     public static final String JavaDoc ATTR_IDENTIFIER = "identifier"; // NOI18N
96
/** Name of attribute replace format XML element. */
97     public static final String JavaDoc ATTR_REPLACE_FORMAT = "replaceFormat"; // NOI18N
98
/** Name of attribute index of argument XML element. */
99     public static final String JavaDoc ATTR_INDEX = "index"; // NOI18N
100
/** Name of attribute java code of argument XML element. */
101     public static final String JavaDoc ATTR_JAVACODE = "javacode"; // NOI18N
102

103     /** Maximal index of arguments in one argument XML element. */
104     private static final int MAX_INDEX = 1000;
105     
106     private final ResourceBundle JavaDoc bundle;
107
108  
109     /** Constructor. Creates new <code>ResourceBundleStringFormEditor</code>. */
110     public FormI18nIntegerEditor() {
111         bundle = NbBundle.getBundle(FormI18nIntegerEditor.class);
112     }
113
114
115     /** Overrides superclass method.
116      * @return null as we don't support this feature */

117     public String JavaDoc[] getTags() {
118         return null;
119     }
120
121     /** Sets as text. Overrides superclass method to be dummy -> don't throw
122      * <code>IllegalArgumentException</code> . */

123     public void setAsText(String JavaDoc text) {}
124         
125     
126     /** Overrides superclass method.
127      * @return text for the current value */

128     public String JavaDoc getAsText() {
129         FormI18nInteger formI18nInteger = (FormI18nInteger)getValue();
130         DataObject dataObject = formI18nInteger.getSupport().getResourceHolder().getResource();
131         
132         if (dataObject == null || formI18nInteger.getKey() == null) {
133             return bundle.getString("TXT_InvalidValue");
134         } else {
135
136             String JavaDoc resourceName = org.netbeans.modules.i18n.Util.
137                 getResourceName(formI18nInteger.getSupport().getSourceDataObject().getPrimaryFile(),
138                                 dataObject.getPrimaryFile(),
139                                 '/', false);// NOI18N
140

141             return MessageFormat.format(
142                 bundle.getString("TXT_Key"),
143                 new Object JavaDoc[] {
144                     formI18nInteger.getKey(),
145                     resourceName, // NOI18N
146
}
147             );
148         }
149     }
150
151     /** Overrides superclass method. Gets string, piece of code which will replace the hardcoded
152      * non-internationalized string in the source. The default form is:
153      * <p>
154      * <b><identifier name>.getString("<key name>")</b>
155      * or if arguments for the ResoureBundleStrin are set the form:
156      * <p>
157      * <b>java.text.MessageFormat.format(<identifier name>getString("<key name>"), new Object[] {<code set in Parameters and Comments panel>})</b>
158      */

159     public String JavaDoc getJavaInitializationString() {
160         return ((FormI18nInteger)getValue()).getReplaceString();
161     }
162     
163     /** Overrides superclass method.
164      * @return <code>ResourceBundlePanel</code> fed with <code>FormI18nInteger</code> value. */

165     public Component JavaDoc getCustomEditor() {
166         return new CustomEditor(new FormI18nInteger((FormI18nInteger)getValue()), getProject(), sourceDataObject.getPrimaryFile());
167     }
168     
169     private Project getProject() {
170       return org.netbeans.modules.i18n.Util.getProjectFor(sourceDataObject);
171     }
172
173
174     /** Overrides superclass method.
175      * @return true since we support this feature */

176     public boolean supportsCustomEditor() {
177         return true;
178     }
179
180     /** Overrides superclass method.
181      * @return <code>formI18nInteger</code> */

182     public Object JavaDoc getValue() {
183         if(formI18nInteger == null) {
184             formI18nInteger = createFormI18nInteger();
185
186             if(I18nUtil.getOptions().getLastResource2() != null)
187                 formI18nInteger.getSupport().getResourceHolder().setResource(I18nUtil.getOptions().getLastResource2());
188         }
189         
190         return formI18nInteger;
191     }
192
193     /** Overrides superclass method.
194      * @param value sets the new value for this editor */

195     public void setValue(Object JavaDoc object) {
196         if(object instanceof FormI18nInteger)
197             formI18nInteger = (FormI18nInteger)object;
198         else {
199             formI18nInteger = createFormI18nInteger();
200         
201             if(I18nUtil.getOptions().getLastResource2() != null)
202                 formI18nInteger.getSupport().getResourceHolder().setResource(I18nUtil.getOptions().getLastResource2());
203         }
204     }
205
206     /** Creates <code>FormI18nInteger</code> instance. Helper method. */
207     private FormI18nInteger createFormI18nInteger() {
208         // Note: Only here we can have support without possible document loading.
209
return new FormI18nInteger(new FormI18nSupport.Factory().createI18nSupport(sourceDataObject));
210     }
211     
212     /**
213      * Implements <code>FormAwareEditor</code> method.
214      * If a property editor implements the <code>FormAwareEditor</code>
215      * interface, this method is called immediately after the PropertyEditor
216      * instance is created or the custom editor is obtained from getCustomEditor().
217      * @param model the <code>FormModel</code> representing meta-data of current form */

218     public void setFormModel(FormModel model) {
219         sourceDataObject = FormEditorSupport.getFormDataObject(model);
220     }
221
222     /**
223      * Implements <code>NamePropertyEditor</code> interface method.
224      * @return Display name of the property editor
225      */

226     public String JavaDoc getDisplayName () {
227         return NbBundle.getMessage(FormI18nIntegerEditor.class, "PROP_IntegerEditor_name"); // NOI18N
228
}
229
230
231     /**
232      * Implements <code>XMLPropertyEditor</code> interface method.
233      * Called to load property value from specified XML subtree. If succesfully loaded,
234      * the value should be available via the getValue method.
235      * An IOException should be thrown when the value cannot be restored from the specified XML element
236      * @param element the XML DOM element representing a subtree of XML from which the value should be loaded
237      * @exception IOException thrown when the value cannot be restored from the specified XML element
238      * @see org.w3c.dom.Node
239      */

240     public void readFromXML(Node JavaDoc domNode) throws IOException JavaDoc {
241         if(!XML_RESOURCESTRING.equals (domNode.getNodeName ())) {
242             throw new IOException JavaDoc ();
243         }
244         
245         FormI18nInteger formI18nInteger = createFormI18nInteger();
246
247         NamedNodeMap JavaDoc namedNodes = domNode.getAttributes ();
248         
249         try {
250             Node JavaDoc node;
251             // Retrieve bundle name.
252
node = namedNodes.getNamedItem(ATTR_BUNDLE);
253             String JavaDoc bundleName = (node == null) ? null : node.getNodeValue();
254
255             // Retrieve key name.
256
node = namedNodes.getNamedItem(ATTR_KEY);
257             String JavaDoc key = (node == null) ? null : node.getNodeValue();
258
259             // Set the resource bundle property.
260
if(bundleName != null) {
261                 
262                 FileObject sourceFo = sourceDataObject.getPrimaryFile();
263                 if ( sourceFo != null ) {
264                     FileObject fileObject = org.netbeans.modules.i18n.Util.
265                         getResource(sourceFo, bundleName);
266
267                     if(fileObject != null) {
268                         try {
269                             DataObject dataObject = DataObject.find(fileObject);
270                             if(dataObject.getClass().equals(formI18nInteger.getSupport().getResourceHolder().getResourceClasses()[0])) // PENDING
271
formI18nInteger.getSupport().getResourceHolder().setResource(dataObject);
272                         }
273                         catch (IOException JavaDoc e) {
274                         }
275                     }
276                 }
277             }
278
279             // Set the key property.
280
if(key != null && key.length() > 0) {
281                 formI18nInteger.setKey(key);
282                 
283                 // Set value and comment.
284
formI18nInteger.setValue(formI18nInteger.getSupport().getResourceHolder().getValueForKey(key));
285                 formI18nInteger.setComment(formI18nInteger.getSupport().getResourceHolder().getCommentForKey(key));
286             }
287
288             // Try to get identifier value.
289
((JavaI18nSupport)formI18nInteger.getSupport()).createIdentifier();
290             
291             node = namedNodes.getNamedItem(ATTR_IDENTIFIER);
292             if(node != null) {
293                 String JavaDoc identifier = (node == null) ? null : node.getNodeValue();
294                 
295                 if(identifier != null)
296                     ((JavaI18nSupport)formI18nInteger.getSupport()).setIdentifier(identifier);
297             }
298             
299             // Try to get init format string value.
300
node = namedNodes.getNamedItem(ATTR_REPLACE_FORMAT);
301             if(node != null) {
302                 String JavaDoc replaceFormat = node.getNodeValue();
303                 
304                 if(replaceFormat != null && replaceFormat.length() > 0) {
305                     
306                     // Note: This part of code is only due to use in some development builds of MessageFormat
307
// instead of MapFormat. If somebidy used those builds the replace code is in MessageFormat
308
// so we will convert it to MapFormat.
309
// This could be later extracted.
310
// Note if the replace form at was in the MessageFormat convert to MapFormat
311
// Don't throw away.
312
Map JavaDoc map = new HashMap JavaDoc(6);
313                     map.put("0", "{identifier}"); // NOI18N
314
map.put("1", "{key}"); // NOI18N
315
map.put("2", "{bundleNameSlashes}"); // NOI18N
316
map.put("3", "{bundleNameDots}"); // NOI18N
317
map.put("4", "{sourceFileName}"); // NOI18N
318
map.put("fileName", "{sourceFileName}"); // NOI18N
319

320                     String JavaDoc newReplaceFormat = MapFormat.format(replaceFormat, map);
321                     
322                     formI18nInteger.setReplaceFormat(newReplaceFormat);
323                 }
324             } else {
325                 // Read was not succesful (old form or error) -> set old form replace format.
326
formI18nInteger.setReplaceFormat((String JavaDoc)I18nUtil.getDefaultReplaceFormat(false));
327             }
328         } catch(NullPointerException JavaDoc npe) {
329             throw new IOException JavaDoc ();
330         }
331
332         // Retrieve the arguments.
333
if(domNode instanceof Element JavaDoc) {
334             Element JavaDoc domElement = (Element JavaDoc)domNode;
335             NodeList JavaDoc argNodeList = domElement.getElementsByTagName(XML_ARGUMENT);
336
337             // Find out the highest index.
338
int highest = -1;
339             for(int i = 0; i < argNodeList.getLength(); i++) {
340                 NamedNodeMap JavaDoc attributes = argNodeList.item(i).getAttributes();
341                 
342                 Node JavaDoc indexNode = attributes.getNamedItem (ATTR_INDEX);
343                 String JavaDoc indexString = (indexNode == null) ? null : indexNode.getNodeValue ();
344
345                 if(indexString != null) {
346                     try {
347                         int index = Integer.parseInt(indexString);
348                         if (index > highest && index < MAX_INDEX)
349                             highest = index;
350                     } catch (Exception JavaDoc e) {}
351                 }
352             }
353
354             // Construct the array.
355
String JavaDoc[] parameters = new String JavaDoc[highest + 1];
356
357             // Fill the array.
358
for (int i = 0; i < argNodeList.getLength(); i++) {
359                 NamedNodeMap JavaDoc attr = argNodeList.item(i).getAttributes ();
360                 
361                 Node JavaDoc indexNode = attr.getNamedItem (ATTR_INDEX);
362                 String JavaDoc indexString = (indexNode == null) ? null : indexNode.getNodeValue ();
363                 if (indexString != null) {
364                     try {
365                         int index = Integer.parseInt(indexString);
366                         if (index < MAX_INDEX) {
367                             Node JavaDoc javaCodeNode = attr.getNamedItem (ATTR_JAVACODE);
368                             String JavaDoc javaCode = (javaCodeNode == null) ? null : javaCodeNode.getNodeValue ();
369                             parameters[index] = javaCode;
370                         }
371                     } catch (Exception JavaDoc e) {}
372                 }
373             }
374
375             // Fill all the values in case some are missing - make it really foolproof.
376
for (int i = 0; i < parameters.length; i++)
377                 if (parameters[i] == null)
378                     parameters[i] = ""; // NOI18N
379

380             // Set the parameters.
381
formI18nInteger.setArguments(parameters);
382         }
383
384         // Set the value for this editor.
385
setValue(formI18nInteger);
386     }
387
388     /**
389      * Implements <code>XMLPropertyEditor</code> interface method.
390      * Called to store current property value into XML subtree. The property value should be set using the
391      * setValue method prior to calling this method.
392      * @param doc The XML document to store the XML in - should be used for creating nodes only
393      * @return the XML DOM element representing a subtree of XML from which the value should be loaded
394      */

395     public Node JavaDoc storeToXML(Document JavaDoc doc) {
396         Element JavaDoc element = doc.createElement (XML_RESOURCESTRING);
397
398         String JavaDoc bundleName;
399         if (formI18nInteger.getSupport().getResourceHolder().getResource() == null) {
400             bundleName = "";
401         } else {
402             bundleName = org.netbeans.modules.i18n.Util.
403                 getResourceName(formI18nInteger.getSupport().getSourceDataObject().getPrimaryFile(),
404                                 formI18nInteger.getSupport().getResourceHolder().getResource().getPrimaryFile(),'/', true);
405             if (bundleName == null) bundleName = "";
406         }
407
408
409         // Set bundle and key property.
410
element.setAttribute(ATTR_BUNDLE, bundleName);
411         element.setAttribute(ATTR_KEY, (formI18nInteger.getKey() == null) ? "" : formI18nInteger.getKey()); // NOI18N
412
// Don't save identifier, replace the identifier argument with actual value in format.
413
JavaI18nSupport support = (JavaI18nSupport)formI18nInteger.getSupport();
414         if(support.getIdentifier() == null)
415             support.createIdentifier();
416         Map JavaDoc map = new HashMap JavaDoc(1);
417         map.put("identifier", support.getIdentifier()); // NOI18N
418
element.setAttribute(ATTR_REPLACE_FORMAT, formI18nInteger.getReplaceFormat() == null ? "" : MapFormat.format(formI18nInteger.getReplaceFormat(), map) ); // NOI18N
419

420         // Append subelements corresponding to parameters.
421
String JavaDoc[] arguments = formI18nInteger.getArguments();
422         for (int i = 0; i < arguments.length; i++) {
423             Element JavaDoc childElement = doc.createElement (XML_ARGUMENT);
424             childElement.setAttribute (ATTR_INDEX, "" + i); // NOI18N
425
childElement.setAttribute (ATTR_JAVACODE, arguments[i]);
426             try {
427                 element.appendChild(childElement);
428             } catch (DOMException JavaDoc de) {}
429         }
430
431         return element;
432     }
433
434     /** Custom editor for this property editor. */
435     private static class CustomEditor extends I18nPanel implements EnhancedCustomPropertyEditor {
436
437         private final ResourceBundle JavaDoc bundle;
438         
439         /** Constructor. */
440         public CustomEditor(I18nString i18nString, Project project, FileObject file) {
441             super(i18nString.getSupport().getPropertyPanel(), false, project, file);
442             bundle = NbBundle.getBundle(FormI18nIntegerEditor.class);
443             setI18nString(i18nString);
444             
445             HelpCtx.setHelpIDString(this, I18nUtil.HELP_ID_FORMED);
446         }
447
448         /** Implements <code>EnhancedCustomPropertyEditor</code> interface. */
449         public Object JavaDoc getPropertyValue() throws IllegalStateException JavaDoc {
450             I18nString i18nString = getI18nString();
451
452             if(i18nString == null
453                 || !(i18nString instanceof FormI18nInteger)
454                 || i18nString.getSupport().getResourceHolder().getResource() == null
455                 || i18nString.getKey() == null) {
456
457                 // Notify user that invalid value set.
458
IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc();
459                 String JavaDoc message = bundle.getString("MSG_InvalidValue");
460                 ErrorManager.getDefault().annotate(
461                      ise, ErrorManager.WARNING, message,
462                      message, null, null);
463                 throw ise;
464             }
465
466             // Try to add new key into resource bundle first.
467
i18nString.getSupport().getResourceHolder().addProperty(
468                 i18nString.getKey(),
469                 i18nString.getValue(),
470                 i18nString.getComment(),
471                 false //#19137 do not destroy existing locale values
472
);
473
474             return i18nString;
475         }
476
477     }
478
479     
480 }
481
Popular Tags