KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > ui > nodes > editors > IdentifierArrayEditor


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.java.ui.nodes.editors;
21
22 import java.beans.*;
23 import java.util.*;
24
25 import javax.swing.*;
26 import javax.jmi.reflect.JmiException;
27
28 import org.openide.*;
29 import org.openide.util.Utilities;
30 import org.openide.util.NbBundle;
31 import org.openide.explorer.propertysheet.ExPropertyEditor;
32 import org.openide.explorer.propertysheet.PropertyEnv;
33 import org.netbeans.jmi.javamodel.MultipartId;
34 import org.netbeans.jmi.javamodel.JavaModelPackage;
35 import org.netbeans.jmi.javamodel.NamedElement;
36 import org.netbeans.jmi.javamodel.Type;
37 import org.netbeans.jmi.javamodel.PrimitiveType;
38 import org.netbeans.modules.javacore.internalapi.JavaMetamodel;
39 import org.netbeans.modules.java.ui.nodes.elements.ElementNode;
40
41
42 /** Property editors for array of org.netbeans.jmi.javamodel.MultipartId
43 *
44 * @author Petr Hamernik, Jan Pokorsky
45 */

46 public class IdentifierArrayEditor extends PropertyEditorSupport implements ExPropertyEditor {
47         
48     public static final String JavaDoc JAVA_LANG_OBJECT = "java.lang.Object"; // NOI18N
49

50     /** Custom property editor Component. */
51     IdentifierArrayPanel panel;
52
53     /** Flag for prevention of cycle in firing
54     * of the properties changes.
55     */

56     boolean ignoreEditor = false;
57
58     /** Flag for prevention of cycle in firing
59     * of the properties changes.
60     */

61     boolean ignorePanel = false;
62
63     PropertyEnv env;
64     
65     private JavaModelPackage model;
66
67     /** @return text representation of the value */
68     public String JavaDoc getAsText() {
69         MultipartId[] id = (MultipartId[]) getValue();
70         if ( id == null )
71             return ""; // NOI18N
72

73         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
74
75         for (int i = 0; i < id.length; i++) {
76             if (i > 0)
77                 buf.append(", "); // NOI18N
78
buf.append(multipartIdToName(id[i]));
79         }
80
81         return buf.toString();
82     }
83     
84     public static String JavaDoc multipartIdToName(MultipartId id) {
85         LinkedList list = new LinkedList();
86         while (id != null) {
87             String JavaDoc stringRep;
88             if (id.getTypeArguments().size() > 0) {
89                 JavaModelPackage pkg = (JavaModelPackage) id.refImmediatePackage();
90                 NamedElement e = id.getElement();
91                 stringRep = e.getName();
92                 stringRep += '<';
93                 for (Iterator tIt = id.getTypeArguments().iterator(); ;) {
94                     stringRep += ((NamedElement) tIt.next()).getName();
95                     if (tIt.hasNext()) {
96                         stringRep += ", "; // NOI18N
97
} else {
98                         break;
99                     }
100                 }
101                 stringRep += '>';
102             } else {
103                 stringRep = id.getName();
104             }
105             list.addFirst(stringRep);
106             id = id.getParent();
107         }
108         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
109         for (Iterator iter = list.iterator(); iter.hasNext();) {
110             buf.append((String JavaDoc)iter.next());
111             if (iter.hasNext())
112                 buf.append('.');
113         }
114         return buf.toString();
115     }
116
117     /** Sets the value as the text */
118     public void setAsText(String JavaDoc text) throws IllegalArgumentException JavaDoc {
119         List list = Collections.EMPTY_LIST;
120
121         try {
122             JavaMetamodel.getDefaultRepository().beginTrans(false);
123             try {
124                 list = resolveIdentifiers(text);
125             } finally {
126                 JavaMetamodel.getDefaultRepository().endTrans();
127             }
128         } catch (JmiException ex) {
129             ErrorManager.getDefault().notify(ex);
130         }
131
132         MultipartId[] ret = new MultipartId[list.size()];
133         list.toArray(ret);
134         setValue(ret);
135     }
136
137     /**
138      * parses txt to return list of MultipartIds
139      */

140     private List/*<MultipartId>*/ resolveIdentifiers(String JavaDoc txt) {
141         StringTokenizer tukac = new StringTokenizer(txt, ", ", false); // NOI18N
142
List list = new ArrayList();
143         while (tukac.hasMoreTokens()) {
144             String JavaDoc id = tukac.nextToken();
145             JavaModelPackage jmp = model;
146             Type t = jmp.getType().resolve(id);
147             
148             // Assume any Java identifier can serve as a reference type name:
149
if (t instanceof PrimitiveType) {
150                 IllegalArgumentException JavaDoc ex = new IllegalArgumentException JavaDoc();
151                 String JavaDoc msg = java.text.MessageFormat.format(
152                         getString("MSG_InvalidIdentifier"), // NOI18N
153
new Object JavaDoc[] { id });
154                 ErrorManager.getDefault().annotate(ex, ErrorManager.USER, null, msg, null, null);
155                 throw ex;
156             }
157             
158             MultipartId mid = jmp.getMultipartId().createMultipartId(id, null, null);
159             list.add(mid);
160         }
161         return list;
162     }
163
164     /** Set new value */
165     public void setValue(Object JavaDoc o) {
166         ignoreEditor = true;
167         boolean saveIgnorePanel = ignorePanel;
168         
169         ignorePanel = false;
170         super.setValue(o);
171         if ((panel != null) & !saveIgnorePanel) {
172             panel.setIdentifiers((MultipartId[]) o);
173         }
174         ignoreEditor = false;
175     }
176
177     /** @return <CODE>true</CODE> */
178     public boolean supportsCustomEditor () {
179         return true;
180     }
181
182     /** Create new panel for this property editor.
183     * @return the visual component for editing the property
184     */

185     public java.awt.Component JavaDoc getCustomEditor () {
186         if (panel == null) {
187             panel = new IdentifierArrayPanel(model);
188             panel.setIdentifiers((MultipartId[]) getValue());
189             panel.setMnemonics(env);
190             panel.addPropertyChangeListener(new PropertyChangeListener() {
191                                                 public void propertyChange(PropertyChangeEvent evt) {
192                                                     if (!ignoreEditor && IdentifierArrayPanel.PROP_IDENTIFIERS.equals(evt.getPropertyName())) {
193                                                         ignorePanel = true;
194                                                         setValue(evt.getNewValue());
195                                                         ignorePanel = false;
196                                                     }
197                                                 }
198                                             });
199         }
200         return panel;
201     }
202
203     /**
204      * This method is called by the IDE to pass
205      * the environment to the property editor.
206      */

207     public void attachEnv(PropertyEnv env) {
208         this.env = env;
209         model = ElementNode.getModel(env.getFeatureDescriptor());
210     }
211     
212     /** Implementation of the abstract ObjectArrayPanel2 class.
213     * It is used for editing of arrays of Identifier objects.
214     */

215     static class IdentifierArrayPanel extends ObjectArrayPanel2 {
216
217         /** Name of the 'identifiers' property. */
218         public static final String JavaDoc PROP_IDENTIFIERS = "identifiers"; // NOI18N
219

220         /** Previous value */
221         MultipartId[] prevValue;
222         
223         private final JavaModelPackage javaModel;
224         
225         /** Constructor */
226         public IdentifierArrayPanel(JavaModelPackage javaModel) {
227             this.javaModel = javaModel;
228             prevValue = new MultipartId[0];
229
230             this.getListComponent().setCellRenderer(new DefaultListCellRenderer() {
231                                                         public java.awt.Component JavaDoc getListCellRendererComponent(JList list,
232                                                                 Object JavaDoc value, int index, boolean isSelected, boolean cellHasFocus) {
233                                                             java.awt.Component JavaDoc comp = super.getListCellRendererComponent(list,
234                                                                                       value, index, isSelected, cellHasFocus);
235                                                             if (comp == this) {
236                                                                 setText(multipartIdToName((MultipartId) value));
237                                                             }
238                                                             return comp;
239                                                         }
240                                                     });
241         }
242
243         /** @return the current value */
244         public MultipartId[] getIdentifiers() {
245             MultipartId[] ret = new MultipartId[model.size()];
246             model.copyInto(ret);
247             return ret;
248         }
249
250         /** Set new value.
251         */

252         public void setIdentifiers(MultipartId[] data) {
253             model = new DefaultListModel();
254             if (data != null) {
255                 for (int i = 0; i < data.length; i++)
256                     model.addElement(data[i]);
257             }
258             this.getListComponent().setModel(model);
259             modelChanged();
260         }
261
262         /** Fire the 'identifiers' property change. */
263         protected void modelChanged() {
264             MultipartId[] newValue = getIdentifiers();
265             firePropertyChange(PROP_IDENTIFIERS, prevValue, newValue);
266             prevValue = newValue;
267         }
268
269         /** Ask user for new value.
270         * @return new value or <CODE>null</CODE> when
271         * operation was canceled.
272         */

273         protected Object JavaDoc insertNewValue() {
274             return openInputDialog(null);
275         }
276
277         /** Ask user for edit value.
278         * @param oldValue The previous value to be edited
279         * @return new value or <CODE>null</CODE> when
280         * operation was canceled.
281         */

282         protected Object JavaDoc editValue(Object JavaDoc oldValue) {
283             return openInputDialog((MultipartId) oldValue);
284         }
285
286         /** Show dialog and allow user to enter new name.
287         */

288         protected MultipartId openInputDialog(MultipartId origValue) {
289             NotifyDescriptor.InputLine input = new NotifyDescriptor.InputLine(
290                                                    getString("LAB_NewName"), // NOI18N
291
getString("LAB_NewIdentifier") // NOI18N
292
);
293             if (origValue != null)
294                 input.setInputText(multipartIdToName(origValue));
295
296             for (;;) {
297                 Object JavaDoc ret = DialogDisplayer.getDefault().notify(input);
298                 if (ret == NotifyDescriptor.OK_OPTION) {
299                     String JavaDoc retValue = input.getInputText();
300                     if (retValue != null && !"".equals(retValue)) { // NOI18N
301
if (!retValue.startsWith(".") && !retValue.endsWith(".") && // NOI18N
302
(retValue.indexOf("..") == -1)) { // NOI18N
303
boolean ok = true;
304                             StringTokenizer tokenizer = new StringTokenizer(retValue, ".", false); // NOI18N
305
while (tokenizer.hasMoreTokens()) {
306                                 String JavaDoc token = tokenizer.nextToken();
307                                 if (!Utilities.isJavaIdentifier(token)) {
308                                     ok = false;
309                                     break;
310                                 }
311                             }
312                             if (ok)
313                                 return javaModel.getMultipartId().createMultipartId(retValue, null, null);
314                         }
315                     }
316                     DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(getString("MSG_NotValidID"))); // NOI18N
317
} else {
318                     return null;
319                 }
320             }
321         }
322     }
323          
324     private static String JavaDoc getString(String JavaDoc key) {
325         return NbBundle.getMessage(IdentifierArrayEditor.class, key);
326     }
327          
328 }
329
Popular Tags