KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > refactoring > ui > util > AnalysisUtilities


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 package org.netbeans.modules.xml.refactoring.ui.util;
21
22 import java.awt.Color JavaDoc;
23 import java.awt.Image JavaDoc;
24 import java.beans.BeanInfo JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import javax.swing.tree.TreeModel JavaDoc;
30 import org.netbeans.modules.refactoring.spi.ui.UI;
31 import org.netbeans.modules.xml.nbprefuse.AnalysisConstants;
32 import org.netbeans.modules.xml.refactoring.CannotRefactorException;
33 import org.netbeans.modules.xml.refactoring.DeleteRequest;
34 import org.netbeans.modules.xml.refactoring.FileRenameRequest;
35 import org.netbeans.modules.xml.refactoring.RefactorRequest;
36 import org.netbeans.modules.xml.refactoring.RefactoringManager;
37 import org.netbeans.modules.xml.refactoring.RenameRequest;
38 import org.netbeans.modules.xml.refactoring.spi.UIHelper;
39 import org.netbeans.modules.xml.refactoring.ui.ModelProvider;
40 import org.netbeans.modules.xml.refactoring.ui.j.spi.ui.RenameRefactoringUI;
41 import org.netbeans.modules.xml.refactoring.ui.j.ui.CheckNode;
42 import org.netbeans.modules.xml.refactoring.ui.ReferenceableProvider;
43 import org.netbeans.modules.xml.refactoring.ui.j.spi.ui.DeleteRefactoringUI;
44 import org.netbeans.modules.xml.refactoring.ui.j.spi.ui.FileRenameRefactoringUI;
45 import org.netbeans.modules.xml.refactoring.ui.j.spi.ui.RefactoringUI;
46 import org.netbeans.modules.xml.refactoring.ui.j.ui.RefactoringPanel;
47 import org.netbeans.modules.xml.refactoring.ui.views.WhereUsedView;
48 import org.netbeans.modules.xml.xam.Component;
49 import org.netbeans.modules.xml.xam.Model;
50 import org.netbeans.modules.xml.xam.Nameable;
51 import org.netbeans.modules.xml.xam.Named;
52 import org.netbeans.modules.xml.xam.Referenceable;
53 import org.openide.DialogDisplayer;
54 import org.openide.ErrorManager;
55 import org.openide.NotifyDescriptor;
56 import org.openide.filesystems.FileObject;
57 import org.openide.filesystems.FileUtil;
58 import org.openide.loaders.DataObject;
59 import org.openide.loaders.DataObjectNotFoundException;
60 import org.openide.text.CloneableEditorSupport;
61 import org.openide.util.NbBundle;
62 import org.openide.windows.TopComponent;
63 import prefuse.Visualization;
64 import prefuse.data.Edge;
65 import prefuse.data.Graph;
66 import prefuse.data.Node;
67 import prefuse.data.expression.Predicate;
68 import prefuse.data.expression.parser.ExpressionParser;
69 import prefuse.util.ColorLib;
70 import prefuse.visual.EdgeItem;
71 import prefuse.visual.NodeItem;
72
73 /**
74  *
75  * @author Jeri Lockhart
76  */

77 public abstract class AnalysisUtilities {
78     
79
80     public static final String JavaDoc WSDL_MIME_TYPE = "text/xml-wsdl"; // NOI18N
81

82     /**
83      * @param fobj a FileObject
84      * @returns Image java.awt.Image for the FileObject
85      *
86      */

87     public static Image JavaDoc getImage(FileObject fobj){
88         try {
89             return DataObject.find(fobj).getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16);
90         } catch (DataObjectNotFoundException ex) {
91             ErrorManager.getDefault().notify(ex);
92         }
93         return null;
94     }
95     
96     
97     
98     /**
99      *
100      *
101      */

102     public static FileObject getFileObject(final Component xamComp){
103         return (FileObject)xamComp.getModel().getModelSource().getLookup().lookup(FileObject.class);
104     }
105     
106     /**
107      * Find the first CheckNode in the tree model that has the passed user object
108      * @param model the TreeModel
109      * @param object the user object
110      * @returns CheckNode the check node that contains the user object, or null
111      * if none is found
112      *
113      */

