KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > i18n > SelectorUtils


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20
21 package org.netbeans.modules.i18n;
22
23 import java.awt.*;
24 import java.io.IOException JavaDoc;
25 import java.util.*;
26 import javax.swing.*;
27 import org.netbeans.api.java.classpath.ClassPath;
28 import org.netbeans.api.java.project.JavaProjectConstants;
29 import org.netbeans.api.project.FileOwnerQuery;
30 import org.netbeans.api.project.Project;
31 import org.netbeans.api.project.ProjectUtils;
32 import org.netbeans.api.project.SourceGroup;
33 import org.netbeans.api.project.Sources;
34 import org.netbeans.modules.properties.PropertiesDataObject; // PENDING
35
import org.openide.filesystems.FileObject;
36 import org.openide.loaders.DataFolder;
37 import org.openide.loaders.DataObject;
38 import org.openide.nodes.AbstractNode;
39 import org.openide.nodes.Children;
40 import org.openide.nodes.Node;
41 import org.openide.nodes.NodeAcceptor;
42 import org.openide.nodes.NodeOperation;
43 import org.openide.util.UserCancelException;
44 import org.openide.filesystems.FileUtil;
45 import org.netbeans.api.java.queries.SourceForBinaryQuery;
46 import java.net.URL JavaDoc;
47 import org.netbeans.api.project.ProjectInformation;
48 import org.netbeans.api.queries.VisibilityQuery;
49 import org.openide.awt.Mnemonics;
50
51
52
53
54
55 /**
56  * A static utility class grouping functions for dialogs for selection
57  * sources from project and other places.
58  */

