KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > businesslogic > ireport > util > Misc


1 /*
2  * Copyright (C) 2005 - 2006 JasperSoft Corporation. All rights reserved.
3  * http://www.jaspersoft.com.
4  *
5  * Unless you have purchased a commercial license agreement from JasperSoft,
6  * the following license terms apply:
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as published by
10  * the Free Software Foundation.
11  *
12  * This program is distributed WITHOUT ANY WARRANTY; and without the
13  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14  * See the GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
18  * or write to:
19  *
20  * Free Software Foundation, Inc.,
21  * 59 Temple Place - Suite 330,
22  * Boston, MA USA 02111-1307
23  *
24  *
25  *
26  *
27  * Misc.java
28  *
29  * Created on 14 febbraio 2003, 16.35
30  *
31  */

32
33 package it.businesslogic.ireport.util;
34 import it.businesslogic.ireport.ConditionedStyle;
35 import it.businesslogic.ireport.CrosstabReportElement;
36 import it.businesslogic.ireport.IReportConnection;
37 import it.businesslogic.ireport.Report;
38 import it.businesslogic.ireport.Style;
39 import it.businesslogic.ireport.gui.ExpressionEditor;
40 import it.businesslogic.ireport.gui.MainFrame;
41 import it.businesslogic.ireport.gui.sheet.Tag;
42 import java.awt.*;
43 import java.awt.image.*;
44 import java.util.*;
45 import java.util.jar.*;
46 import java.net.*;
47 import java.io.*;
48 import javax.swing.JComboBox JavaDoc;
49 import javax.swing.JFileChooser JavaDoc;
50 import javax.swing.JOptionPane JavaDoc;
51 import javax.swing.UIDefaults JavaDoc;
52 import javax.swing.UIManager JavaDoc;
53 import org.apache.xerces.parsers.DOMParser;
54 import org.flexdock.docking.Dockable;
55 import org.flexdock.docking.DockingConstants;
56 import org.flexdock.docking.defaults.DefaultDockingStrategy;
57 import org.flexdock.view.View;
58 import org.w3c.dom.Document JavaDoc;
59 import org.w3c.dom.NamedNodeMap JavaDoc;
60 import org.w3c.dom.Node JavaDoc;
61 import org.w3c.dom.NodeList JavaDoc;
62 import org.xml.sax.SAXException JavaDoc;
63
64 /**
65  *
66  * @author Administrator
67  */