114     public static CheckNode findCheckNode(TreeModel JavaDoc model, Object JavaDoc userObject){
115         if (model == null || userObject == null){
116             return null;
117         }
118         CheckNode root = (CheckNode)model.getRoot();
119         if (root.getUserObject() == userObject){
120             return root;
121         }
122         return processChildren(root, userObject);
123         
124     }
125     
126     private static CheckNode processChildren(CheckNode node, Object JavaDoc userObject){
127         Enumeration JavaDoc en = node.children();
128         while (en.hasMoreElements()){
129             CheckNode child = (CheckNode)en.nextElement();
130             Object JavaDoc currUserObject = child.getUserObject();
131             if (currUserObject == userObject){
132                 return child;
133             }
134             return processChildren(child, userObject);
135         }
136         return null;
137     }
138     
139     /**
140      * Returns a color palette of given size that cycles through
141      * the hues of the HSB (Hue/Saturation/Brightness) color space.
142      * @param size the size of the color palette
143      * @param s the saturation value to use
144      * @param b the brightness value to use
145      * @param huesToExclude null or an array of hues to exclude from palette
146      * @return the color palette
147      */

148     public static int[] getHSBPalette(int size, float s, float b,
149             AnalysisConstants.HSBHues[] huesToExclude) {
150         int[] cm = new int[size];
151         int igen = 0;
152         for ( int i=0; i<size; i++ ) {
153             float h = 0;
154             boolean goodHue = false;
155             while(goodHue == false){
156                 h = ((float)igen++)/(size);
157                 if (huesToExclude != null) {
158                     for (AnalysisConstants.HSBHues exH:huesToExclude){
159                         goodHue = !isInColorFamily(h, exH);
160                         if (goodHue == false){
161                             break;
162                         }
163                     }
164                 } else {
165                     goodHue = true;
166                 }
167             }
168             cm[i] = ColorLib.hsb(h,s,b);
169         }
170         return cm;
171     }
172     
173     private static boolean isInColorFamily(float h, AnalysisConstants.HSBHues hue){
174         if (hue == null){
175             return false;
176         }
177         return (h >= hue.low() && h <= hue.high());
178         
179     }
180     
181     /**
182      * If there is only one file node, expand it
183      * otherwise, collapse them
184      * When a file node is expanded, all the schema component nodes
185      * in the file are shown. The edge from the file node to the
186      * query node is hidden.
187      *
188      * When a file node is collapsed, all the schema component nodes
189      * in the file are hidden. The edge from the file node to the query
190      * node is shown.
191      *
192      *
193      */

194     public static void expandCollapseFileNodes(List JavaDoc<NodeItem> fileNodes){
195         Predicate p = null;
196         if (fileNodes == null || fileNodes.size() < 1 || fileNodes.get(0) == null){
197             return;
198         }
199         Visualization vis = fileNodes.get(0).getVisualization();
200         
201         if (fileNodes.size() == 1){
202             NodeItem n = fileNodes.get(0);
203             n.setBoolean(AnalysisConstants.IS_EXPANDED, true);
204             p = (Predicate)
205             ExpressionParser.parse("["+AnalysisConstants.FILE_GROUP+"] = " + //NOI18N
206
n.getInt(AnalysisConstants.FILE_NODE_FILE_GROUP));
207             vis.setVisible(AnalysisConstants.GRAPH_GROUP, p, true);
208             setFileEdgeVisible(n, false);
209             
210         } else {
211             for(NodeItem n:fileNodes){
212                 n.setBoolean(AnalysisConstants.IS_EXPANDED, false);
213                 p = (Predicate)
214                 ExpressionParser.parse("["+AnalysisConstants.FILE_GROUP+"] = " + //NOI18N
215
n.getInt(AnalysisConstants.FILE_NODE_FILE_GROUP));
216                 vis.setVisible(AnalysisConstants.GRAPH_GROUP, p, false);
217                 setFileEdgeVisible(n, true);
218             }
219         }
220     }
221     
222     /**
223      * Set the edge between the file node and query node
224      * visible or not visible
225      *
226      *
227      */

