KickJava   Java API By Example, From Geeks To Geeks.

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


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.NbBundle;
30 import org.openide.util.Utilities;
31 import org.openide.explorer.propertysheet.ExPropertyEditor;
32 import org.openide.explorer.propertysheet.PropertyEnv;
33 import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor;
34 import org.netbeans.jmi.javamodel.Parameter;
35 import org.netbeans.jmi.javamodel.JavaModelPackage;
36 import org.netbeans.jmi.javamodel.MultipartId;
37 import org.netbeans.modules.java.ui.nodes.elements.ElementNode;
38 import org.netbeans.modules.java.ui.nodes.elements.ElementFormat;
39 import org.netbeans.modules.javacore.internalapi.JavaMetamodel;
40
41 /** Property editor for array of org.netbeans.jmi.javamodel.Parameter classes
42 *
43 * @author Petr Hamernik, Jan Pokorsky
44 */

45 public class MethodParameterArrayEditor extends PropertyEditorSupport implements ExPropertyEditor {
46
47     /** Custom property editor Component. */
48     MethodParameterArrayPanel panel;
49
50     /** Flag for prevention of cycle in firing
51     * of the properties changes.
52     */

53     boolean ignoreEditor = false;
54
55     /** Flag for prevention of cycle in firing
56     * of the properties changes.
57     */

58     boolean ignorePanel = false;
59     
60     private PropertyEnv env;
61     
62     private JavaModelPackage model;
63     
64     private boolean isWritable;
65
66     public MethodParameterArrayEditor() {
67         this(true);
68     }
69
70     public MethodParameterArrayEditor(boolean isWritable) {
71         this.isWritable = isWritable;
72     }
73
74     /**
75     * @return The property value as a human editable string.
76     * <p> Returns null if the value can't be expressed as an editable string.
77     * <p> If a non-null value is returned, then the PropertyEditor should
78     * be prepared to parse that string back in setAsText().
79     */

80     public String JavaDoc getAsText() {
81         Parameter[] params = (Parameter[]) getValue();
82         String JavaDoc text = ""; // NOI18N
83
if (params != null) {
84             try {
85                 JavaMetamodel.getDefaultRepository().beginTrans(false);
86                 try {
87                     text = params2String(params, ", ", false); // NOI18N
88
} finally {
89                     JavaMetamodel.getDefaultRepository().endTrans();
90                 }
91             } catch (JmiException ex) {
92                 ErrorManager.getDefault().notify(ex);
93             }
94         }
95         return text;
96     }
97     
98     public static String JavaDoc params2String(Parameter[] params, String JavaDoc delimiter, boolean listJustTypes) {
99         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(30);
100         for (int i = 0; i < params.length; i++) {
101             if (i > 0)
102                 buf.append(delimiter); // NOI18N
103
buf.append(param2String(params[i], listJustTypes));
104         }
105         return buf.toString();
106     }
107     
108     private static String JavaDoc param2String(Parameter p, boolean listJustTypes) {
109         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(30);
110         if (!listJustTypes && p.isFinal()) {
111             sb.append("final"); // NOI18N
112
sb.append(' ');
113         }
114         sb.append(ElementFormat.elementName(p.getType()));
115         if (p.isVarArg()) {
116             sb.append("..."); // NOI18N
117
}
118
119         if (!listJustTypes) {
120             sb.append(' ');
121             sb.append(p.getName());
122         }
123         return sb.toString();
124     }
125
126     /** Set the property value by parsing a given String. May raise
127     * java.lang.IllegalArgumentException if either the String is
128     * badly formatted or if this kind of property can't be expressed
129     * as text.
130     * @param text The string to be parsed.
131     */

132     public void setAsText(String JavaDoc text) throws IllegalArgumentException JavaDoc {
133         throw new IllegalArgumentException JavaDoc("Use refactoring action instead"); // NOI18N
134
// StringTokenizer tok = new StringTokenizer(text, ",", false); // NOI18N
135
// ArrayList list = new ArrayList();
136
// while (tok.hasMoreTokens()) {
137
// String token = tok.nextToken();
138
// MethodParameter par;
139
//
140
// try {
141
// par = MethodParameter.parse(token);
142
// } catch (IllegalArgumentException ex) {
143
// String msg = java.text.MessageFormat.format(
144
// getString("MSG_IllegalMethodParameter"), // NOI18N
145
// new Object[] { token });
146
// ErrorManager.getDefault().annotate(ex,
147
// ErrorManager.USER, null, msg, null, null);
148
// throw ex;
149
// }
150
// for (Iterator it = list.iterator(); it.hasNext(); ) {
151
// if (par.getName().equals(((MethodParameter)it.next()).getName())) {
152
// String msg = java.text.MessageFormat.format(
153
// getString("MSG_DuplicateName2"), // NOI18N
154
// new Object[] { par.getName() });
155
// IllegalArgumentException ex= new IllegalArgumentException("Ambiguous name"); // NOI18N
156
// ErrorManager.getDefault().annotate(ex,
157
// ErrorManager.USER, null, msg, null, null);
158
// throw ex;
159
// }
160
// }
161
// list.add(par);
162
// }
163
// MethodParameter[] params = new MethodParameter[list.size()];
164
// list.toArray(params);
165
// setValue(params);
166
}
167
168     /** Sets the value */
169     public void setValue(Object JavaDoc o) {
170         ignoreEditor = true;
171         boolean saveIgnorePanel = ignorePanel;
172         
173         ignorePanel = false;
174         super.setValue(o);
175         if ((panel != null) & !saveIgnorePanel) {
176             panel.setMethodParameters((Parameter[])o);
177         }
178         ignoreEditor = false;
179     }
180
181     /** @return <CODE>true</CODE> */
182     public boolean supportsCustomEditor () {
183         return true;
184     }
185
186     /** Create new panel for this property editor.
187     * @return the visual component for editing the property
188     */

189     public java.awt.Component JavaDoc getCustomEditor () {
190         if (panel == null) {
191             panel = new MethodParameterArrayPanel(model, isWritable);
192             panel.setMnemonics(env);
193             panel.setMethodParameters((Parameter[]) getValue());
194
195             panel.addPropertyChangeListener(new PropertyChangeListener() {
196                                                 public void propertyChange(PropertyChangeEvent evt) {
197                                                     if (!ignoreEditor && MethodParameterArrayPanel.PROP_METHOD_PARAMETERS.equals(evt.getPropertyName())) {
198                                                         ignorePanel = true;
199                                                         setValue(evt.getNewValue());
200                                                         ignorePanel = false;
201                                                     }
202                                                 }
203                                             });
204
205         }
206         return panel;
207     }
208
209     /**
210      * This method is called by the IDE to pass
211      * the environment to the property editor.
212      */

213     public void attachEnv(PropertyEnv env) {
214         this.env = env;
215         model = ElementNode.getModel(env.getFeatureDescriptor());
216     }
217     
218     /** Implementation of the abstract ObjectArrayPanel2 class.
219     * It is used for editing of arrays of Identifier objects.
220     */

221     static class MethodParameterArrayPanel extends ObjectArrayPanel2
222     implements EnhancedCustomPropertyEditor {
223         /** Name of the 'methodParameters' property */
224         public static final String JavaDoc PROP_METHOD_PARAMETERS = "methodParameters"; // NOI18N
225

226         /** Previous value */
227         Parameter[] prevValue;
228         
229         final JavaModelPackage javaModel;
230
231         /** Constructor */
232         public MethodParameterArrayPanel(JavaModelPackage javaModel, boolean isWritable) {
233             super(isWritable);
234             this.javaModel = javaModel;
235             prevValue = new Parameter[0];
236
237             this.getListComponent().setCellRenderer(new DefaultListCellRenderer() {
238                 public java.awt.Component JavaDoc getListCellRendererComponent(JList list,
239                         Object JavaDoc value, int index, boolean isSelected, boolean cellHasFocus) {
240                     java.awt.Component JavaDoc comp = super.getListCellRendererComponent(list,
241                                               value, index, isSelected, cellHasFocus);
242                     if (comp == this) {
243                         try {
244                             JavaMetamodel.getDefaultRepository().beginTrans(false);
245                             try {
246                                 setText(param2String((Parameter) value, false));
247                             } finally {
248                                 JavaMetamodel.getDefaultRepository().endTrans();
249                             }
250                         } catch (JmiException ex) {
251                             ErrorManager.getDefault().notify(ex);
252                         }
253                     }
254                     return comp;
255                 }
256             });
257         }
258
259         /** @return the current value
260         */

261         public Parameter[] getMethodParameters() {
262             Parameter[] ret = new Parameter[model.size()];
263             model.copyInto(ret);
264             return ret;
265         }
266
267         /** Set new value
268         */

269         public void setMethodParameters(Parameter[] data) {
270             model = new DefaultListModel();
271             if (data != null) {
272                 for (int i = 0; i < data.length; i++)
273                     model.addElement(data[i]);
274             }
275             this.getListComponent().setModel(model);
276             modelChanged();
277         }
278
279         /** Fire the 'methodParameters' property change. */
280         protected void modelChanged() {
281             super.modelChanged();
282             Parameter[] newValue = getMethodParameters();
283             firePropertyChange(PROP_METHOD_PARAMETERS, prevValue, newValue);
284             prevValue = newValue;
285         }
286
287         /** Ask user for new value.
288         * @return new value or <CODE>null</CODE> when
289         * operation was canceled.
290         */

291         protected Object JavaDoc insertNewValue() {
292             return openInputDialog(null);
293         }
294
295         /** Ask user for edit value.
296         * @param oldValue The previous value to be edited
297         * @return new value or <CODE>null</CODE> when
298         * operation was canceled.
299         */

300         protected Object JavaDoc editValue(Object JavaDoc oldValue) {
301             return openInputDialog((Parameter) oldValue);
302         }
303
304         /** Show dialog and allow user to enter new method parameter.
305         * @param origValue current parameter
306         * @return New valid name or <CODE>null</CODE> if user cancel the operation.
307         */

308         protected Parameter openInputDialog(Parameter origValue) {
309             MethodParameterPanel panel = new MethodParameterPanel();
310
311             NotifyDescriptor desriptor = new NotifyDescriptor(
312                                              panel,
313                                              getString("LAB_EnterParameter"), // NOI18Nv
314
NotifyDescriptor.OK_CANCEL_OPTION,
315                                              NotifyDescriptor.PLAIN_MESSAGE, null, null);
316
317             if (origValue != null) {
318                 String JavaDoc origTypeName = origValue.getType().getName();
319                 if (origValue.isVarArg()) {
320                     origTypeName += "..."; // NOI18N
321
}
322                 panel.nameTextField.setText(origValue.getName());
323                 panel.typeCombo.setSelectedItem(origTypeName);
324                 panel.finalCheckBox.setSelected(origValue.isFinal());
325             }
326
327             for (;;) {
328                 Object JavaDoc ret = DialogDisplayer.getDefault().notify(desriptor);
329                 if (ret == NotifyDescriptor.OK_OPTION) {
330                     String JavaDoc errMsg = null;
331                     String JavaDoc name = panel.nameTextField.getText().trim();
332                     String JavaDoc typeName = panel.typeCombo.getSelectedItem().toString().trim();
333                     if (!Utilities.isJavaIdentifier(name))
334                         errMsg = "MSG_NotValidID"; // NOI18N
335
else if (typeName.length() == 0)
336                         errMsg = "MSG_NotValidType"; // NOI18N
337
else {
338                         try {
339                             JavaMetamodel.getDefaultRepository().beginTrans(false);
340                             try {
341                                 boolean isFinal = panel.finalCheckBox.isSelected();
342                                 Enumeration methodEnum = model.elements();
343                                 
344                                 while(methodEnum.hasMoreElements()) {
345                                     Parameter oldPar = (Parameter)methodEnum.nextElement();
346                                                               
347                                     if (origValue!=null && oldPar.equals(origValue))
348                                         continue;
349                                     if (name.equals(oldPar.getName())) {
350                                         errMsg = "MSG_DuplicateName"; // NOI18N
351
break;
352                                     }
353                                 }
354                                 if (errMsg == null) {
355                                     boolean isVarArg = typeName.endsWith("..."); // NOI18N
356
typeName = isVarArg? typeName.substring(0, typeName.length() - 3): typeName;
357                                     
358 // Type type = javaModel.getType().resolve(typeName);
359
// XXX Something like org.openide.src.Type.parse is needed to validate new type
360
// errMsg = "MSG_NotValidType"; // NOI18N
361
MultipartId typeID = javaModel.getMultipartId().createMultipartId(typeName, null, null);
362                                     Parameter p = javaModel.getParameter().createParameter();
363                                     p.setName(name);
364                                     p.setFinal(isFinal);
365 // p.setType(type);
366
p.setTypeName(typeID);
367                                     p.setVarArg(isVarArg);
368                                     return p;
369                                 }
370                             } finally {
371                                 JavaMetamodel.getDefaultRepository().endTrans();
372                             }
373                         } catch (JmiException ex) {
374                             ErrorManager.getDefault().notify(ex);
375                             return null;
376                         }
377                     }
378                     DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(getString(errMsg)));
379                 } else {
380                     return null;
381                 }
382             }
383         }
384         
385         public Object JavaDoc getPropertyValue() throws IllegalStateException JavaDoc {
386             return getMethodParameters();
387         }
388         
389     }
390     
391     private static String JavaDoc getString(String JavaDoc key) {
392         return NbBundle.getMessage(MethodParameterArrayEditor.class, key);
393     }
394
395 }
396
Popular Tags