68 public class Misc {
69         public static final String JavaDoc[] special_chars= new String JavaDoc[]{
70                                     "&","&",
71                                     "\"",""",
72                                     "'","'",
73                                     "<","&lt;",
74                                     ">","&gt;"
75                                     };
76                                     /*
77                                         "&","&amp;",
78                                         "?","&aacute;",
79                                         "?","&acirc;",
80                                         "?","&aelig;",
81                                         "?","&agrave;",
82                                         "?","&aring;",
83                                         "?","&atilde;",
84                                         "?","&auml;",
85                                         "?","&ccedil;",
86                                         "?","&eacute;",
87                                         "?","&ecirc;",
88                                         "?","&egrave;",
89                                         "?","&eth;",
90                                         "?","&euml;",
91                                         ">","&gt;",
92                                         "?","&iacute;",
93                                         "?","&icirc;",
94                                         "?","&igrave;",
95                                         "?","&iuml;",
96                                         "<","&lt;",
97                                         "?","&ntilde;",
98                                         "?","&oacute;",
99                                         "?","&ocirc;",
100                                         "?","&ograve;",
101                                         "?","&oslash;",
102                                         "?","&otilde;",
103                                         "?","&ouml;",
104                                         "\"","&quot;",
105                                         "?","&szlig;",
106                                         "?","&thorn;",
107                                         "?","&uacute;",
108                                         "?","&ucirc;",
109                                         "?","&ugrave;",
110                                         "?","&uuml;",
111                                         "?","&yacute;",
112                                         "?","&yuml;",
113                                         "?","&#161;",
114                                         "?","&#170;",
115                                         "?","&#183;",
116                                         "?","&#162;",
117                                         "?","&#171;",
118                                         "?","&#184;",
119                                         "?","&#163;",
120                                         "?","&#174;",
121                                         "?","&#185;",
122                                         "?","&#164;",
123                                         "?","&#176;",
124                                         "?","&#186;",
125                                         "?","&#165;",
126                                         "?","&#177;",
127                                         "?","&#187;",
128                                         "?","&#166;",
129                                         "?","&#178;",
130                                         "?","&#188;",
131                                         "?","&#167;",
132                                         "?","&#179;",
133                                         "?","&#189;",
134                                         "?","&#168;",
135                                         "?","&#181;",
136                                         "?","&#190;",
137                                         "?","&#169;",
138                                         "?","&#182;",
139                                         "?","&#191;",
140                                         "?","&#172;",
141                                         "?","&#215;",
142                                         "?","&#247;",
143                                         "?","&#177;",
144                                         "?","&#183;",
145                                         "?","&#189;",
146                                         "?","&#171;",
147                                         "?","&#178;",
148                                         "?","&#185;",
149                                         "?","&#190;",
150                                         "?","&#172;",
151                                         "?","&#179;",
152                                         "?","&#187;",
153                                         "?","&#215;",
154                                         "?","&#176;",
155                                         "?","&#181;",
156                                         "?","&#188;",
157                                         "?","&#247;"};
158                                      */

159
160
161         /** Creates a new instance of Misc */
162         public Misc() {
163         }
164
165          public static String JavaDoc xmlEscape(String JavaDoc text)
166           {
167             if( text == null) return "";
168             int i=0;
169             String JavaDoc tmp = "";
170             for (i=0; i < special_chars.length; i+=2)
171             {
172               text = string_replace(special_chars[i+1], special_chars[i], text);
173               //text = string_replace(special_chars[i], special_chars[i+1], text);
174
}
175
176             return text;
177           }
178
179          /*
180         public static java.awt.Image loadImageFromResources(String filename) {
181                 try {
182                         ClassLoader cl = ClassLoader.getSystemClassLoader();
183                         //java.io.InputStream in = new java.io.FileInputStream( cl.getResource(filename).getPath() );
184                         java.io.InputStream in = cl.getResourceAsStream(filename);
185                         byte[] data = getBytesFromInputStream(in, in.available());
186                         return java.awt.Toolkit.getDefaultToolkit().createImage(data);
187                 } catch (Exception ex) {
188                         System.out.println("Exception loading resource: "+filename);
189                         //ex.getMessage();
190                         //ex.printStackTrace();
191                 }
192                 return null;
193         }
194         */

195         /** New version by Umberto Uderzo */
196         public static java.awt.Image JavaDoc loadImageFromResources(String JavaDoc filename) {
197                 try {
198                         return new javax.swing.ImageIcon JavaDoc( Misc.class.getResource( "/" + filename )).getImage();
199                 } catch (Exception JavaDoc ex) {
200                         System.out.println("Exception loading resource: " +filename);
201                 }
202                 return null;
203         }
204
205         /**
206          * Returns an array of bytes containing the bytecodes for
207          * the class represented by the InputStream
208          * @param in the inputstream of the class file
209          * @return the bytecodes for the class
210          * @exception java.io.IOException if the class cannot be read
211          */

212         private static byte[] getBytesFromInputStream(java.io.InputStream JavaDoc in, int length) throws java.io.IOException JavaDoc {
213                 java.io.DataInputStream JavaDoc din = new java.io.DataInputStream JavaDoc(in);
214                 byte[] bytecodes = new byte[length];
215                 try {
216                         din.readFully(bytecodes);
217                 } finally {
218                         if (din != null) din.close();
219                 }
220                 return bytecodes;
221         }
222
223         public static java.awt.image.BufferedImage JavaDoc loadBufferedImageFromResources(Component c,String JavaDoc filename) {
224
225                 try {
226                         Misc m = new Misc();
227                         java.awt.Image JavaDoc img = loadImageFromResources(filename);
228                         MediaTracker mt = new MediaTracker(c);
229                         mt.addImage(img,0);
230                         mt.waitForID(0);
231                         int width= img.getWidth(null);
232                         int height= img.getHeight(null);
233                         BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
234                         Graphics gg = bi.getGraphics();
235                         gg.drawImage(img, 0,0, null);
236                         gg.dispose();
237                         return bi;
238                 } catch (Exception JavaDoc ex){
239                         System.out.println(ex.toString());
240                 }
241                 return null;
242         }
243
244         public static void updateComboBox(javax.swing.JComboBox JavaDoc comboBox, Vector newItems) {
245                 updateComboBox(comboBox,newItems, false);
246         }
247         public static void updateComboBox(javax.swing.JComboBox JavaDoc comboBox, Vector newItems, boolean addNullEntry) {
248                 Object JavaDoc itemSelected = null;
249                 if (comboBox.getSelectedIndex() >=0 ) {
250                         itemSelected = comboBox.getSelectedItem();
251                 }
252
253                 comboBox.removeAllItems();
254                 boolean selected = false;
255                 boolean foundNullItem = false;
256                 Enumeration e = newItems.elements();
257                 while (e.hasMoreElements()) {
258                         Object JavaDoc item = e.nextElement();
259                         comboBox.addItem(item);
260                         if (item == itemSelected) {
261                                 selected = true;
262                                 comboBox.setSelectedItem(itemSelected);
263                         }
264                         if (item.equals("")) {
265                                 foundNullItem = true;
266                         }
267                 }
268
269                 if (addNullEntry) {
270                         if (!foundNullItem) comboBox.insertItemAt("", 0);
271                         if (!selected) comboBox.setSelectedItem("");
272                 }
273
274         }
275
276         /** Mthis method perform equals based on string rapresentation of objects
277          *
278          */

279         public static void updateStringComboBox(javax.swing.JComboBox JavaDoc comboBox, Vector newItems, boolean addNullEntry) {
280                 Object JavaDoc itemSelected = null;
281                 if (comboBox.getSelectedIndex() >=0 ) {
282                         itemSelected = comboBox.getSelectedItem()+"";
283                 }
284
285                 comboBox.removeAllItems();
286                 boolean selected = false;
287                 boolean foundNullItem = false;
288                 Enumeration e = newItems.elements();
289                 while (e.hasMoreElements()) {
290                         String JavaDoc item = ""+e.nextElement();
291                         comboBox.addItem(item);
292                         if (item.equals(itemSelected)) {
293                                 selected = true;
294                                 comboBox.setSelectedItem(itemSelected);
295                         }
296                         if (item.equals("")) {
297                                 foundNullItem = true;
298                         }
299                 }
300
301                 if (addNullEntry) {
302                         if (!foundNullItem) comboBox.insertItemAt("", 0);
303                         if (!selected) comboBox.setSelectedItem("");
304                 }
305
306         }
307
308
309         public static String JavaDoc nvl(Object JavaDoc obj, String JavaDoc def) {
310                 return (obj == null) ? def : obj.toString();
311         }
312
313         public static void centerFrame(java.awt.Component JavaDoc c) {
314                 java.awt.Toolkit JavaDoc tk = java.awt.Toolkit.getDefaultToolkit();
315                 c.setLocation((int)((tk.getScreenSize().getWidth()-c.getWidth())/2),
316                 (int)((tk.getScreenSize().getHeight()- c.getHeight())/2) );
317         }
318
319         /**
320          * Replace s2 with s1 in s3
321          **/

322         public static String JavaDoc string_replace(String JavaDoc s1, String JavaDoc s2, String JavaDoc s3) {
323                 String JavaDoc string="";
324                 string = "";
325
326                 if (s2 == null || s3 == null || s2.length() == 0) return s3;
327
328                 int pos_i = 0; // posizione corrente.
329
int pos_f = 0; // posizione corrente finale
330

331                 int len = s2.length();
332                 while ( (pos_f = s3.indexOf(s2, pos_i)) >= 0) {
333                         string += s3.substring(pos_i,pos_f)+s1;
334                         //+string.substring(pos+ s2.length());
335
pos_f = pos_i = pos_f + len;
336
337                 }
338
339                 string += s3.substring(pos_i);
340
341                 return string;
342         }
343
344         public static java.awt.Image JavaDoc loadImageFromFile(String JavaDoc path) {
345                 java.io.File JavaDoc file = new java.io.File JavaDoc(path);
346                 if (file.exists()) {
347                         java.awt.Toolkit JavaDoc tk = java.awt.Toolkit.getDefaultToolkit();
348                         java.awt.Image JavaDoc img = tk.createImage(path);
349                         try {
350                                 java.awt.MediaTracker JavaDoc mt = new java.awt.MediaTracker JavaDoc( new javax.swing.JPanel JavaDoc() );
351                                 mt.addImage(img,0);
352                                 mt.waitForID(0);
353                         } catch (Exception JavaDoc ex){
354                                 return null;
355                         }
356                         return img;
357                 }
358                 return null;
359         }
360
361
362
363         /**
364          * This method inserts a blank character between to consecutive
365          * newline characters if encoutered. Also appends a blank character at
366          * the beginning of the text, if the first character is a newline character
367          * and at the end of the text, if the last character is also a newline.
368          * This is useful when trying to layout the paragraphs.
369          * Thanks to Teodor Danciu for this this method (c) 2003 Teodor Danciu
370          */

371         public static String JavaDoc treatNewLineChars(String JavaDoc source) {
372                 String JavaDoc result = source;
373
374                 if (source != null && source.length() > 0) {
375                         StringBuffer JavaDoc sbuffer = new StringBuffer JavaDoc(source);
376
377                         // insert a blank character between every two consecutives
378
// newline characters
379
int offset = source.length() - 1;
380                         int pos = source.lastIndexOf("\n\n", offset);
381                         while (pos >= 0 && offset > 0) {
382                                 sbuffer = sbuffer.insert(pos + 1, " ");
383                                 offset = pos - 1;
384                                 pos = source.lastIndexOf("\n\n", offset);
385                         }
386
387                         // append a blank character at the and of the text
388
// if the last character is a newline character
389
if (sbuffer.charAt(sbuffer.length() - 1) == '\n') {
390                                 sbuffer.append(' ');
391                         }
392
393                         // append a blank character at the begining of the text
394
// if the first character is a newline character
395
if (sbuffer.charAt(0) == '\n') {
396                                 sbuffer.insert(0, ' ');
397                         }
398
399                         result = sbuffer.toString();
400                 }
401
402                 // remove this if you want to treat the tab characters in a special way
403
result = replaceTabWithBlank(result);
404
405                 return result;
406         }
407
408
409         /**
410          * Thanks to Teodor Danciu for this method (c) 2003 Teodor Danciu
411          */

412         public static String JavaDoc replaceTabWithBlank(String JavaDoc source) {
413                 String JavaDoc result = source;
414
415                 if (source != null && source.length() > 0) {
416                         StringBuffer JavaDoc sbuffer = new StringBuffer JavaDoc(source);
417
418                         int offset = 0;
419                         int pos = source.indexOf("\t", offset);
420                         while (pos >= 0) {
421                                 sbuffer.setCharAt(pos, ' ');
422                                 offset = pos + 1;
423                                 pos = source.indexOf("\t", offset);
424                         }
425
426                         result = sbuffer.toString();
427                 }
428
429                 return result;
430         }
431
432         public static String JavaDoc toHTML(String JavaDoc s) {
433                 s = Misc.string_replace("&gt;",">",s);
434                 s = Misc.string_replace("&lt;","<",s);
435                 s = Misc.string_replace("&nbsp;"," ",s);
436                 s = Misc.string_replace("&nbsp;&nbsp;&nbsp;&nbsp;","\t",s);
437                 s = Misc.string_replace("<br>", "\n", s);
438                 return s;
439         }
440
441         static public String JavaDoc getShortFileName(String JavaDoc filename) {
442                 if (filename.length() > 50) {
443                         java.io.File JavaDoc f = new java.io.File JavaDoc(filename);
444                         if (nvl(f.getParentFile(),"").length()>10) {
445                                 String JavaDoc dir = f.getParentFile().getPath()+java.io.File.separatorChar;
446
447                                 String JavaDoc shortDir = dir.substring(0,dir.indexOf( java.io.File.separatorChar)+1);
448                                 dir = dir.substring(dir.indexOf( java.io.File.separatorChar)+1);
449                                 if (dir.indexOf( java.io.File.separatorChar) > 0) {
450                                         shortDir += dir.substring(0, dir.indexOf( java.io.File.separatorChar)+1);
451                                 }
452                                 return shortDir + "..."+ java.io.File.separatorChar +
453                                 f.getName();
454                         }
455                 }
456
457                 return filename;
458
459         }
460
461
462         /**
463          * Thanx to Jackie Manning j.m@programmer.net for this method!!
464          */

465         public static String JavaDoc getJdbcTypeClass(java.sql.ResultSetMetaData JavaDoc rsmd, int t ) {
466                 String JavaDoc cls = "java.lang.Object";
467
468                 try {
469                     cls = rsmd.getColumnClassName(t);
470                     cls = getJRFieldType(cls);
471
472                 } catch (Exception JavaDoc ex)
473                 {
474                     // if getColumnClassName is not supported...
475
try {
476                         int type = rsmd.getColumnType(t);
477                         switch( type ) {
478                                 case java.sql.Types.TINYINT:
479                                 case java.sql.Types.BIT:
480                                         cls = "java.lang.Byte";
481                                         break;
482                                 case java.sql.Types.SMALLINT:
483                                         cls = "java.lang.Short";
484                                         break;
485                                 case java.sql.Types.INTEGER:
486                                         cls = "java.lang.Integer";
487                                         break;
488                                 case java.sql.Types.FLOAT:
489                                 case java.sql.Types.REAL:
490                                 case java.sql.Types.DOUBLE:
491                                 case java.sql.Types.NUMERIC:
492                                 case java.sql.Types.DECIMAL:
493                                         cls = "java.lang.Double";
494                                         break;
495                                 case java.sql.Types.CHAR:
496                                 case java.sql.Types.VARCHAR:
497                                         cls = "java.lang.String";
498                                         break;
499
500                                 case java.sql.Types.BIGINT:
501                                         cls = "java.lang.Long";
502                                         break;
503                                 case java.sql.Types.DATE:
504                                         cls = "java.util.Date";
505                                         break;
506                                 case java.sql.Types.TIME:
507                                         cls = "java.sql.Time";
508                                         break;
509                                 case java.sql.Types.TIMESTAMP:
510                                         cls = "java.sql.Timestamp";
511                                         break;
512                         }
513                     } catch (Exception JavaDoc ex2){
514                         ex2.printStackTrace();
515                     }
516                 }
517                 return cls;
518         }
519
520
521     /**
522      * Return the correct field type...
523      *
524      */

525     public static String JavaDoc getJRFieldType(String JavaDoc type)
526     {
527
528         if (type == null) return "java.lang.Object";
529
530         if (type.equals("java.lang.Boolean") || type.equals("boolean")) return "java.lang.Boolean";
531         if (type.equals("java.lang.Byte") || type.equals("byte")) return "java.lang.Byte";
532         if (type.equals("java.lang.Integer") || type.equals("int")) return "java.lang.Integer";
533         if (type.equals("java.lang.Long") || type.equals("long")) return "java.lang.Long";
534         if (type.equals("java.lang.Double") || type.equals("double")) return "java.lang.Double";
535         if (type.equals("java.lang.Float") || type.equals("float")) return "java.lang.Float";
536         if (type.equals("java.lang.Short") || type.equals("short")) return "java.lang.Short";
537         if (type.startsWith("[")) return "java.lang.Object";
538         /*
539         if (type.equals("java.util.Date") ||
540             type.equals("java.sql.Timestamp") ||
541             type.equals("java.io.InputStream") ||
542             type.equals("java.math.BigDecimal") ||
543             type.equals("java.lang.String") ||
544             type.equals("java.sql.Time")) return type;
545
546         return "java.lang.Object";
547         */

548         return type;
549     }
550
551
552
553         public static long getLastWriteTime(String JavaDoc filename) {
554                 try {
555                         java.io.File JavaDoc f = new java.io.File JavaDoc(filename);
556                         if (f.exists())
557                         {
558                             return f.lastModified();
559                         }
560                 } catch (Exception JavaDoc ex) {
561                         
562                 }
563                 return -1;
564         }
565
566         /**
567          *Method used to grab the Frame which is above this component in the hierarchy.
568          *This allows programmers to make any component the parent of any window or
569          *dialog easier.
570          *@param comp the component to get the Frame for
571          *@return the Frame above this component in the hierarchy
572          */

573         public static java.awt.Frame JavaDoc frameFromComponent(java.awt.Component JavaDoc parent) {
574                 java.awt.Frame JavaDoc f = (java.awt.Frame JavaDoc)javax.swing.SwingUtilities.getAncestorOfClass(java.awt.Frame JavaDoc.class, parent);
575                 return f;
576         }//end frameFromComponent
577
//ErtanO 12.03.2004
578
public static java.util.List JavaDoc getAvailablePLAF(){
579                 java.util.List JavaDoc l = new java.util.ArrayList JavaDoc();
580                 l.add("System");
581                 l.add("TinyLAF");
582                 l.add("TonicLAF");
583                 l.add("JGoodiesLAF-PlasticXP");
584                 l.add("JGoodiesLAF-Plastic");
585                 l.add("JGoodiesLAF-Plastic3D");
586                 l.add("JGoodiesLAF-ExtWindows");
587                 l.add("JGoodiesLAF-ExtWindows");
588         //l.add("KunststofLAF");
589

590                 javax.swing.UIManager.LookAndFeelInfo[] lfinfo = javax.swing.UIManager.getInstalledLookAndFeels();
591
592                 for (int i=0; i<lfinfo.length; ++i) {
593                         l.add( lfinfo[i].getName() );
594                 }
595
596                 return l;
597         }
598         public static void setPLAF(String JavaDoc s){
599                 try {
600                         
601                         if(s.equals("TinyLAF")) {
602                                 javax.swing.UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel");
603                         } else if(s.equals("TonicLAF")) {
604                                 javax.swing.UIManager.setLookAndFeel("com.digitprop.tonic.TonicLookAndFeel");
605                         } else if(s.equals("JGoodiesLAF-PlasticXP")) {
606                                 javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
607                         } else if(s.equals("JGoodiesLAF-Plastic")) {
608                                 javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticLookAndFeel");
609                         } else if(s.equals("JGoodiesLAF-Plastic3D")) {
610                                 javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
611                         } else if(s.equals("JGoodiesLAF-ExtWindows")) {
612                                 javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel");
613                         //} else if(s.equals("KunststofLAF")) {
614
// javax.swing.UIManager.setLookAndFeel("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
615
} else if(s.equals("System")) {
616                                 javax.swing.UIManager.setLookAndFeel( javax.swing.UIManager.getSystemLookAndFeelClassName() );
617
618                                 UIDefaults JavaDoc uiDefaults = UIManager.getDefaults();
619                                 Object JavaDoc obj = uiDefaults.get("Panel.background");
620                                 if (obj instanceof javax.swing.plaf.ColorUIResource JavaDoc)
621                                 {
622                                     javax.swing.plaf.ColorUIResource JavaDoc cr = (javax.swing.plaf.ColorUIResource JavaDoc)obj;
623                                     uiDefaults.put("Desktop.background", new javax.swing.plaf.ColorUIResource JavaDoc(cr.darker()));
624                 }
625                         } else {
626                                 javax.swing.UIManager.LookAndFeelInfo[] lfinfo = javax.swing.UIManager.getInstalledLookAndFeels();
627                                 for (int i=0; i<lfinfo.length; ++i) {
628                                         if (lfinfo[i].getName().equalsIgnoreCase( s )) {
629                                                 javax.swing.UIManager.setLookAndFeel( lfinfo[i].getClassName() );
630
631                                                 if (s.equals("Metal"))
632                                                 {
633                                                     if (MainFrame.getMainInstance().getProperties().getProperty("overrideDefaultFont","true").equals("true"))
634                                                     {
635
636                                                         String JavaDoc fontFamily = MainFrame.getMainInstance().getProperties().getProperty("overrideDefaultFontName", I18n.getString("defaultFont","Tahoma"));
637
638                                                         int fontSize = 11;
639                                                         try {
640                                                             fontSize = Integer.parseInt( MainFrame.getMainInstance().getProperties().getProperty("overrideDefaultFontSize","11"));
641                                                         } catch (Exception JavaDoc ex)
642                                                         {
643                                                             ex.printStackTrace();
644                                                         }
645                                                         String JavaDoc sNum = MainFrame.getMainInstance().getProperties().getProperty("overrideDefaultFontAttrs","0");
646                                                         if (sNum == null || !sNum.equals("1")) sNum = "0";
647                                                         int fontAttrs = Integer.parseInt(sNum);
648
649                                                         javax.swing.plaf.FontUIResource JavaDoc f = new javax.swing.plaf.FontUIResource JavaDoc(fontFamily,fontAttrs,fontSize);
650                                                         java.util.Enumeration JavaDoc keys = javax.swing.UIManager.getDefaults().keys();
651                                                         while (keys.hasMoreElements()) {
652                                                             Object JavaDoc key = keys.nextElement();
653                                                             Object JavaDoc value = javax.swing.UIManager.get (key);
654                                                             if (value instanceof javax.swing.plaf.FontUIResource JavaDoc)
655                                                             javax.swing.UIManager.put (key, f);
656                                                         }
657                                                     }
658                                                 }
659
660
661
662
663                                                 return;
664                                         }
665                                 }
666                         }
667                 } catch (Exception JavaDoc ex) {
668                         ex.printStackTrace();
669                 }
670         }
671
672         public static String JavaDoc getClassPath() {
673                 String JavaDoc cp = (String JavaDoc)System.getProperty("java.class.path");
674                 if (it.businesslogic.ireport.gui.MainFrame.getMainInstance() != null)
675                 {
676                     Vector cp_v = it.businesslogic.ireport.gui.MainFrame.getMainInstance().getClasspath();
677                     for (int i=0; i<cp_v.size(); ++i)
678                     {
679                         cp += File.pathSeparator + cp_v.elementAt(i);
680                     }
681                 }
682                 return cp;
683         }
684
685
686         /**
687          * Enumerates the resouces in a give package name.
688          * This works even if the resources are loaded from a jar file!
689          *
690          * Adapted from code by mikewse
691          * on the java.sun.com message boards.
692          * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
693          *
694          * @param packageName The package to enumerate
695          * @return A Set of Strings for each resouce in the package.
696          */

697         public static Set getResoucesInPackage(String JavaDoc packageName) throws IOException {
698                 String JavaDoc localPackageName;
699                 if( packageName.endsWith("/") ) {
700                         localPackageName = packageName;
701                 } else {
702                         localPackageName = packageName + '/';
703                 }
704
705                 ClassLoader JavaDoc cl = Misc.class.getClassLoader();
706                 if (MainFrame.getMainInstance() != null)
707                 {
708                     cl = MainFrame.getMainInstance().getReportClassLoader();
709                 }
710                 
711                 Enumeration dirEnum = cl.getResources( localPackageName );
712                 
713                 Set names = new HashSet();
714
715                 // Loop CLASSPATH directories
716
while( dirEnum.hasMoreElements() ) {
717                         URL resUrl = (URL) dirEnum.nextElement();
718                        
719                         // Pointing to filesystem directory
720
if ( resUrl.getProtocol().equals("file") ) {
721                             try {
722                               File dir = new File( resUrl.getFile() );
723                                 File[] files = dir.listFiles();
724                                 if ( files != null ) {
725                                         for( int i=0; i<files.length; i++ ) {
726                                                 File file = files[i];
727                                                 if ( file.isDirectory() )
728                                                         continue;
729                                                 names.add( localPackageName + file.getName() );
730                                         }
731                                 }
732                             } catch (Exception JavaDoc ex) {
733                                 ex.printStackTrace();
734                             }
735                             
736                                 // Pointing to Jar file
737
} else if ( resUrl.getProtocol().equals("jar") ) {
738                                 JarURLConnection jconn = (JarURLConnection) resUrl.openConnection();
739                                 JarFile jfile = jconn.getJarFile();
740                                 Enumeration entryEnum = jfile.entries();
741                                 while( entryEnum.hasMoreElements() ) {
742                                         JarEntry entry = (JarEntry) entryEnum.nextElement();
743                                         String JavaDoc entryName = entry.getName();
744                                         // Exclude our own directory
745
if ( entryName.equals(localPackageName) )
746                                                 continue;
747                                         String JavaDoc parentDirName = entryName.substring( 0, entryName.lastIndexOf('/')+1 );
748                                         if ( ! parentDirName.equals(localPackageName) )
749                                                 continue;
750                                         names.add( entryName );
751                                 }
752                         } else {
753                                 // Invalid classpath entry
754
}
755                 }
756
757                 return names;
758         }
759
760
761         /**
762          * Take a filename, strip out the extension and append the new extension
763          * newExtension = ".xyz" or "xyz"
764          * If filename is null, ".xyz" is returned
765          */

766         public static String JavaDoc changeFileExtension(String JavaDoc filename, String JavaDoc newExtension ) {
767                 if (!newExtension.startsWith(".")) newExtension = "."+newExtension;
768                 if (filename == null || filename.length()==0 ) {
769                         return newExtension;
770                 }
771
772                 int index = filename.lastIndexOf(".");
773                 if (index >= 0) {
774                         filename = filename.substring(0,index);
775                 }
776                 return filename += newExtension;
777         }
778
779
780         /**
781          * Take a string like _it_IT or it_IT or it
782          * and return the right locale
783          */

784         static public java.util.Locale JavaDoc getLocaleFromString( String JavaDoc localeName )
785     {
786         String JavaDoc language = "";
787         String JavaDoc country = "";
788         String JavaDoc variant = "";
789         Locale locale = Locale.getDefault();
790
791         if (localeName == null || localeName.length() == 0) return locale;
792         if (localeName.startsWith("_")) localeName = localeName.substring(1);
793         if (localeName.indexOf("_") > 0)
794         {
795             language = localeName.substring(0,localeName.indexOf("_"));
796             localeName = localeName.substring(localeName.indexOf("_")+1);
797
798             if (localeName.indexOf("_") > 0)
799             {
800                 country = localeName.substring(0,localeName.indexOf("_"));
801                 localeName = localeName.substring(localeName.indexOf("_")+1);
802
803                 if (localeName.indexOf("_") > 0)
804                 {
805                     variant = localeName.substring(0,localeName.indexOf("_"));
806                     localeName = localeName.substring(localeName.indexOf("_")+1);
807                 }
808                 else
809                 {
810                     variant = localeName;
811                 }
812             }
813             else
814             {
815                 country = localeName;
816             }
817         }
818         else
819         {
820             language = localeName;
821         }
822
823         locale = new Locale(language,country,variant);
824
825         return locale;
826     }
827
828
829         public static void setComboboxSelectedTagValue(javax.swing.JComboBox JavaDoc comboBox, String JavaDoc itemValue) {
830             for (int i=0; i<comboBox.getItemCount(); ++i)
831             {
832                 Object JavaDoc val = comboBox.getItemAt(i);
833                 if ( val instanceof it.businesslogic.ireport.gui.sheet.Tag)
834                 {
835                     if (((it.businesslogic.ireport.gui.sheet.Tag)val).getValue().equals(itemValue))
836                     {
837                         comboBox.setSelectedIndex( i );
838                         break;
839                     }
840                 }
841             }
842         }
843         
844
845         /**
846          * Return the named connection configured in iReport
847          * Return a java.sql.Connection;
848          */

849         public static java.sql.Connection JavaDoc getConnection(String JavaDoc name)
850         {
851             Vector v = MainFrame.getMainInstance().getConnections();
852             for (int i=0; i<v.size(); ++i)
853             {
854                 IReportConnection irc = (IReportConnection)v.get(i);
855                 if (irc.getName().equals(name))
856                 {
857                     return irc.getConnection();
858                 }
859             }
860
861             return null;
862         }
863
864         /**
865          * Return the named connection configured in iReport
866          * Return a net.sf.jasperreports.engine.getJRDataSource
867          */

868         public static net.sf.jasperreports.engine.JRDataSource getJRDataSource(String JavaDoc name)
869         {
870             Vector v = MainFrame.getMainInstance().getConnections();
871             for (int i=0; i<v.size(); ++i)
872             {
873                 IReportConnection irc = (IReportConnection)v.get(i);
874                 if (irc.getName().equals(name))
875                 {
876                     return irc.getJRDataSource();
877                 }
878             }
879
880             return null;
881         }
882
883         public static Vector loadStyleLibrary(String JavaDoc fileName)
884         {
885             Vector v = new Vector();
886             try {
887
888                 File f = new File(fileName);
889                 InputStream fis = null;
890
891                 if (!f.exists())
892                 {
893                     fis = Misc.class.getClassLoader().getResourceAsStream("it/businesslogic/ireport/res/defaultStyleLibrary.xml");
894                     fileName = ""+Misc.class.getClassLoader().getResource("it/businesslogic/ireport/res/defaultStyleLibrary.xml");
895                 }
896                 else
897                 {
898                     fis = new FileInputStream(f);
899                     fileName = "file:///"+fileName;
900                 }
901
902                 v.addAll( loadStyleLibrary( fis, fileName));
903             } catch (Exception JavaDoc ex)
904             {
905                 ex.printStackTrace();
906             }
907
908             return v;
909         }
910
911          public static Vector loadStyleLibrary(InputStream is, String JavaDoc filename)
912          {
913              Vector v = new Vector();
914              try {
915                  DOMParser parser = new DOMParser();
916                  org.xml.sax.InputSource JavaDoc input_sss = new org.xml.sax.InputSource JavaDoc(is);
917                  //input_sss.setSystemId(filename);
918
parser.parse( input_sss );
919
920                  Document JavaDoc document = parser.getDocument();
921                  Node JavaDoc node = document.getDocumentElement();
922
923
924                  NodeList JavaDoc list_child = node.getChildNodes();
925                  for (int ck=0; ck< list_child.getLength(); ck++) {
926                      Node JavaDoc styleNode = (Node JavaDoc)list_child.item(ck);
927                      if (styleNode.getNodeName() != null && styleNode.getNodeName().equals("style"))
928                      {
929                         Style s = readStyle(styleNode,null);
930                         v.add( s );
931                     }
932                  }
933              } catch (Exception JavaDoc ex)
934              {
935                  ex.printStackTrace();
936              }
937
938              return v;
939          }
940
941          /**
942           * If a ConditionedStyle, the style is interpreted like part of the tag conditionalStyle
943           */

944          public static it.businesslogic.ireport.Style readStyle(Node JavaDoc styleNode, ConditionedStyle cStyle)
945          {
946             Style style = new Style();
947             if (cStyle != null) style = cStyle;
948             NamedNodeMap JavaDoc nnm = styleNode.getAttributes();
949
950             for (int i=0; i<Style.JRXMLStyleAttributes.length; ++i)
951             {
952                  if ( nnm.getNamedItem(Style.JRXMLStyleAttributes[i]) != null) {
953                     style.getAttributes().put(Style.JRXMLStyleAttributes[i], nnm.getNamedItem(Style.JRXMLStyleAttributes[i]).getNodeValue());
954                  }
955             }
956
957             //conditionalStyle
958
// Check for description and expression...
959
NodeList JavaDoc children = styleNode.getChildNodes();
960             if (children != null) {
961                 for (int k=0; k< children.getLength(); k++) {
962                     Node JavaDoc nodeChild = (Node JavaDoc)children.item(k);
963                     if (nodeChild.getNodeType() == Node.ELEMENT_NODE && nodeChild.getNodeName().equals("conditionalStyle")) {
964                         ConditionedStyle childStyle = readConditionalStyle(nodeChild);
965                         style.getConditionedStyles().add(childStyle);
966                     }
967                 }
968             }
969
970             return style;
971          }
972
973          /**
974      * If a ConditionedStyle, the style is interpreted like part of the tag conditionalStyle
975      */

976     private static it.businesslogic.ireport.ConditionedStyle readConditionalStyle(Node JavaDoc styleNode)
977     {
978         ConditionedStyle style = new ConditionedStyle();
979
980         //conditionalStyle
981
// Check for description and expression...
982
NodeList JavaDoc children = styleNode.getChildNodes();
983         if (children != null) {
984             for (int k=0; k< children.getLength(); k++) {
985                 Node JavaDoc nodeChild = (Node JavaDoc)children.item(k);
986                 if (nodeChild.getNodeType() == Node.ELEMENT_NODE && nodeChild.getNodeName().equals("conditionExpression")) {
987                     style.setCondition(Report.readPCDATA(nodeChild));
988                 }
989                 else if (nodeChild.getNodeType() == Node.ELEMENT_NODE && nodeChild.getNodeName().equals("style")) {
990                     style = (ConditionedStyle)readStyle(nodeChild, style);
991                 }
992             }
993         }
994
995         return style;
996     }
997
998     public static void saveStyleLibrary(String JavaDoc filename, Vector styles)
999     {
1000        try {
1001        PrintWriter pw = new PrintWriter( new java.io.OutputStreamWriter JavaDoc( new java.io.FileOutputStream JavaDoc( filename ), "UTF8" )); //UTF8
1002

1003        pw.print("<?xml version=\"1.0\"?>");
1004        pw.println("<!-- iReport styles library -->");
1005        pw.println("<styles>");
1006
1007        writeXMLStyles(styles, pw, "\t");
1008        pw.println("</styles>");
1009
1010        pw.close();
1011
1012        } catch (Exception JavaDoc ex)
1013        {
1014            JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
1015                    I18n.getFormattedString( "messages.misc.errorSavingStyles",
1016                    "Error saving styles library: {0}",
1017                    new Object JavaDoc[]{ ex.getMessage() }) );
1018            ex.printStackTrace();
1019        }
1020    }
1021
1022
1023    private static void writeXMLStyles(Vector styles, java.io.PrintWriter JavaDoc pw, String JavaDoc tabs)
1024    {
1025
1026            Enumeration e = styles.elements();
1027            if (styles.size() > 0) pw.println("");
1028            while (e.hasMoreElements()) {
1029                it.businesslogic.ireport.Style style = (it.businesslogic.ireport.Style)e.nextElement();
1030
1031                String JavaDoc tabs2 = tabs;
1032                if (style instanceof ConditionedStyle)
1033                {
1034                    pw.println(tabs2 + "<conditionalStyle>");
1035                    tabs += "\t";
1036                    pw.print(tabs + "<conditionExpression");
1037                    pw.println(">" + Report.getCDATAString(((ConditionedStyle)style).getCondition() ,tabs2.length()+1) +"</conditionExpression>");
1038                 }
1039                pw.println(tabs + "<style ");
1040                for (int i=0; i<Style.JRXMLStyleAttributes.length; ++i)
1041                {
1042                    if ( style.getAttributes().containsKey(Style.JRXMLStyleAttributes[i]) &&
1043                         style.getAttributes().get( Style.JRXMLStyleAttributes[i] ) != null) {
1044                         Object JavaDoc obj = style.getAttributes().get(Style.JRXMLStyleAttributes[i]);
1045                         String JavaDoc value = ""+obj;
1046                         if (obj instanceof java.awt.Color JavaDoc)
1047                         {
1048                             value = Report.writeEncodedColor( (java.awt.Color JavaDoc)obj);
1049                         }
1050                         if (Style.JRXMLStyleAttributes[i].toLowerCase().endsWith("color") && value.startsWith("["))
1051                         {
1052                             // The color is in the form [r,g,b]...
1053
try {
1054                               value = Report.writeEncodedColor(it.businesslogic.ireport.gui.sheet.ColorSelectorPanel.parseColorString(value));
1055                             } catch (Exception JavaDoc ex)
1056                             {
1057                                 value="black";
1058                             }
1059                         }
1060                         if (Style.JRXMLStyleAttributes[i].equals("style"))
1061                         {
1062                             if (value == null || value.trim().length() == 0) continue;
1063                         }
1064                         pw.println(tabs + "\t" + Style.JRXMLStyleAttributes[i] + "=\"" + value +"\"");
1065                    }
1066                }
1067
1068                if (style.getConditionedStyles().size() == 0)
1069                {
1070                    pw.println(tabs + "/>");
1071                }
1072                else
1073                {
1074                    pw.println(tabs + ">");
1075                    writeXMLStyles(style.getConditionedStyles(), pw, tabs+"\t");
1076                    pw.println(tabs + "</style>");
1077                }
1078                if (style instanceof ConditionedStyle)
1079                {
1080                    pw.println(tabs2 + "</conditionalStyle>");
1081                }
1082            }
1083    }
1084
1085
1086     /**
1087     * Save the query asking for a file.
1088     * see saveSQLQuery(String query, Component c)
1089     */

1090    public static boolean saveSQLQuery(String JavaDoc query)
1091    {
1092         return saveSQLQuery(query, MainFrame.getMainInstance());
1093    }
1094    /**
1095     * Save the query asking for a file.
1096     * The optional component is used as parent for the file selection dialog
1097     * Default is the MainFrame
1098     */

1099    public static boolean saveSQLQuery(String JavaDoc query, Component c)
1100    {
1101            JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
1102            jfc.setFileFilter( new javax.swing.filechooser.FileFilter JavaDoc() {
1103            public boolean accept(java.io.File JavaDoc file) {
1104                String JavaDoc filename = file.getName().toLowerCase();
1105                return (filename.endsWith(".sql") || filename.endsWith(".txt") ||file.isDirectory()) ;
1106            }
1107            public String JavaDoc getDescription() {
1108                return "SQL query (*.sql, *.txt)";
1109            }
1110        });
1111
1112        if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) {
1113
1114                try {
1115
1116                    String JavaDoc fileName = jfc.getSelectedFile().getName();
1117                    if (fileName.indexOf(".") < 0)
1118                    {
1119                        fileName += ".sql";
1120                    }
1121
1122                    File f = new File( jfc.getSelectedFile().getParent(), fileName);
1123
1124                    FileWriter fw = new FileWriter(f);
1125                    fw.write( query );
1126                    fw.close();
1127
1128                    return true;
1129                } catch (Exception JavaDoc ex)
1130                {
1131                    JOptionPane.showMessageDialog(c,"Error saving the query: " + ex.getMessage(),I18n.getString("message.title.error","Error"),JOptionPane.ERROR_MESSAGE);
1132                    ex.printStackTrace();
1133                }
1134        }
1135
1136            return false;
1137    }
1138
1139    /**
1140     * See loadSQLQuery(Component c)
1141     */

1142    public static String JavaDoc loadSQLQuery()
1143    {
1144        return loadSQLQuery(MainFrame.getMainInstance());
1145    }
1146
1147    /**
1148     * Load the query asking for a file.
1149     * The optional component is used as parent for the file selection dialog
1150     * Default is the MainFrame
1151     */

1152    public static String JavaDoc loadSQLQuery(Component c)
1153    {
1154            JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
1155            jfc.setMultiSelectionEnabled(false);
1156            jfc.setFileFilter( new javax.swing.filechooser.FileFilter JavaDoc() {
1157            public boolean accept(java.io.File JavaDoc file) {
1158                String JavaDoc filename = file.getName().toLowerCase();
1159                return (filename.endsWith(".sql") || filename.endsWith(".txt") ||file.isDirectory()) ;
1160            }
1161            public String JavaDoc getDescription() {
1162                return "SQL query (*.sql, *.txt)";
1163            }
1164        });
1165
1166        if (jfc.showOpenDialog(c) == JFileChooser.APPROVE_OPTION) {
1167
1168                try {
1169
1170                    FileReader fr = new FileReader(jfc.getSelectedFile());
1171                    StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1172                    char[] cbuf = new char[1024];
1173                    int i = fr.read(cbuf);
1174                    while (i > 0)
1175                    {
1176                        sb.append( cbuf, 0, i);
1177                        i = fr.read(cbuf);
1178                    }
1179                    fr.close();
1180
1181                    return sb.toString();
1182                } catch (Exception JavaDoc ex)
1183                {
1184                    JOptionPane.showMessageDialog(c,"Error loading the query: " + ex.getMessage(),I18n.getString("message.title.error","Error"),JOptionPane.ERROR_MESSAGE);
1185                    ex.printStackTrace();
1186                }
1187        }
1188
1189            return null;
1190    }
1191    
1192    
1193    /**
1194     * Save the expressions list to the specified file...
1195     */

1196    public static boolean saveExpressionsList( Vector v, String JavaDoc xmlFile) {
1197        // Get the path of this class...
1198
// this.getClass().getResource("MainFrame");
1199
try {
1200            PrintWriter pw = new PrintWriter( new FileWriter(xmlFile) );
1201            // Find iReport configuration in the home directory...
1202
// 1. Save all properties using am XML style...
1203
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
1204            pw.println("<!-- iReport 2 expressions list - " + new Date() + " -->");
1205            pw.println("<!DOCTYPE iReportExpressionsList PUBLIC \"-//iReport/DTD iReport Configuration//EN\" \"http://ireport.sourceforge.net/dtds/iReportExpressionsList.dtd\">");
1206            pw.println("<iReportExpressionsList>");
1207
1208            Enumeration e = v.elements();
1209
1210            while (e.hasMoreElements()) {
1211                String JavaDoc exp = (String JavaDoc)e.nextElement();
1212                pw.println("\t<expression><![CDATA["+ exp +"]]></expression>");
1213            }
1214            pw.println("</iReportExpressionsList>");
1215            pw.close();
1216        } catch (Exception JavaDoc ex) {
1217            //ex.printStackTrace(s
1218
try {
1219                MainFrame.getMainInstance().logOnConsole("Error saving iReport file: "+xmlFile+"\n"+ex.getMessage()+"\n");
1220
1221            } catch (Exception JavaDoc exsx)
1222            {}
1223            return false;
1224        }
1225        try {
1226            MainFrame.getMainInstance().logOnConsole("iReport file "+ xmlFile + " successfully updated!\n");
1227        } catch (Exception JavaDoc ex)
1228        { }
1229        return true;
1230    }
1231    
1232    /**
1233     * Read the expressions list from the specified file...
1234     */

1235    public static Vector loadExpressionsList(String JavaDoc xmlFile) {
1236        File file = null;
1237        Vector v = new Vector();
1238        try {
1239            file = new File(xmlFile);
1240        } catch (Exception JavaDoc ex)
1241        {}
1242        if (file == null || !file.exists() || file.isDirectory()) {
1243
1244            return ExpressionEditor.defaultExpressions;
1245        }
1246        // Create a Xerces DOM Parser
1247
DOMParser parser = new DOMParser();
1248        // Parse the Document
1249
// and traverse the DOM
1250
try {
1251
1252            parser.setEntityResolver( new org.xml.sax.EntityResolver JavaDoc() {
1253                /* Code by Teodor Danciu */
1254                public org.xml.sax.InputSource JavaDoc resolveEntity(
1255                    String JavaDoc publicId,
1256                    String JavaDoc systemId
1257                ) throws SAXException JavaDoc//, java.io.IOException
1258
{
1259                    org.xml.sax.InputSource JavaDoc inputSource = null;
1260
1261                    if (systemId != null) {
1262                        String JavaDoc dtd = null;
1263
1264                        if (
1265                        systemId.equals("http://ireport.sourceforge.net/dtds/iReportExpressionsList.dtd")
1266                        ) {
1267                            dtd = "it/businesslogic/ireport/dtds/iReportExpressionsList.dtd";
1268                        }
1269                        else {
1270                            return new org.xml.sax.InputSource JavaDoc(systemId);
1271                        }
1272
1273                        ClassLoader JavaDoc classLoader = this.getClass().getClassLoader();
1274
1275                        java.net.URL JavaDoc url = null;
1276
1277
1278                        if (classLoader != null) {
1279                            url = classLoader.getResource(dtd);
1280                        }
1281                        if (url == null) {
1282                            classLoader = this.getClass().getClassLoader();
1283                        }
1284
1285                        java.io.InputStream JavaDoc is = classLoader.getResourceAsStream(dtd);
1286                        if (is != null) {
1287                            java.io.InputStreamReader JavaDoc isr = new java.io.InputStreamReader JavaDoc(is);
1288                            inputSource = new org.xml.sax.InputSource JavaDoc(isr);
1289                        }
1290
1291                    }
1292
1293                    return inputSource;
1294                }
1295            });
1296            /* End Code by Teodor Danciu */
1297            parser.parse( new java.io.File JavaDoc(xmlFile).toURI().toString() );
1298            Document JavaDoc document = parser.getDocument();
1299
1300            // Traverse the tree until we don't find a iReportFilesList element...
1301
System.out.println("FL3: " + document.getDocumentElement());
1302            Node JavaDoc fileList = document.getDocumentElement();
1303            //System.out.println("FL: " + fileList);
1304
if (fileList == null) return v;
1305            NodeList JavaDoc list = fileList.getChildNodes();
1306            for (int i=0; i < list.getLength(); ++i) {
1307                Node JavaDoc child = list.item(i);
1308                //System.out.println("FL: " + i + ">>" + child);
1309
if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("expression")) {
1310                    String JavaDoc expression = Report.readPCDATA(child);
1311                    if (expression != null && expression.trim().length()>0) {
1312                        v.addElement( expression );
1313                    }
1314                }
1315            }
1316
1317        } catch (Exception JavaDoc ex) {
1318        }
1319        
1320        return v;
1321    }
1322
1323/*
1324    public static Style getDefaultStyle(ReportElement re)
1325    {
1326        // 1. Look for the report to wich this element belong...
1327        JReportFrame frames = MainFrame.getMainInstance()
1328    }
1329    
1330    public static Report getReportByBand(Band b)
1331    {
1332        
1333    }
1334    
1335    public static Report getReportByReportElement(ReportElement re)
1336    {
1337        if (re instanceof CrosstabReportElement)
1338        {
1339            
1340        }
1341    }
1342  */

1343    
1344    
1345   /**
1346    * side can be:
1347    * DockingConstants.NOTRH_REGION
1348    * DockingConstants.EAST_REGION
1349    * DockingConstants.SOUTH_REGION
1350    * DockingConstants.WEST_REGION
1351    *
1352    * index is the position into a side
1353    *
1354    * i.e.
1355    * dockAt( dockable, DockingConstants.WEST_REGION, 0) means the top left position
1356    *
1357    *
1358    */

1359   static public boolean dockAt(Dockable toDock, String JavaDoc side, int index)
1360   {
1361       Dockable rootDockable = MainFrame.getMainInstance().getDesktopView();
1362       Dockable dockable = rootDockable;
1363              
1364       String JavaDoc directionV = null;
1365       String JavaDoc directionH = null;
1366       String JavaDoc directionIndex = null;
1367       
1368       if (side.equals( DockingConstants.NORTH_REGION ))
1369       {
1370           directionV = DockingConstants.NORTH_REGION;
1371           directionH = DockingConstants.WEST_REGION;
1372           directionIndex = DockingConstants.EAST_REGION;
1373       }
1374       if (side.equals( DockingConstants.WEST_REGION ))
1375       {
1376           directionV = DockingConstants.NORTH_REGION;
1377           directionH = DockingConstants.WEST_REGION;
1378           directionIndex = DockingConstants.SOUTH_REGION;
1379       }
1380       if (side.equals( DockingConstants.EAST_REGION ))
1381       {
1382           directionV = DockingConstants.NORTH_REGION;
1383           directionH = DockingConstants.EAST_REGION;
1384           directionIndex = DockingConstants.SOUTH_REGION;
1385       }
1386       if (side.equals( DockingConstants.SOUTH_REGION ))
1387       {
1388           directionV = DockingConstants.SOUTH_REGION;
1389           directionH = DockingConstants.WEST_REGION;
1390           directionIndex = DockingConstants.EAST_REGION;
1391       }
1392       
1393       String JavaDoc counterDirectionIndex = null;
1394       if (directionIndex.equals( DockingConstants.NORTH_REGION) ) counterDirectionIndex = DockingConstants.SOUTH_REGION;
1395       if (directionIndex.equals( DockingConstants.SOUTH_REGION) ) counterDirectionIndex = DockingConstants.NORTH_REGION;
1396       if (directionIndex.equals( DockingConstants.WEST_REGION) ) counterDirectionIndex = DockingConstants.EAST_REGION;
1397       if (directionIndex.equals( DockingConstants.EAST_REGION) ) counterDirectionIndex = DockingConstants.WEST_REGION;
1398           
1399       
1400       
1401       try {
1402                if (((View)rootDockable).getSibling(side) != null)
1403                {
1404                    dockable = ((View)rootDockable).getSibling(side);
1405                    while (DefaultDockingStrategy.getSibling(dockable, directionV) != null ||
1406                           DefaultDockingStrategy.getSibling(dockable, directionH) != null )
1407                       {
1408                           Dockable tmp = DefaultDockingStrategy.getSibling(dockable, directionV);
1409                           dockable = (tmp != null) ? tmp : DefaultDockingStrategy.getSibling(dockable, directionH);
1410                       }
1411                }
1412                    
1413           } catch (Throwable JavaDoc ex){
1414           
1415           ex.printStackTrace();
1416       }
1417       
1418      
1419       
1420       if (dockable == rootDockable) // there are no siblings in side direction...
1421
{
1422           
1423           return dockable.dock(toDock, side);
1424       }
1425       
1426       
1427       // dockable is now the root...
1428
// Go in the indexDirection for index times (if possible)...
1429
int i = 0;
1430       for (i=0; i<index; ++i)
1431       {
1432           // Look for the right sibling..
1433
try {
1434           System.out.println("Index " + i);
1435           if (DefaultDockingStrategy.getSibling(dockable, directionIndex) == null) break;
1436           dockable = DefaultDockingStrategy.getSibling(dockable, directionIndex);
1437           
1438           
1439           } catch (Throwable JavaDoc ex){
1440           
1441           ex.printStackTrace();
1442           }
1443       }
1444       
1445       if (i == index)
1446       {
1447           
1448           return dockable.dock(toDock, counterDirectionIndex);
1449       }
1450       else
1451       {
1452           return dockable.dock(toDock, directionIndex);
1453       }
1454
1455   }
1456   
1457   
1458   
1459    /**
1460     * Save the expression asking for a file.
1461     * see saveSQLQuery(String query, Component c)
1462     */

1463    public static boolean saveExpression(String JavaDoc expression)
1464    {
1465         return saveExpression(expression, MainFrame.getMainInstance());
1466    }
1467    /**
1468     * Save the query asking for a file.
1469     * The optional component is used as parent for the file selection dialog
1470     * Default is the MainFrame
1471     */

1472    public static boolean saveExpression(String JavaDoc expression, Component c)
1473    {
1474            JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
1475            jfc.setFileFilter( new javax.swing.filechooser.FileFilter JavaDoc() {
1476            public boolean accept(java.io.File JavaDoc file) {
1477                String JavaDoc filename = file.getName().toLowerCase();
1478                return (filename.endsWith(".txt") ||file.isDirectory()) ;
1479            }
1480            public String JavaDoc getDescription() {
1481                return "Text file (*.txt)";
1482            }
1483        });
1484
1485        if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) {
1486
1487                try {
1488
1489                    String JavaDoc fileName = jfc.getSelectedFile().getName();
1490                    if (fileName.indexOf(".") < 0)
1491                    {
1492                        fileName += ".txt";
1493                    }
1494
1495                    File f = new File( jfc.getSelectedFile().getParent(), fileName);
1496
1497                    FileWriter fw = new FileWriter(f);
1498                    fw.write( expression );
1499                    fw.close();
1500
1501                    return true;
1502                } catch (Exception JavaDoc ex)
1503                {
1504                    JOptionPane.showMessageDialog(c,"Error saving the expression: " + ex.getMessage(),I18n.getString("message.title.error","Error"),JOptionPane.ERROR_MESSAGE);
1505                    ex.printStackTrace();
1506                }
1507        }
1508
1509            return false;
1510    }
1511
1512    /**
1513     * See loadSQLQuery(Component c)
1514     */

1515    public static String JavaDoc loadExpression()
1516    {
1517        return loadExpression(MainFrame.getMainInstance());
1518    }
1519
1520    /**
1521     * Load the query asking for a file.
1522     * The optional component is used as parent for the file selection dialog
1523     * Default is the MainFrame
1524     */

1525    public static String JavaDoc loadExpression(Component c)
1526    {
1527            JFileChooser JavaDoc jfc = new JFileChooser JavaDoc();
1528            jfc.setMultiSelectionEnabled(false);
1529            jfc.setFileFilter( new javax.swing.filechooser.FileFilter JavaDoc() {
1530            public boolean accept(java.io.File JavaDoc file) {
1531                String JavaDoc filename = file.getName().toLowerCase();
1532                return (filename.endsWith(".txt") ||file.isDirectory()) ;
1533            }
1534            public String JavaDoc getDescription() {
1535                return "Text file (*.txt)";
1536            }
1537        });
1538
1539        if (jfc.showOpenDialog(c) == JFileChooser.APPROVE_OPTION) {
1540
1541                try {
1542
1543                    FileReader fr = new FileReader(jfc.getSelectedFile());
1544                    StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1545                    char[] cbuf = new char[1024];
1546                    int i = fr.read(cbuf);
1547                    while (i > 0)
1548                    {
1549                        sb.append( cbuf, 0, i);
1550                        i = fr.read(cbuf);
1551                    }
1552                    fr.close();
1553
1554                    return sb.toString();
1555                } catch (Exception JavaDoc ex)
1556                {
1557                    JOptionPane.showMessageDialog(c,"Error loading the expression: " + ex.getMessage(),I18n.getString("message.title.error","Error"),JOptionPane.ERROR_MESSAGE);
1558                    ex.printStackTrace();
1559                }
1560        }
1561
1562            return null;
1563    }
1564    
1565    
1566    
1567   /** This method uses the code from: http://www.centerkey.com/java/browser/
1568     *
1569     * Bare Bones Browser Launch
1570     * Version 1.5
1571     * December 10, 2005
1572     * Supports: Mac OS X, GNU/Linux, Unix, Windows XP
1573     * Example Usage:
1574     * String url = "http://www.centerkey.com/";
1575     * BareBonesBrowserLaunch.openURL(url);
1576     * Public Domain Software -- Free to Use as You Like
1577     *
1578     **/

1579   public static void openURL(String JavaDoc url) {
1580             
1581      String JavaDoc osName = System.getProperty("os.name");
1582      try {
1583         if (osName.startsWith("Mac OS")) {
1584            Class JavaDoc fileMgr = Class.forName("com.apple.eio.FileManager");
1585            java.lang.reflect.Method JavaDoc openURL = fileMgr.getDeclaredMethod("openURL",
1586               new Class JavaDoc[] {String JavaDoc.class});
1587            openURL.invoke(null, new Object JavaDoc[] {url});
1588            }
1589         else if (osName.startsWith("Windows"))
1590            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
1591         else { //assume Unix or Linux
1592
String JavaDoc[] browsers = {
1593               "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "htmlview" };
1594            String JavaDoc browser = null;
1595            for (int count = 0; count < browsers.length && browser == null; count++)
1596            {
1597                if (Runtime.getRuntime().exec(new String JavaDoc[] {"which", browsers[count]}).waitFor() == 0)
1598                {
1599                    browser = browsers[count];
1600                }
1601            }
1602            if (browser == null)
1603               throw new Exception JavaDoc(I18n.getString("misc.browserNotFound","Could not find web browser"));
1604            else
1605               Runtime.getRuntime().exec(new String JavaDoc[] {browser, url});
1606            }
1607         }
1608      catch (Exception JavaDoc e) {
1609         JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
1610                 I18n.getString("misc.browserLunchError","Error attempting to launch web browser") + "\n" + e.getLocalizedMessage());
1611         }
1612      }
1613
1614   /**
1615    * If the selected value is a Tag, tag.getValue is returned,
1616    * otherwise the selected item itself is returned.
1617    * If not item is selected, the method return null.
1618    */

1619   public static Object JavaDoc getComboboxSelectedValue(JComboBox JavaDoc combo)
1620   {
1621       Object JavaDoc result = null;
1622       if (combo != null)
1623       {
1624           result = combo.getSelectedItem();
1625           if (result != null && result instanceof Tag)
1626           {
1627               return ((Tag)result).getValue();
1628           }
1629       }
1630       return result;
1631   }
1632   
1633   /**
1634    * Creates fileName inside <user home>/classes/it/businesslogic/ireport/locale
1635    * and stores there the properties keys
1636    */

1637   public static void saveTemporaryLocale(java.util.Properties JavaDoc properties, String JavaDoc fileName)
1638   {
1639       if (properties == null) return;
1640       // Save in the user directory....
1641
String JavaDoc dir = MainFrame.getMainInstance().IREPORT_USER_HOME_DIR + File.separator +
1642                         "classes" + File.separator +
1643                         "it" + File.separator +
1644                         "businesslogic" + File.separator +
1645                         "ireport" + File.separator +
1646                         "locale";
1647            File fdir = new File(dir);
1648            if (!fdir.exists())
1649            {
1650                fdir.mkdirs();
1651                if (!fdir.exists())
1652                {
1653                    JOptionPane.showMessageDialog(null,I18n.getFormattedString("translationStatusDialog.messages.unableToCreateDir","Unable to create directory: {0}",new Object JavaDoc[]{""+fdir}));
1654                    return;
1655                }
1656            }
1657            try {
1658                File outFile = new File(fdir,fileName);
1659                
1660                properties.store(new FileOutputStream(outFile),"");
1661
1662            } catch (Exception JavaDoc ex)
1663            {
1664                ex.printStackTrace();
1665            }
1666  }
1667}//end class Misc
1668
Popular Tags