228     private static void setFileEdgeVisible(final NodeItem fileNode, boolean visible){
229         Iterator JavaDoc outEdges = fileNode.outEdges();
230         while(outEdges.hasNext()){
231             EdgeItem edge = EdgeItem.class.cast(outEdges.next());
232             if (edge.getString(AnalysisConstants.EDGE_TYPE).equals(
233                     AnalysisConstants.FILE_EDGE_TYPE)){
234                 edge.setVisible(visible);
235             }
236         }
237     }
238     
239     /**
240      * create String using HTML and CSS style tag. Example:
241      *"<html>
242      * <head>
243      * </head>
244      * <body>
245      * <p style='color: rgb(169,205,255);
246      * text-align:center;
247      * font-size:130%'>
248      * This is the top line of the tooltip
249      * </p>
250      * <p style='color: rgb(169,169,169);
251      * text-align:center;
252      * font-size:130%'>
253      * This is the second line of the tooltip.
254      * </p>
255      * </body>
256      * </html>"
257      */

258     
259     public static String JavaDoc createHTMLToolTip(ToolTipLine[] lines){
260         if (lines == null){
261             return null;
262         }
263         StringBuffer JavaDoc tooltip = new StringBuffer JavaDoc();
264         tooltip.append("<html><head></head><body>");
265         for (ToolTipLine l:lines) {
266             if (l == null){
267                 continue;
268             }
269             tooltip.append("<p style='color: rgb");
270             tooltip.append(l.getColorAsRGBString());
271             tooltip.append(";text-align:");
272             tooltip.append(l.getHorizontalAlignmentAsString());
273             tooltip.append(";font-size:");
274             tooltip.append(l.getFontSizePercentageAsString());
275             tooltip.append("%'>");
276             tooltip.append(l.getText());
277             tooltip.append("</p>");
278         }
279         tooltip.append("</body></html>");
280         return tooltip.toString();
281     }
282     
283     
284     /**
285      * Print out of prefuse graph for debugging
286      *
287      *
288      */

289     public static void dumpGraph(Graph graph){
290         if (graph == null){
291             return;
292         }
293         
294         Iterator JavaDoc nodeIt = graph.nodes();
295         Iterator JavaDoc edgeIt = graph.edges();
296         System.out.println("NODES:");
297         while (nodeIt.hasNext()){
298             Node node = Node.class.cast(nodeIt.next());
299             System.out.println(" ");
300             System.out.println(node.toString());
301 // System.out.println("Node Attributes:");
302
// Map map = node.getAttributes();
303
// Set entries = map.entrySet();
304
// for (Iterator i = entries.iterator(); i.hasNext();){
305
// Entry entry = Entry.class.cast(i.next());
306
// System.out.println(entry.getKey() + ": " + entry.getValue());
307
// }
308
Iterator JavaDoc nodeEdgesIt = node.edges();
309             while(nodeEdgesIt.hasNext()){
310                 Edge edge = Edge.class.cast(nodeEdgesIt.next());
311                 System.out.println("First node: " + edge.getSourceNode().toString()
312                 + " Second node: " + edge.getTargetNode().toString()
313                 + " isDirected: " + edge.isDirected()
314                 );
315             }
316         }
317         System.out.println("EDGES:");
318         while (edgeIt.hasNext()){
319             Edge edge = Edge.class.cast(edgeIt.next());
320             System.out.println(" ");
321             System.out.println(edge.toString());
322 // System.out.println("Edge Attributes:");
323
// Map map = edge.getAttributes();
324
// Set entries = map.entrySet();
325
// for (Iterator i = entries.iterator(); i.hasNext();){
326
// Entry entry = Entry.class.cast(i.next());
327
// System.out.println(entry.getKey() + ": " + entry.getValue());
328
// }
329
System.out.println("First Node: " + edge.getSourceNode().toString());
330             System.out.println("Second Node: " + edge.getTargetNode().toString());
331         }
332         
333     }
334     
335     public static String JavaDoc getXmlFileType(FileObject fobj){
336         if (fobj.getExt().equals(AnalysisConstants.SCHEMA_FILE_EXTENSION)){
337             return AnalysisConstants.SCHEMA_FILE_TYPE;
338         }
339         if ( WSDL_MIME_TYPE.equals(FileUtil.getMIMEType(fobj))) {
340             return AnalysisConstants.WSDL_FILE_TYPE;
341         }
342         if (fobj.getExt().equals(AnalysisConstants.BPEL_FILE_EXTENSION)){
343             return AnalysisConstants.BPEL_FILE_TYPE;
344         }
345         return ""; //NOI18N
346
}
347     
348     public static String JavaDoc getXmlFileTypeDisplayName(String JavaDoc fileType){
349         if (fileType.equals(AnalysisConstants.SCHEMA_FILE_TYPE)){
350             return NbBundle.getMessage(AnalysisUtilities.class, "LBL_Schema");
351         }
352         
353         if (fileType.equals(AnalysisConstants.WSDL_FILE_TYPE)){
354             return NbBundle.getMessage(AnalysisUtilities.class, "LBL_WSDL");
355         }
356         
357         if (fileType.equals(AnalysisConstants.BPEL_FILE_TYPE)){
358             return NbBundle.getMessage(AnalysisUtilities.class, "LBL_BPEL");
359         }
360         return ""; //NOI18N
361

362     }
363     
364      
365     /**
366      * Check for the ReferenceableProvider Node.Cookie in node 0
367      *
368      * @returns NamedReferenceable instance of null if the node does
369      * not have the provider cookie
370      */

