KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > xml > schema > refactoring > ui > QueryUtilities


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.schema.refactoring.ui;
21
22 import java.awt.Color JavaDoc;
23 import java.awt.Image JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collections JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.regex.Matcher JavaDoc;
29 import java.util.regex.Pattern JavaDoc;
30 import javax.swing.text.StyledDocument JavaDoc;
31 import org.netbeans.api.project.FileOwnerQuery;
32 import org.netbeans.api.project.Project;
33 import org.netbeans.api.project.ProjectUtils;
34 import org.netbeans.api.project.SourceGroup;
35 import org.netbeans.modules.xml.nbprefuse.AnalysisConstants;
36 import org.netbeans.modules.xml.schema.model.Schema;
37 import org.netbeans.modules.xml.schema.model.SchemaComponent;
38 import org.netbeans.modules.xml.schema.model.SchemaModel;
39 import org.netbeans.modules.xml.schema.model.visitor.FindUsageVisitor;
40 import org.netbeans.modules.xml.schema.model.visitor.Preview;
41 import org.netbeans.modules.xml.xam.Component;
42 import org.netbeans.modules.xml.xam.Model;
43 import org.netbeans.modules.xml.xam.NamedReferenceable;
44 import org.openide.ErrorManager;
45 import org.openide.filesystems.FileObject;
46 import org.openide.filesystems.Repository;
47 import org.openide.loaders.DataObject;
48 import org.openide.loaders.DataObjectNotFoundException;
49 import org.openide.nodes.AbstractNode;
50 import org.openide.nodes.Children;
51 import org.openide.text.CloneableEditorSupport;
52 import org.openide.text.Line;
53 import org.openide.text.NbDocument;
54 import org.openide.util.NbBundle;
55 import prefuse.data.Edge;
56 import prefuse.data.Graph;
57 import prefuse.data.Node;
58 import prefuse.util.ColorLib;
59
60 /**
61  *
62  * @author Jeri Lockhart
63  */

