KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > tasklist > usertasks > util > UTUtils


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  * Code is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.tasklist.usertasks.util;
21
22 import java.awt.Component JavaDoc;
23 import java.awt.Dimension JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.Logger JavaDoc;
33 import javax.swing.Action JavaDoc;
34 import javax.swing.JButton JavaDoc;
35
36 import javax.swing.JEditorPane JavaDoc;
37 import javax.swing.JToolBar JavaDoc;
38 import org.netbeans.modules.tasklist.core.TLUtils;
39
40 import org.openide.cookies.EditorCookie;
41 import org.openide.cookies.LineCookie;
42 import org.openide.filesystems.FileObject;
43 import org.openide.filesystems.FileUtil;
44 import org.openide.filesystems.URLMapper;
45 import org.openide.loaders.DataObject;
46 import org.openide.loaders.DataObjectNotFoundException;
47 import org.openide.nodes.Node;
48 import org.openide.text.CloneableEditorSupport;
49 import org.openide.text.Line;
50 import org.openide.text.NbDocument;
51 import org.openide.util.actions.Presenter;
52 import org.openide.windows.Mode;
53 import org.openide.windows.TopComponent;
54 import org.openide.windows.WindowManager;
55 import org.w3c.dom.Element JavaDoc;
56 import org.w3c.dom.Text JavaDoc;
57
58 /**
59  * Utility methods for usertasks.
60  *
61  * @author tl
62  */