371     public static Referenceable getReferenceable(final org.openide.nodes.Node[] nodes) {
372         Referenceable referenceable = null;
373         ReferenceableProvider provider =
374                 (ReferenceableProvider)nodes[0].getCookie(ReferenceableProvider.class);
375         if (provider != null){
376             referenceable = provider.getReferenceable();
377         } else {
378             ModelProvider modelProvider = (ModelProvider)nodes[0].getCookie(ModelProvider.class);
379             if (modelProvider != null) {
380                 referenceable = modelProvider.getModel();
381             }
382         }
383         return referenceable;
384     }
385     
386     /**
387      * An array of ToolTipLine instances can be passed to
388      * GraphUtilities.createHTMLToolTip()
389      * ToolTipLine contains the text, the font size as a percentage of the default size,
390      * the horizontal alignment (center, left, or right), and the font color.
391      *
392      *
393      */

394     public static class ToolTipLine {
395         public enum HorizontalAlignment {
396             CENTER("center"), // NOI18N
397
LEFT("left"), // NOI18N
398
RIGHT("right"); // NOI18N
399

400             private final String JavaDoc name;
401             HorizontalAlignment(String JavaDoc name) {
402                 this.name = name;
403             }
404             public String JavaDoc toString() { return name; }
405         }
406         private String JavaDoc text =""; //NOI18N
407
private int fontSizePercentage = 100;
408         private int rgbColor = Color.BLACK.getRGB();
409         private HorizontalAlignment hAlign = HorizontalAlignment.CENTER;
410         public ToolTipLine(String JavaDoc text, int fontSizePercentage, int rgbColor, HorizontalAlignment hAlign){
411             
412             this.text = text;
413             this.fontSizePercentage = fontSizePercentage;
414             this.rgbColor = rgbColor;
415             this.hAlign = hAlign;
416         }
417         
418         
419         public ToolTipLine(String JavaDoc text, int rgbColor){
420             this.text = text;
421             this.rgbColor = rgbColor;
422         }
423         
424         
425         public ToolTipLine(String JavaDoc text){
426             this.text = text;
427         }
428         
429         public String JavaDoc getHorizontalAlignmentAsString() {
430             return this.hAlign.toString();
431         }
432         
433         public String JavaDoc getText() {
434             return " " + this.text + " "; //NOI18N
435
}
436         
437         public String JavaDoc getFontSizePercentageAsString() {
438             return String.valueOf(fontSizePercentage);
439         }
440         
441         
442         // example return value "(145,123,000)"
443
public String JavaDoc getColorAsRGBString() {
444             Color JavaDoc color = new Color JavaDoc(rgbColor);
445             StringBuilder JavaDoc str = new StringBuilder JavaDoc();
446             str.append("("); //NOI18N
447
str.append(String.valueOf(color.getRed()));
448             str.append(","); //NOI18N
449
str.append(String.valueOf(color.getGreen()));
450             str.append(","); //NOI18N
451
str.append(String.valueOf(color.getBlue()));
452             str.append(")"); //NOI18N
453
return str.toString();
454         }
455         
456         
457     }
458
459     public static String JavaDoc getName(Referenceable target) {
460         if (target instanceof Model JavaDoc) {
461             FileObject fo = (FileObject) ((Model JavaDoc)target).getModelSource().getLookup().lookup(FileObject.class);
462             assert fo != null : "Target model does not contain FileObject in lookkup";
463             return fo.getName();
464         } else {
465             return ((Named)target).getName();
466         }
467     }
468     
469     public static org.openide.nodes.Node getDisplayNode(Referenceable ref) {
470         if (ref instanceof Model JavaDoc) {
471             return getUIHelper(ref).getDisplayNode((Model JavaDoc)ref);
472         } else {
473             return getUIHelper(ref).getDisplayNode((Component)ref);
474         }
475     }
476     
477     public static UIHelper getUIHelper(Referenceable component) {
478         return RefactoringManager.getInstance().getTargetComponentUIHelper(component);
479     }
480     
481     public static Object JavaDoc[] getChangeValues(RefactorRequest request) {
482         if (request instanceof RenameRequest) {
483             RenameRequest rr = (RenameRequest) request;
484             return new Object JavaDoc[] { rr.getOldName(), rr.getNewName() };
485         } else if (request instanceof FileRenameRequest) {
486             FileRenameRequest rr = (FileRenameRequest) request;
487             return new Object JavaDoc[] { rr.getOldFileName(), rr.getNewFileName() };
488         }
489         return new String JavaDoc[0];
490     }
491
492     /**
493      * Quiet and local rename refactoring.
494      */