59 public class SelectorUtils {
60
61   /**
62    * The filter used to filter out folders and resource bundles.
63    */

64   public static final FilteredNode.NodeFilter BUNDLES_FILTER =
65     new FilteredNode.NodeFilter() {
66       public boolean acceptNode(Node n) {
67     // Has to be data object.
68
DataObject dataObject = (DataObject)n.getCookie(DataObject.class);
69     if(dataObject == null)
70       return false;
71            
72     // Has to be a folder or a resource class.
73
return
74       ((dataObject instanceof DataFolder) && (isVisible(dataObject))) ||
75       (dataObject instanceof PropertiesDataObject); // PENDING same like above.
76
}
77     };
78
79     private static boolean isVisible(DataObject dobj) {
80         return (dobj.getPrimaryFile()==null) ||
81             (VisibilityQuery.getDefault().isVisible(dobj.getPrimaryFile()));
82             
83     }
84     
85                        
86   public static final FilteredNode.NodeFilter ALL_FILTER =
87     new FilteredNode.NodeFilter() {
88       public boolean acceptNode(Node n) {
89     return true;
90       }
91     };
92
93
94
95   /**
96    * Brings up a modal windows for selection of a resource bundle from
97    * the given project.
98    * @param prj the project to select from
99    * @return DataObject representing the selected bundle file or null
100    */

101   static public DataObject selectBundle(Project prj, FileObject file) {
102     try {
103       Node root = bundlesNode(prj, file, true);
104
105       Node[] selectedNodes=
106     NodeOperation.getDefault().
107     select(
108            Util.getString("CTL_SelectPropDO_Dialog_Title"),
109            Util.getString("CTL_SelectPropDO_Dialog_RootTitle"),
110            root,
111            new NodeAcceptor() {
112          public boolean acceptNodes(Node[] nodes) {
113            if(nodes == null || nodes.length != 1) {
114              return false;
115            }
116
117            // Has to be data object.
118
DataObject dataObject = (DataObject)nodes[0].getCookie(DataObject.class);
119            if(dataObject == null)
120              return false;
121                       
122            // Has to be of resource class.
123
return dataObject.getClass().equals(PropertiesDataObject.class); // PENDING same like above.
124
}
125            }
126            );
127       return (DataObject)selectedNodes[0].getCookie(DataObject.class);
128     } catch (UserCancelException uce) {
129         //ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, uce);
130
// nobody is interested in the message
131
return null;
132     }
133
134   }
135
136
137     /**
138      * Prepare node structure for showing available bundles. The
139      * structure is relative to the file that should access the
140      * bundle.
141      * @param prj the <code>Project</code> <code>file</code> is in
142      * @param file <code>FileObject</code> to show bundles for
143      * @param includeFiles specifies whether to show jar files or just folders
144      * @return root <code>Node</code>
145      */

146     static public Node bundlesNode(Project prj, FileObject file, boolean includeFiles) {
147         java.util.List JavaDoc nodes = new LinkedList();
148         if (prj == null)
149             prj = FileOwnerQuery.getOwner(file);
150
151         ClassPath cp = ClassPath.getClassPath(file, ClassPath.EXECUTE);
152         if (cp != null) nodes.addAll(getRootNodes(prj, getRoots(cp), BUNDLES_FILTER, includeFiles));
153         
154         return createRootFor(nodes, prj);
155     }
156
157     private static java.util.List JavaDoc getRoots(ClassPath cp) {
158         ArrayList l = new ArrayList(cp.entries().size());
159         Iterator eit = cp.entries().iterator();
160         while(eit.hasNext()) {
161             ClassPath.Entry e = (ClassPath.Entry)eit.next();
162
163             // try to map it to sources
164
URL JavaDoc url = e.getURL();
165             SourceForBinaryQuery.Result r= SourceForBinaryQuery.findSourceRoots(url);
166             FileObject [] fos = r.getRoots();
167             if (fos.length > 0) {
168                 for (int i = 0 ; i < fos.length; i++) l.add(fos[i]);
169             } else {
170                 if (e.getRoot()!=null)
171                     l.add(e.getRoot()); // add the class-path location
172
// directly
173
}
174         }
175
176         return l;
177     }
178
179
180     private static java.util.List JavaDoc getRootNodes(Project prj,
181                                                java.util.List JavaDoc roots,
182                                                FilteredNode.NodeFilter filter,
183                                                boolean includeFiles) {
184         java.util.List JavaDoc nodes = new ArrayList(roots.size());
185         Iterator it = roots.iterator();
186         while (it.hasNext()) {
187             try {
188                 FileObject rfo = (FileObject)it.next();
189                 if (includeFiles || (FileUtil.toFile(rfo)!=null)) {
190                     Project owner = org.netbeans.api.project.FileOwnerQuery.getOwner(rfo);
191                     Node origNode = DataObject.find(rfo).getNodeDelegate();
192                     FilteredNode node = new FilteredNode(origNode,filter, getDisplayName(rfo, owner, prj!=owner));
193                     nodes.add(node);
194                 }
195             } catch (org.openide.loaders.DataObjectNotFoundException ex) {}
196         }
197         return nodes;
198     }
199
200
201     private static String JavaDoc getDisplayName(FileObject fo, Project owner, boolean incPrjName) {
202         if (owner != null) {
203             SourceGroup grp = getSourceGroup(fo, owner);
204             String JavaDoc n = (grp!=null)?grp.getDisplayName():FileUtil.getFileDisplayName(fo);
205             if (incPrjName) {
206                 ProjectInformation pi = ProjectUtils.getInformation(owner);
207                 n += " [" + pi.getDisplayName() + "]";
208             }
209             return n;
210         } else
211             return FileUtil.getFileDisplayName(fo);
212     }
213
214     private static SourceGroup getSourceGroup(FileObject file, Project prj) {
215       Sources src = ProjectUtils.getSources(prj);
216       SourceGroup[] srcgrps = src.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
217       for (int i = 0 ; i < srcgrps.length; i++) {
218           if (file == srcgrps[i].getRootFolder())
219               return srcgrps[i];
220       }
221       return null;
222     }
223
224
225   /**
226    * Prepare node structure showing sources
227    * @param prj the project to select from
228    * @param filter NodeFilter used to filter only relevant information
229    * @return root Node of source files from <code>prj</code> filtered
230    * by <code>filter</code>
231    **/

232   static public Node sourcesNode(Project prj, FilteredNode.NodeFilter filter) {
233       Sources src = ProjectUtils.getSources(prj);
234       SourceGroup[] srcgrps = src.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
235       java.util.List JavaDoc nodes = new ArrayList();
236       for (int i = 0 ; i < srcgrps.length; i++) {
237     try {
238       FileObject rfo = srcgrps[i].getRootFolder();
239       FilteredNode node = new FilteredNode(DataObject.find(rfo).getNodeDelegate(),
240                            filter);
241       // node.setName(srcgrps[i].getName());
242
node.setDisplayName(srcgrps[i].getDisplayName());
243       // node.setIcon(srcgrps[i].getIcon());
244

245       nodes.add(node);
246     } catch (org.openide.loaders.DataObjectNotFoundException ex) {}
247       }
248
249       return createRootFor(nodes, prj);
250   }
251
252     private static Node createRootFor(java.util.List JavaDoc nodes, Project prj) {
253         // create a root for all gathered nodes
254
Children ch = new Children.Array();
255         Node[] nodesArray = new Node[ nodes.size() ];
256         nodes.toArray( nodesArray );
257         ch.add( nodesArray );
258
259         AbstractNode ret = new AbstractNode(ch);
260         ret.setDisplayName(ProjectUtils.getInformation(prj).getDisplayName());
261         return ret;
262     }
263
264
265
266
267   /** Instantiate a template object.
268    * Asks user for the target file's folder and creates the file.
269    * @param project the project the template should be instantiated in
270    * @param refFile the file for which bundle is created
271    * @param template the template to use
272    * @return the generated DataObject
273    * @exception UserCancelException if the user cancels the action
274    * @exception IOException on I/O error
275    * @see DataObject#createFromTemplate
276    */

277   public static DataObject instantiateTemplate(Project project, FileObject refFile, DataObject template) throws IOException JavaDoc {
278     // Create component for for file name input.
279
ObjectNameInputPanel panel = new ObjectNameInputPanel();
280         
281     Node repositoryNode = SelectorUtils.bundlesNode(project, refFile, false);
282         
283     // Selects one folder from data systems.
284
DataFolder dataFolder =
285       (DataFolder)NodeOperation.getDefault().select
286       (
287        I18nUtil.getBundle().getString ("CTL_Template_Dialog_Title"),
288        I18nUtil.getBundle().getString ("CTL_Template_Dialog_RootTitle"),
289        repositoryNode,
290        new NodeAcceptor() {
291      public boolean acceptNodes(Node[] nodes) {
292        if(nodes == null || nodes.length != 1) {
293          return false;
294        }
295                     
296        DataFolder cookie = (DataFolder)nodes[0].getCookie(DataFolder.class);
297        return (cookie != null && cookie.getPrimaryFile().canWrite());
298      }
299        },
300        panel
301        )[0].getCookie(DataFolder.class);
302         
303        String JavaDoc name = panel.getText();
304         
305        DataObject newObject;
306         
307        if(name.equals ("")) { // NOI18N
308
newObject = template.createFromTemplate(dataFolder);
309        } else {
310      newObject = template.createFromTemplate(dataFolder, name);
311        }
312         
313        try {
314      return newObject;
315        } catch(ClassCastException JavaDoc cce) {
316      throw new UserCancelException();
317        }
318   }
319
320     public static DataObject selectOrCreateBundle(FileObject refFile, DataObject template) {
321         Node rootNode = bundlesNode(null, refFile, true);
322         FileSelector fs = new FileSelector(refFile, template);
323         fs.getDialog(I18nUtil.getBundle().getString ("CTL_SelectPropDO_Dialog_Title"), null) // NOI18N
324
.setVisible(true);
325         return fs.isConfirmed() ? fs.getSelectedDataObject() : null;
326     }
327
328   /** Panel used by <code>instantiateTemplate</code> method. */
329   private static class ObjectNameInputPanel extends JPanel {
330         
331     /** Generated Serialized Version UID. */
332     static final long serialVersionUID = 1980214734060402958L;
333
334     /** Text field. */
335     JTextField text;
336
337         
338     /** Constructs panel. */
339     public ObjectNameInputPanel () {
340       BorderLayout layout = new BorderLayout();
341       layout.setVgap(5);
342       layout.setHgap(5);
343       setLayout(layout);
344             
345       // label and text field with mnemonic
346
String JavaDoc labelText = I18nUtil.getBundle().getString ("LBL_TemplateName");
347       JLabel label = new JLabel();
348       Mnemonics.setLocalizedText(label, labelText);
349       text = new JTextField();
350       text.getAccessibleContext().setAccessibleDescription(I18nUtil.getBundle().getString ("ACS_TEXT_ObjectNameInputPanel"));
351             
352       label.setLabelFor(text);
353             
354       add(BorderLayout.WEST, label);
355       add(BorderLayout.CENTER, text);
356     }
357
358         
359     /** Requets focus for text field. */
360     public void requestFocus () {
361       text.requestFocus ();
362     }
363         
364     /** Getter for <code>text</code>. */
365     public String JavaDoc getText () {
366       return text.getText ();
367     }
368
369     /** Setter for <code>text</code>. */
370     public void setText (String JavaDoc s) {
371       setText(s);
372     }
373   } // End of nested class ObjectNameInputPanel
374

375
376
377
378 }
379
Popular Tags