63 public final class UTUtils {
64     public static final Logger JavaDoc LOGGER = TLUtils.getLogger(UTUtils.class);
65     
66     static {
67         LOGGER.setLevel(Level.OFF);
68     }
69
70     /**
71      * Copies the content of one stream to another.
72      *
73      * @param is input stream
74      * @param os output stream
75      */

76     public static void copyStream(InputStream JavaDoc is, OutputStream JavaDoc os)
77     throws IOException JavaDoc {
78         byte[] buffer = new byte[1024];
79         int read;
80         while ((read = is.read(buffer)) != -1) {
81             os.write(buffer, 0, read);
82         }
83     }
84     
85     /**
86      * Creates a tag in another one.
87      *
88      * @param el an XML node
89      * @param tagName name of the new sub-tag
90      * @return created element
91      */

92     public static Element JavaDoc appendElement(Element JavaDoc el, String JavaDoc tagName) {
93         Element JavaDoc r = el.getOwnerDocument().createElement(tagName);
94         el.appendChild(r);
95         return r;
96     }
97     
98     /**
99      * Creates a tag in another one.
100      *
101      * @param el an XML node
102      * @param tagName name of the new sub-tag
103      * @param content content for the new tag
104      * @return created element
105      */

106     public static Element JavaDoc appendElement(Element JavaDoc el, String JavaDoc tagName,
107             String JavaDoc content) {
108         Element JavaDoc r = el.getOwnerDocument().createElement(tagName);
109         el.appendChild(r);
110         Text JavaDoc txt = el.getOwnerDocument().createTextNode(content);
111         r.appendChild(txt);
112         return r;
113     }
114     
115     /**
116      * Appends a text element.
117      *
118      * @param el an element
119      * @param content text
120      * @return el
121      */

122     public static Element JavaDoc appendText(Element JavaDoc el, String JavaDoc content) {
123         Text JavaDoc txt = el.getOwnerDocument().createTextNode(content);
124         el.appendChild(txt);
125         return el;
126     }
127     
128     /**
129      * Prepares a (possibly) multi line text for showing as a tooltip
130      * (converts it to html).
131      *
132      * @param text a text
133      * @return a tooltip
134      */

135     public static String JavaDoc prepareForTooltip(String JavaDoc text) {
136         int index = text.indexOf('\n');
137         if (index == -1)
138             return text;
139         
140         StringBuffer JavaDoc sb = new StringBuffer JavaDoc("<html>"); // NOI18N
141
while (index >= 0) {
142             sb.append(text.substring(0, index));
143             sb.append("<br>"); // NOI18N
144
text = text.substring(index + 1);
145             index = text.indexOf('\n');
146         };
147         sb.append(text);
148         sb.append("</html>"); // NOI18N
149
return sb.toString();
150     }
151     
152     /**
153      * Create the default toolbar representation of an array of actions.
154      * Null items in the array will add a separator to the toolbar.
155      *
156      * @param actions actions to show in the generated toolbar
157      * @return a toolbar instance displaying them
158      */

159     public static JToolBar JavaDoc createToolbarPresenter(Action JavaDoc[] actions) {
160         JToolBar JavaDoc p = new JToolBar JavaDoc();
161         int i;
162         int k = actions.length;
163
164         for (i = 0; i < k; i++) {
165             if (actions[i] == null) {
166                 p.addSeparator(new Dimension JavaDoc(3, 3));
167             } else if (actions[i] instanceof Presenter.Toolbar) {
168                 p.add(((Presenter.Toolbar) actions[i]).getToolbarPresenter());
169             } else {
170                 p.add(actions[i]);
171             }
172         }
173         
174         final Dimension JavaDoc D = new Dimension JavaDoc(24, 24);
175         for (int j = 0; j < p.getComponentCount(); j++) {
176             Component JavaDoc c = p.getComponent(j);
177             if (c instanceof JButton JavaDoc) {
178                 ((JButton JavaDoc) c).setPreferredSize(D);
179                 ((JButton JavaDoc) c).setMinimumSize(D);
180                 ((JButton JavaDoc) c).setMaximumSize(D);
181             }
182         }
183
184         return p;
185     }
186     
187     /**
188      * Compares 2 objects using equals(Object).
189      *
190      * @param obj1 an object or null
191      * @param obj2 an object or null
192      * @return true if obj1 == null && obj2 == null or obj1.equals(obj2)
193      */

194     public static boolean objectsEquals(Object JavaDoc obj1, Object JavaDoc obj2) {
195         if (obj1 == null && obj2 == null)
196             return true;
197         if (obj1 != null && obj2 == null)
198             return false;
199         if (obj1 == null && obj2 != null)
200             return false;
201         return obj1.equals(obj2);
202     }
203     
204     /**
205      * Utility method which attempts to find the activated nodes
206      * for the currently showing topcomponent in the editor window.
207      *
208      * @return editor nodes or null
209      */

210     public static Node[] getEditorNodes() {
211         // First try to get the editor window itself; if you right click
212
// on a node in the Todo Window, that node becomes the activated
213
// node (which is good - it makes the properties window show the
214
// todo item's properties, etc.) but that means that we can't
215
// find the editor position via the normal means.
216
// So, we go hunting for the topmosteditor tab, and when we find it,
217
// ask for its nodes.
218
Node[] nodes = null;
219         WindowManager wm = WindowManager.getDefault();
220
221         // HACK ALERT !!! HACK ALERT!!! HACK ALERT!!!
222
// Look for the source editor window, and then go through its
223
// top components, pick the one that is showing - that's the
224
// front one!
225
Mode mode = wm.findMode(CloneableEditorSupport.EDITOR_MODE);
226         if (mode == null) {
227             return null;
228         }
229         TopComponent [] tcs = mode.getTopComponents();
230         for (int j = 0; j < tcs.length; j++) {
231             // Found the source editor...
232
if (tcs[j].isShowing()) {
233                 nodes = tcs[j].getActivatedNodes();
234                 break;
235             }
236         }
237         return nodes;
238     }
239
240     /**
241      * Finds cursor position.
242      *
243      * @param nodes nodes to search. May be null
244      * @return found line object or null if nothing found.
245      */

246     public static Line findCursorPosition(Node[] nodes) {
247         if (nodes == null) {
248             return null;
249         }
250
251         for (int i = 0; i < nodes.length; i++) {
252             EditorCookie ec = (EditorCookie) nodes[i].getCookie(EditorCookie.class);
253
254             if (ec != null) {
255                 JEditorPane JavaDoc[] editorPanes = ec.getOpenedPanes();
256                 if ((editorPanes != null) && (editorPanes.length > 0)) {
257                     int line = NbDocument.findLineNumber(
258                         ec.getDocument(),
259                         editorPanes[0].getCaret().getDot());
260                     LineCookie lc = (LineCookie) nodes[i].
261                         getCookie(LineCookie.class);
262                     if (lc != null) {
263                         Line l = lc.getLineSet().getCurrent(line);
264                         if (l != null)
265                             return l;
266                     }
267                 }
268             }
269         }
270
271         return null;
272     }
273
274     /**
275      * Finds a FileObject corresponding to the specified file name.
276      *
277      * @param filename a filename
278      * @return found FileObject or null
279      */

280     public static FileObject getFileObjectForFile(String JavaDoc filename) {
281         return FileUtil.toFileObject(FileUtil.normalizeFile(new File JavaDoc(filename)));
282     }
283     
284     /**
285      * Return the Line object for a particular line in a file.
286      *
287      * @param fo a file
288      * @param lineno line number: 0, 1, 2, 3, ...
289      * @return Line object or null
290      */

291     public static Line getLineByFile(FileObject fo, int lineno) {
292         DataObject dobj = null;
293         try {
294             dobj = DataObject.find(fo);
295         } catch (DataObjectNotFoundException e) {
296             LOGGER.log(Level.WARNING,
297                     "No data object could be found for file object " + // NOI18N
298
fo, e);
299         }
300
301         if (dobj == null)
302             return null;
303
304         // Go to the given line
305
try {
306             LineCookie lc = (LineCookie)dobj.getCookie(LineCookie.class);
307             if (lc != null) {
308                 Line.Set ls = lc.getLineSet();
309                 if (ls != null) {
310                     // I'm subtracting 1 because empirically I've discovered
311
// that the editor highlights whatever line I ask for plus 1
312
Line l = ls.getCurrent(lineno);
313                     return l;
314                 }
315             }
316         } catch (Exception JavaDoc e) {
317             LOGGER.log(Level.INFO, "failed", e); // NOI18N
318
}
319         return null;
320     }
321
322     /**
323      * Finds URL with the type URLMapper.EXTERNAL for the specified
324      * Line object.
325      *
326      * @param line a line objct
327      * @return found URL or null
328      */

329     public static URL JavaDoc getExternalURLForLine(Line line) {
330         DataObject dobj = (DataObject) line.getLookup().
331             lookup(DataObject.class);
332         URL JavaDoc url = null;
333         if (dobj != null) {
334             FileObject fo = dobj.getPrimaryFile();
335             url = URLMapper.findURL(fo, URLMapper.EXTERNAL);
336
337             /*
338             if (UTUtils.LOGGER.isLoggable(Level.FINE)) {
339                 UTUtils.LOGGER.fine("URLMapper.EXTERNAL" +
340                     URLMapper.findURL(fo, URLMapper.EXTERNAL));
341                 UTUtils.LOGGER.fine("URLMapper.INTERNAL" +
342                     URLMapper.findURL(fo, URLMapper.INTERNAL));
343                 UTUtils.LOGGER.fine("URLMapper.NETWORK" +
344                     URLMapper.findURL(fo, URLMapper.NETWORK));
345             }
346              */

347         }
348         
349         return url;
350     }
351     
352     /**
353      * Searchs for nodes in a tree that pass a filter.
354      *
355      * @param t a tree
356      * @param filter Boolean f(Object). Filter function.
357      */

358     public static <T> List JavaDoc<T> filter(TreeAbstraction<T> t, UnaryFunction filter) {
359         List JavaDoc<T> r = new ArrayList JavaDoc<T>();
360         filter(t, t.getRoot(), filter, r);
361         return r;
362     }
363     
364     /**
365      * Searches for nodes in a tree that pass a filter.
366      *
367      * @param t a tree
368      * @param node this node and all it's descendants will be filtered
369      * @param result nodes that passed the filter will be stored here
370      */

371     private static <T> void filter(TreeAbstraction<T> t, T node,
372             UnaryFunction filter, List JavaDoc<T> result) {
373         if (((Boolean JavaDoc) filter.compute(node)).booleanValue())
374             result.add(node);
375         for (int i = 0; i < t.getChildCount(node); i++) {
376             filter(t, t.getChild(node, i), filter, result);
377         }
378     }
379     
380     /**
381      * Processes all nodes in a tree in a depth-first manner.
382      *
383      * @param tree a tree
384      * @param f a function to be applied to each node
385      */

386     public static <T> void processDepthFirst(TreeAbstraction<T> tree,
387             UnaryFunction f) {
388         processDepthFirst(tree, tree.getRoot(), f);
389     }
390     
391     /**
392      * Processes all nodes under the specified in a depth-first manner.
393      *
394      * @param tree a tree
395      * @param f a function to be applied to each node.
396      */

397     private static <T> void processDepthFirst(TreeAbstraction<T> tree,
398             T object, UnaryFunction f) {
399         for (int i = 0; i < tree.getChildCount(object); i++) {
400             processDepthFirst(tree, tree.getChild(object, i), f);
401         }
402         f.compute(object) ;
403     }
404
405     /**
406      * Processes all nodes in a tree in a breadth-first manner.
407      *
408      * @param tree a tree
409      * @param f a function to be applied to each node
410      */

411     public static <T> void processBreadthFirst(TreeAbstraction<T> tree,
412             UnaryFunction f) {
413         processBreadthFirst(tree, tree.getRoot(), f);
414     }
415     
416     /**
417      * Processes all nodes under the specified in a breadth-first manner.
418      *
419      * @param tree a tree
420      * @param f a function to be applied to each node.
421      */

422     private static <T> void processBreadthFirst(TreeAbstraction<T> tree,
423             T object, UnaryFunction f) {
424         f.compute(object);
425         for (int i = 0; i < tree.getChildCount(object); i++) {
426             processBreadthFirst(tree, tree.getChild(object, i), f);
427         }
428     }
429
430     /**
431      * Computes a sum of an array.
432      *
433      * @param values array of values
434      * @return sum of the values
435      */

436     public static long sum(long[] values) {
437         long r = 0;
438         for (int i = 0; i < values.length; i++) {
439             r += values[i];
440         }
441         return r;
442     }
443     
444
445     /**
446      * For debug purposes.
447      * Converts an array to a String.
448      *
449      * @param objs an array with objects
450      * @return string with format [obj1, obj2, ...]
451      */

452     public static String JavaDoc toString(Object JavaDoc[] objs) {
453         StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
454         sb.append("[");
455         for (Object JavaDoc a: objs) {
456             if (sb.length() != 1)
457                 sb.append(", ");
458             sb.append(a);
459         }
460         sb.append("]");
461         return sb.toString();
462     }
463     
464     /**
465      * Searches for an element using ==.
466      *
467      * @param values list of values
468      * @param value a value
469      * @return index of the value or -1
470      */

471     public static<T> int identityIndexOf(List JavaDoc<T> values, T value) {
472         for (int i = 0; i < values.size(); i++) {
473             if (values.get(i) == value)
474                 return i;
475         }
476         return -1;
477     }
478     
479     /**
480      * DEBUG:
481      *
482      * Dumps the hierarchy of class loaders.
483      *
484      * @param cl a class loader or null
485      *
486     public static void dumpClassLoaders(ClassLoader cl) {
487         while (cl != null) {
488             UTUtils.LOGGER.fine(cl.getClass().getName() +
489                     " " + cl.toString()); // NOI18N
490             cl = cl.getParent();
491         }
492     }*/

493 }
494
Popular Tags