495     public static void locallyRenameRefactor(Nameable target, String JavaDoc newName) {
496         RenameRequest request = new RenameRequest(target, newName);
497         request.setScopeLocal();
498         doQuietRefactor(request);
499     }
500     
501     /**
502      * Quietly execute the given refactoring request.
503      *
504      */

505     public static void doQuietRefactor(RefactorRequest request) {
506         try {
507             RefactoringManager.getInstance().execute(request, false);
508         } catch(IOException JavaDoc ex) {
509             String JavaDoc msg = ex.getMessage();
510             NotifyDescriptor nd = new NotifyDescriptor.Message(
511                 msg, NotifyDescriptor.ERROR_MESSAGE);
512             DialogDisplayer.getDefault().notify(nd);
513         } catch (CannotRefactorException cre) {
514             showRefactoringUI(request);
515         }
516     }
517     
518     public static void showRefactoringUI(RefactorRequest request) {
519         WhereUsedView wuv = new WhereUsedView(request.getTarget());
520        org.netbeans.modules.refactoring.spi.ui.RefactoringUI ui = null;
521         if (request instanceof FileRenameRequest) {
522             ui = new FileRenameRefactoringUI(wuv, (FileRenameRequest)request);
523         } else if (request instanceof RenameRequest) {
524             ui = new RenameRefactoringUI(wuv, (RenameRequest)request);
525         } else if (request instanceof DeleteRequest) {
526             ui = new DeleteRefactoringUI(wuv, (DeleteRequest) request);
527         } else {
528             throw new IllegalArgumentException JavaDoc("Unknown refactoring type!"); //NOI18N
529
}
530         TopComponent activetc = TopComponent.getRegistry().getActivated();
531         if (activetc instanceof CloneableEditorSupport.Pane) {
532             //new RefactoringPanel(ui, activetc);
533
UI.openRefactoringUI(ui, activetc);
534         } else {
535            // new RefactoringPanel(ui);
536
UI.openRefactoringUI(ui);
537         }
538     }
539 }
540
541
542
Popular Tags