64 public abstract class QueryUtilities {
65     
66     /**
67      * Get all the files in the project for the SchemaModel
68      * @param model The SchemaModel that is contained in the project
69      * @param sourceGroup The source group, such as JavaProjectConstants.SOURCES_TYPE_JAVA
70      * or Sources.TYPE_GENERIC
71      * @return a List of SourceGroups
72      *
73      */

74     
75     public static List JavaDoc<SourceGroup> getProjectSourceGroups(final SchemaModel model,
76             final String JavaDoc sourceGroupName){
77         if (model == null || sourceGroupName == null){
78             return null;
79         }
80         List JavaDoc<SourceGroup>result = new ArrayList JavaDoc<SourceGroup>();
81         Project proj = getProject(model);
82         
83         List JavaDoc<String JavaDoc>sourceGroupTypeList = new ArrayList JavaDoc<String JavaDoc>();
84         sourceGroupTypeList.add(sourceGroupName);
85         
86         for(String JavaDoc type: sourceGroupTypeList){
87             SourceGroup[] srcGrps = ProjectUtils.getSources(proj).getSourceGroups(type);
88             if(srcGrps != null){
89                 for(SourceGroup srcGrp : srcGrps) {
90                     result.add(srcGrp);
91                 }
92             }
93         }
94         return result;
95     }
96     
97     /**
98      *
99      *
100      */

101     private static Project getProject(final Model model){
102         if (model == null ){
103             return null;
104         }
105         FileObject fileObj = (FileObject) model.getModelSource().getLookup().lookup(FileObject.class);
106         return FileOwnerQuery.getOwner(fileObj);
107         
108     }
109     
110     
111     
112     
113     /**
114      * Use FindUsageVisitor to get the usages Preview for a Named
115      *
116      */

117     
118     @SuppressWarnings JavaDoc("unchecked")
119     public static Preview getUsagesPreview(Schema schema, NamedReferenceable ref){
120         FindUsageVisitor usage = new FindUsageVisitor();
121         return usage.findUsages(Collections.singletonList
122                 (schema), ref);
123         
124     }
125     
126     /**
127      * Creates an AbstractNode with the given label
128      * with Children.SortedArray and a String comparator
129      * Used by Analysis modules to create category container
130      * nodes for Global Complex Types, Global Elements, etc
131      *
132      *
133      */

134     public static AbstractNode createCategoryNode(AnalysisConstants.GlobalTypes type) {
135         Children.SortedArray children = new Children.SortedArray();
136         children.setComparator(new NodeComparator());
137         AbstractNode catNode = new AbstractNode(children) {
138             org.openide.nodes.Node node = null;
139             private org.openide.nodes.Node getDelegateNode() {
140                 if(node==null) {
141                     try {
142                         node = DataObject.find(Repository.getDefault().
143                                 getDefaultFileSystem().getRoot()).getNodeDelegate();
144                     } catch (DataObjectNotFoundException ex) {
145                     }
146                 }
147                 return node;
148             };
149             public Image JavaDoc getIcon(int type) {
150                 org.openide.nodes.Node n = getDelegateNode();
151                 return n!=null?n.getIcon(type):super.getIcon(type);
152             }
153             public Image JavaDoc getOpenedIcon(int type) {
154                 org.openide.nodes.Node n = getDelegateNode();
155                 return n!=null?n.getOpenedIcon(type):super.getOpenedIcon(type);
156             }
157         };
158         String JavaDoc label = null;
159         switch(type){
160             case COMPLEX_TYPE:
161                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalComplexTypes");
162                 break;
163             case SIMPLE_TYPE:
164                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalSimpleTypes");
165                 break;
166             case PRIMITIVE:
167                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_Primitives");
168                 break;
169             case ELEMENT:
170                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalElements");
171                 break;
172             case GROUP:
173                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalGroups");
174                 break;
175             case ATTRIBUTE:
176                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalAttributes");
177                 break;
178             case ATTRIBUTE_GROUP:
179                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_GlobalAttributeGroups");
180                 break;
181             case BASE_COMPLEX_TYPES:
182                 label = NbBundle.getMessage(QueryUtilities.class,"LBL_Global_ComplexTypes_With_Derivations");
183                 break;
184         }
185         
186         catNode.setName(label);
187         return catNode;
188     }
189     
190     
191     /**
192      * Returns a color palette of given size that cycles through
193      * the hues of the HSB (Hue/Saturation/Brightness) color space.
194      * @param size the size of the color palette
195      * @param s the saturation value to use
196      * @param b the brightness value to use
197      * @param huesToExclude null or an array of hues to exclude from palette
198      * @return the color palette
199      */

200     public static int[] getHSBPalette(int size, float s, float b,
201             AnalysisConstants.HSBHues[] huesToExclude) {
202         int[] cm = new int[size];
203         int igen = 0;
204         for ( int i=0; i<size; i++ ) {
205             float h = 0;
206             boolean goodHue = false;
207             while(goodHue == false){
208                 h = ((float)igen++)/(size);
209                 if (huesToExclude != null) {
210                     for (AnalysisConstants.HSBHues exH:huesToExclude){
211                         goodHue = !isInColorFamily(h, exH);
212                         if (goodHue == false){
213                             break;
214                         }
215                     }
216                 } else {
217                     goodHue = true;
218                 }
219             }
220             cm[i] = ColorLib.hsb(h,s,b);
221         }
222         return cm;
223     }
224     
225     private static boolean isInColorFamily(float h, AnalysisConstants.HSBHues hue){
226         if (hue == null){
227             return false;
228         }
229         return (h >= hue.low() && h <= hue.high());
230         
231     }
232
233     /**
234      * Print out of prefuse graph for debugging
235      *
236      *
237      */

238     public static void dumpGraph(Graph graph){
239 // if (graph == null){
240
// return;
241
// }
242
//
243
// Iterator nodeIt = graph.nodes();
244
// Iterator edgeIt = graph.edges();
245
// System.out.println("NODES:");
246
// while (nodeIt.hasNext()){
247
// Node node = Node.class.cast(nodeIt.next());
248
// System.out.println(" ");
249
// System.out.println(node.toString());
250
// System.out.println("Node Attributes:");
251
// Map map = node.getAttributes();
252
// Set entries = map.entrySet();
253
// for (Iterator i = entries.iterator(); i.hasNext();){
254
// Entry entry = Entry.class.cast(i.next());
255
// System.out.println(entry.getKey() + ": " + entry.getValue());
256
// }
257
// Iterator nodeEdgesIt = node.edges();
258
// while(nodeEdgesIt.hasNext()){
259
// Edge edge = Edge.class.cast(nodeEdgesIt.next());
260
// System.out.println("First node: " + edge.getSourceNode().toString()
261
// + " Second node: " + edge.getTargetNode().toString()
262
// + " isDirected: " + edge.isDirected()
263
// );
264
// }
265
// }
266
// System.out.println("EDGES:");
267
// while (edgeIt.hasNext()){
268
// Edge edge = Edge.class.cast(edgeIt.next());
269
// System.out.println(" ");
270
// System.out.println(edge.toString());
271
// System.out.println("Edge Attributes:");
272
// Map map = edge.getAttributes();
273
// Set entries = map.entrySet();
274
// for (Iterator i = entries.iterator(); i.hasNext();){
275
// Entry entry = Entry.class.cast(i.next());
276
// System.out.println(entry.getKey() + ": " + entry.getValue());
277
// }
278
// System.out.println("First Node: " + edge.getSourceNode().toString());
279
// System.out.println("Second Node: " + edge.getTargetNode().toString());
280
// }
281
//
282
}
283     
284     /**
285      * @return a trimmed snippet of XML from the 1st line of the Schema Component
286      * @param sc a Schema Component
287      *
288      */

289     public static String JavaDoc getTextForSchemaComponent(final Component comp){
290         SchemaComponent sc = null;
291         if (comp instanceof SchemaComponent){
292             sc = SchemaComponent.class.cast(comp);
293         }
294         if (sc == null){
295             return ""; //NOI18N
296
}
297         // TODO - if the line doesn't contain the target (query component name) string, keep searcing subsequent lines
298
DataObject dobj = null;
299         try {
300             dobj = DataObject.find((FileObject) sc.getModel().getModelSource().getLookup().lookup(FileObject.class));
301         } catch (DataObjectNotFoundException ex) {
302             ErrorManager.getDefault().notify(ex);
303         }
304         CloneableEditorSupport editor = (CloneableEditorSupport)dobj.getCookie(org.openide.cookies.EditorCookie.class);
305         Line.Set s =editor.getLineSet();
306         StyledDocument JavaDoc doc = editor.getDocument();
307         
308         int position = (int)sc.findPosition();
309         int line = NbDocument.findLineNumber(doc, position);
310         int col = NbDocument.findLineColumn(doc, position);
311         Line xmlLine = s.getCurrent(line);
312         String JavaDoc nodeLabel = xmlLine.getText().trim();
313         // substitute xml angle brackets <> for &lt; and &gt;
314
Pattern JavaDoc lt = Pattern.compile("<"); //NOI18N
315
Matcher JavaDoc mlt = lt.matcher(nodeLabel);
316         nodeLabel = mlt.replaceAll("&lt;"); //NOI18N
317
Pattern JavaDoc gt = Pattern.compile(">"); //NOI18N
318
Matcher JavaDoc mgt = gt.matcher(nodeLabel);
319         nodeLabel = mgt.replaceAll("&gt;"); //NOI18N
320
return boldenRefOrType(nodeLabel);
321     }
322     
323     // TODO get xml snippet for line that contains the
324
// query component name
325
/**
326      * If the label contains ref= or type=
327      * the substring containing the named portion of the attribute
328      * will be surrounded with html bold tags
329      * e.g.,
330      * input param <xsd:element ref="comment" minOccurs="0"/>
331      * return <xsd:element ref="<b>comment</b>" minOccurs="0"/>
332      *
333      *
334      */

335     private static String JavaDoc boldenRefOrType(String JavaDoc label){
336         // find index of type or ref
337
// find 1st occurence of " from index
338
// find 1st occurence of : after ", if any
339
// insert <b>
340
// find closing "
341
// insert </b>
342
int it = label.indexOf(" type"); //NOI18N
343
if (it < 0){
344             it = label.indexOf(" ref"); //NOI18N
345
}
346         if (it < 0){
347             // no type or ref found
348
return label;
349         }
350         int iq1 = label.indexOf('"',it);
351         if (iq1 < it){
352             // no begin quote
353
return label;
354         }
355         int ic = label.indexOf(':',iq1);
356 // if (ic < iq1){
357
// // no colon
358
// }
359
int iq2 = label.indexOf('"', iq1+1);
360         if (iq2 < iq1 || ic > iq2){
361             // couldn't find closing quote for tag
362
return label;
363         }
364         int ib1 = -1;
365         if (ic > -1){
366             ib1 = ic+1;
367         } else {
368             ib1 = iq1+1;
369         }
370         StringBuffer JavaDoc l = new StringBuffer JavaDoc(label);
371         l.insert(ib1,"<b>");
372         // the close quote has now been pushed right 3 spaces
373
l.insert(iq2+3,"</b>");
374         return l.toString();
375         
376     }
377     
378     
379     /**
380      * An array of ToolTipLine instances can be passed to
381      * GraphUtilities.createHTMLToolTip()
382      * ToolTipLine contains the text, the font size as a percentage of the default size,
383      * the horizontal alignment (center, left, or right), and the font color.
384      *
385      *
386      */

387     public static class ToolTipLine {
388         public enum HorizontalAlignment {
389             CENTER("center"), // NOI18N
390
LEFT("left"), // NOI18N
391
RIGHT("right"); // NOI18N
392

393             private final String JavaDoc name;
394             HorizontalAlignment(String JavaDoc name) {
395                 this.name = name;
396             }
397             public String JavaDoc toString() { return name; }
398         }
399         private String JavaDoc text =""; //NOI18N
400
private int fontSizePercentage = 100;
401         private int rgbColor = Color.BLACK.getRGB();
402         private HorizontalAlignment hAlign = HorizontalAlignment.CENTER;
403         public ToolTipLine(String JavaDoc text, int fontSizePercentage, int rgbColor, HorizontalAlignment hAlign){
404             
405             this.text = text;
406             this.fontSizePercentage = fontSizePercentage;
407             this.rgbColor = rgbColor;
408             this.hAlign = hAlign;
409         }
410         
411         
412         public ToolTipLine(String JavaDoc text, int rgbColor){
413             this.text = text;
414             this.rgbColor = rgbColor;
415         }
416         
417         
418         public ToolTipLine(String JavaDoc text){
419             this.text = text;
420         }
421         
422         public String JavaDoc getHorizontalAlignmentAsString() {
423             return this.hAlign.toString();
424         }
425         
426         public String JavaDoc getText() {
427             return " " + this.text + " "; //NOI18N
428
}
429         
430         public String JavaDoc getFontSizePercentageAsString() {
431             return String.valueOf(fontSizePercentage);
432         }
433         
434         
435         // example return value "(145,123,000)"
436
public String JavaDoc getColorAsRGBString() {
437             Color JavaDoc color = new Color JavaDoc(rgbColor);
438             StringBuffer JavaDoc str = new StringBuffer JavaDoc();
439             str.append("("); //NOI18N
440
str.append(String.valueOf(color.getRed()));
441             str.append(","); //NOI18N
442
str.append(String.valueOf(color.getGreen()));
443             str.append(","); //NOI18N
444
str.append(String.valueOf(color.getBlue()));
445             str.append(")"); //NOI18N
446
return str.toString();
447         }
448         
449         
450     }
451 }
452
453
Popular Tags