1 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 ; 49 import javax.swing.JFileChooser ; 50 import javax.swing.JOptionPane ; 51 import javax.swing.UIDefaults ; 52 import javax.swing.UIManager ; 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 ; 59 import org.w3c.dom.NamedNodeMap ; 60 import org.w3c.dom.Node ; 61 import org.w3c.dom.NodeList ; 62 import org.xml.sax.SAXException ; 63 64 68 public class Misc { 69 public static final String [] special_chars= new String []{ 70 "&","&", 71 "\"",""", 72 "'","'", 73 "<","<", 74 ">",">" 75 }; 76 159 160 161 162 public Misc() { 163 } 164 165 public static String xmlEscape(String text) 166 { 167 if( text == null) return ""; 168 int i=0; 169 String 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 } 175 176 return text; 177 } 178 179 195 196 public static java.awt.Image loadImageFromResources(String filename) { 197 try { 198 return new javax.swing.ImageIcon ( Misc.class.getResource( "/" + filename )).getImage(); 199 } catch (Exception ex) { 200 System.out.println("Exception loading resource: " +filename); 201 } 202 return null; 203 } 204 205 212 private static byte[] getBytesFromInputStream(java.io.InputStream in, int length) throws java.io.IOException { 213 java.io.DataInputStream din = new java.io.DataInputStream (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 loadBufferedImageFromResources(Component c,String filename) { 224 225 try { 226 Misc m = new Misc(); 227 java.awt.Image 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 ex){ 239 System.out.println(ex.toString()); 240 } 241 return null; 242 } 243 244 public static void updateComboBox(javax.swing.JComboBox comboBox, Vector newItems) { 245 updateComboBox(comboBox,newItems, false); 246 } 247 public static void updateComboBox(javax.swing.JComboBox comboBox, Vector newItems, boolean addNullEntry) { 248 Object 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 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 279 public static void updateStringComboBox(javax.swing.JComboBox comboBox, Vector newItems, boolean addNullEntry) { 280 Object 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 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 nvl(Object obj, String def) { 310 return (obj == null) ? def : obj.toString(); 311 } 312 313 public static void centerFrame(java.awt.Component c) { 314 java.awt.Toolkit 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 322 public static String string_replace(String s1, String s2, String s3) { 323 String string=""; 324 string = ""; 325 326 if (s2 == null || s3 == null || s2.length() == 0) return s3; 327 328 int pos_i = 0; int pos_f = 0; 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 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 loadImageFromFile(String path) { 345 java.io.File file = new java.io.File (path); 346 if (file.exists()) { 347 java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); 348 java.awt.Image img = tk.createImage(path); 349 try { 350 java.awt.MediaTracker mt = new java.awt.MediaTracker ( new javax.swing.JPanel () ); 351 mt.addImage(img,0); 352 mt.waitForID(0); 353 } catch (Exception ex){ 354 return null; 355 } 356 return img; 357 } 358 return null; 359 } 360 361 362 363 371 public static String treatNewLineChars(String source) { 372 String result = source; 373 374 if (source != null && source.length() > 0) { 375 StringBuffer sbuffer = new StringBuffer (source); 376 377 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 if (sbuffer.charAt(sbuffer.length() - 1) == '\n') { 390 sbuffer.append(' '); 391 } 392 393 if (sbuffer.charAt(0) == '\n') { 396 sbuffer.insert(0, ' '); 397 } 398 399 result = sbuffer.toString(); 400 } 401 402 result = replaceTabWithBlank(result); 404 405 return result; 406 } 407 408 409 412 public static String replaceTabWithBlank(String source) { 413 String result = source; 414 415 if (source != null && source.length() > 0) { 416 StringBuffer sbuffer = new StringBuffer (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 toHTML(String s) { 433 s = Misc.string_replace(">",">",s); 434 s = Misc.string_replace("<","<",s); 435 s = Misc.string_replace(" "," ",s); 436 s = Misc.string_replace(" ","\t",s); 437 s = Misc.string_replace("<br>", "\n", s); 438 return s; 439 } 440 441 static public String getShortFileName(String filename) { 442 if (filename.length() > 50) { 443 java.io.File f = new java.io.File (filename); 444 if (nvl(f.getParentFile(),"").length()>10) { 445 String dir = f.getParentFile().getPath()+java.io.File.separatorChar; 446 447 String 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 465 public static String getJdbcTypeClass(java.sql.ResultSetMetaData rsmd, int t ) { 466 String cls = "java.lang.Object"; 467 468 try { 469 cls = rsmd.getColumnClassName(t); 470 cls = getJRFieldType(cls); 471 472 } catch (Exception ex) 473 { 474 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 ex2){ 514 ex2.printStackTrace(); 515 } 516 } 517 return cls; 518 } 519 520 521 525 public static String getJRFieldType(String 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 548 return type; 549 } 550 551 552 553 public static long getLastWriteTime(String filename) { 554 try { 555 java.io.File f = new java.io.File (filename); 556 if (f.exists()) 557 { 558 return f.lastModified(); 559 } 560 } catch (Exception ex) { 561 562 } 563 return -1; 564 } 565 566 573 public static java.awt.Frame frameFromComponent(java.awt.Component parent) { 574 java.awt.Frame f = (java.awt.Frame )javax.swing.SwingUtilities.getAncestorOfClass(java.awt.Frame .class, parent); 575 return f; 576 } public static java.util.List getAvailablePLAF(){ 579 java.util.List l = new java.util.ArrayList (); 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 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 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("System")) { 616 javax.swing.UIManager.setLookAndFeel( javax.swing.UIManager.getSystemLookAndFeelClassName() ); 617 618 UIDefaults uiDefaults = UIManager.getDefaults(); 619 Object obj = uiDefaults.get("Panel.background"); 620 if (obj instanceof javax.swing.plaf.ColorUIResource ) 621 { 622 javax.swing.plaf.ColorUIResource cr = (javax.swing.plaf.ColorUIResource )obj; 623 uiDefaults.put("Desktop.background", new javax.swing.plaf.ColorUIResource (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 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 ex) 642 { 643 ex.printStackTrace(); 644 } 645 String 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 f = new javax.swing.plaf.FontUIResource (fontFamily,fontAttrs,fontSize); 650 java.util.Enumeration keys = javax.swing.UIManager.getDefaults().keys(); 651 while (keys.hasMoreElements()) { 652 Object key = keys.nextElement(); 653 Object value = javax.swing.UIManager.get (key); 654 if (value instanceof javax.swing.plaf.FontUIResource ) 655 javax.swing.UIManager.put (key, f); 656 } 657 } 658 } 659 660 661 662 663 return; 664 } 665 } 666 } 667 } catch (Exception ex) { 668 ex.printStackTrace(); 669 } 670 } 671 672 public static String getClassPath() { 673 String cp = (String )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 697 public static Set getResoucesInPackage(String packageName) throws IOException { 698 String localPackageName; 699 if( packageName.endsWith("/") ) { 700 localPackageName = packageName; 701 } else { 702 localPackageName = packageName + '/'; 703 } 704 705 ClassLoader 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 while( dirEnum.hasMoreElements() ) { 717 URL resUrl = (URL) dirEnum.nextElement(); 718 719 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 ex) { 733 ex.printStackTrace(); 734 } 735 736 } 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 entryName = entry.getName(); 744 if ( entryName.equals(localPackageName) ) 746 continue; 747 String parentDirName = entryName.substring( 0, entryName.lastIndexOf('/')+1 ); 748 if ( ! parentDirName.equals(localPackageName) ) 749 continue; 750 names.add( entryName ); 751 } 752 } else { 753 } 755 } 756 757 return names; 758 } 759 760 761 766 public static String changeFileExtension(String filename, String 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 784 static public java.util.Locale getLocaleFromString( String localeName ) 785 { 786 String language = ""; 787 String country = ""; 788 String 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 comboBox, String itemValue) { 830 for (int i=0; i<comboBox.getItemCount(); ++i) 831 { 832 Object 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 849 public static java.sql.Connection getConnection(String 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 868 public static net.sf.jasperreports.engine.JRDataSource getJRDataSource(String 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 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 ex) 904 { 905 ex.printStackTrace(); 906 } 907 908 return v; 909 } 910 911 public static Vector loadStyleLibrary(InputStream is, String filename) 912 { 913 Vector v = new Vector(); 914 try { 915 DOMParser parser = new DOMParser(); 916 org.xml.sax.InputSource input_sss = new org.xml.sax.InputSource (is); 917 parser.parse( input_sss ); 919 920 Document document = parser.getDocument(); 921 Node node = document.getDocumentElement(); 922 923 924 NodeList list_child = node.getChildNodes(); 925 for (int ck=0; ck< list_child.getLength(); ck++) { 926 Node styleNode = (Node )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 ex) 934 { 935 ex.printStackTrace(); 936 } 937 938 return v; 939 } 940 941 944 public static it.businesslogic.ireport.Style readStyle(Node styleNode, ConditionedStyle cStyle) 945 { 946 Style style = new Style(); 947 if (cStyle != null) style = cStyle; 948 NamedNodeMap 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 NodeList children = styleNode.getChildNodes(); 960 if (children != null) { 961 for (int k=0; k< children.getLength(); k++) { 962 Node nodeChild = (Node )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 976 private static it.businesslogic.ireport.ConditionedStyle readConditionalStyle(Node styleNode) 977 { 978 ConditionedStyle style = new ConditionedStyle(); 979 980 NodeList children = styleNode.getChildNodes(); 983 if (children != null) { 984 for (int k=0; k< children.getLength(); k++) { 985 Node nodeChild = (Node )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 filename, Vector styles) 999 { 1000 try { 1001 PrintWriter pw = new PrintWriter( new java.io.OutputStreamWriter ( new java.io.FileOutputStream ( filename ), "UTF8" )); 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 ex) 1013 { 1014 JOptionPane.showMessageDialog(MainFrame.getMainInstance(), 1015 I18n.getFormattedString( "messages.misc.errorSavingStyles", 1016 "Error saving styles library: {0}", 1017 new Object []{ ex.getMessage() }) ); 1018 ex.printStackTrace(); 1019 } 1020 } 1021 1022 1023 private static void writeXMLStyles(Vector styles, java.io.PrintWriter pw, String 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 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 obj = style.getAttributes().get(Style.JRXMLStyleAttributes[i]); 1045 String value = ""+obj; 1046 if (obj instanceof java.awt.Color ) 1047 { 1048 value = Report.writeEncodedColor( (java.awt.Color )obj); 1049 } 1050 if (Style.JRXMLStyleAttributes[i].toLowerCase().endsWith("color") && value.startsWith("[")) 1051 { 1052 try { 1054 value = Report.writeEncodedColor(it.businesslogic.ireport.gui.sheet.ColorSelectorPanel.parseColorString(value)); 1055 } catch (Exception 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 1090 public static boolean saveSQLQuery(String query) 1091 { 1092 return saveSQLQuery(query, MainFrame.getMainInstance()); 1093 } 1094 1099 public static boolean saveSQLQuery(String query, Component c) 1100 { 1101 JFileChooser jfc = new JFileChooser (); 1102 jfc.setFileFilter( new javax.swing.filechooser.FileFilter () { 1103 public boolean accept(java.io.File file) { 1104 String filename = file.getName().toLowerCase(); 1105 return (filename.endsWith(".sql") || filename.endsWith(".txt") ||file.isDirectory()) ; 1106 } 1107 public String getDescription() { 1108 return "SQL query (*.sql, *.txt)"; 1109 } 1110 }); 1111 1112 if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) { 1113 1114 try { 1115 1116 String 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 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 1142 public static String loadSQLQuery() 1143 { 1144 return loadSQLQuery(MainFrame.getMainInstance()); 1145 } 1146 1147 1152 public static String loadSQLQuery(Component c) 1153 { 1154 JFileChooser jfc = new JFileChooser (); 1155 jfc.setMultiSelectionEnabled(false); 1156 jfc.setFileFilter( new javax.swing.filechooser.FileFilter () { 1157 public boolean accept(java.io.File file) { 1158 String filename = file.getName().toLowerCase(); 1159 return (filename.endsWith(".sql") || filename.endsWith(".txt") ||file.isDirectory()) ; 1160 } 1161 public String 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 sb = new StringBuffer (); 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 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 1196 public static boolean saveExpressionsList( Vector v, String xmlFile) { 1197 try { 1200 PrintWriter pw = new PrintWriter( new FileWriter(xmlFile) ); 1201 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 exp = (String )e.nextElement(); 1212 pw.println("\t<expression><![CDATA["+ exp +"]]></expression>"); 1213 } 1214 pw.println("</iReportExpressionsList>"); 1215 pw.close(); 1216 } catch (Exception ex) { 1217 try { 1219 MainFrame.getMainInstance().logOnConsole("Error saving iReport file: "+xmlFile+"\n"+ex.getMessage()+"\n"); 1220 1221 } catch (Exception exsx) 1222 {} 1223 return false; 1224 } 1225 try { 1226 MainFrame.getMainInstance().logOnConsole("iReport file "+ xmlFile + " successfully updated!\n"); 1227 } catch (Exception ex) 1228 { } 1229 return true; 1230 } 1231 1232 1235 public static Vector loadExpressionsList(String xmlFile) { 1236 File file = null; 1237 Vector v = new Vector(); 1238 try { 1239 file = new File(xmlFile); 1240 } catch (Exception ex) 1241 {} 1242 if (file == null || !file.exists() || file.isDirectory()) { 1243 1244 return ExpressionEditor.defaultExpressions; 1245 } 1246 DOMParser parser = new DOMParser(); 1248 try { 1251 1252 parser.setEntityResolver( new org.xml.sax.EntityResolver () { 1253 1254 public org.xml.sax.InputSource resolveEntity( 1255 String publicId, 1256 String systemId 1257 ) throws SAXException { 1259 org.xml.sax.InputSource inputSource = null; 1260 1261 if (systemId != null) { 1262 String 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 (systemId); 1271 } 1272 1273 ClassLoader classLoader = this.getClass().getClassLoader(); 1274 1275 java.net.URL 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 is = classLoader.getResourceAsStream(dtd); 1286 if (is != null) { 1287 java.io.InputStreamReader isr = new java.io.InputStreamReader (is); 1288 inputSource = new org.xml.sax.InputSource (isr); 1289 } 1290 1291 } 1292 1293 return inputSource; 1294 } 1295 }); 1296 1297 parser.parse( new java.io.File (xmlFile).toURI().toString() ); 1298 Document document = parser.getDocument(); 1299 1300 System.out.println("FL3: " + document.getDocumentElement()); 1302 Node fileList = document.getDocumentElement(); 1303 if (fileList == null) return v; 1305 NodeList list = fileList.getChildNodes(); 1306 for (int i=0; i < list.getLength(); ++i) { 1307 Node child = list.item(i); 1308 if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("expression")) { 1310 String expression = Report.readPCDATA(child); 1311 if (expression != null && expression.trim().length()>0) { 1312 v.addElement( expression ); 1313 } 1314 } 1315 } 1316 1317 } catch (Exception ex) { 1318 } 1319 1320 return v; 1321 } 1322 1323 1343 1344 1345 1359 static public boolean dockAt(Dockable toDock, String side, int index) 1360 { 1361 Dockable rootDockable = MainFrame.getMainInstance().getDesktopView(); 1362 Dockable dockable = rootDockable; 1363 1364 String directionV = null; 1365 String directionH = null; 1366 String 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 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 ex){ 1414 1415 ex.printStackTrace(); 1416 } 1417 1418 1419 1420 if (dockable == rootDockable) { 1422 1423 return dockable.dock(toDock, side); 1424 } 1425 1426 1427 int i = 0; 1430 for (i=0; i<index; ++i) 1431 { 1432 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 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 1463 public static boolean saveExpression(String expression) 1464 { 1465 return saveExpression(expression, MainFrame.getMainInstance()); 1466 } 1467 1472 public static boolean saveExpression(String expression, Component c) 1473 { 1474 JFileChooser jfc = new JFileChooser (); 1475 jfc.setFileFilter( new javax.swing.filechooser.FileFilter () { 1476 public boolean accept(java.io.File file) { 1477 String filename = file.getName().toLowerCase(); 1478 return (filename.endsWith(".txt") ||file.isDirectory()) ; 1479 } 1480 public String getDescription() { 1481 return "Text file (*.txt)"; 1482 } 1483 }); 1484 1485 if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) { 1486 1487 try { 1488 1489 String 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 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 1515 public static String loadExpression() 1516 { 1517 return loadExpression(MainFrame.getMainInstance()); 1518 } 1519 1520 1525 public static String loadExpression(Component c) 1526 { 1527 JFileChooser jfc = new JFileChooser (); 1528 jfc.setMultiSelectionEnabled(false); 1529 jfc.setFileFilter( new javax.swing.filechooser.FileFilter () { 1530 public boolean accept(java.io.File file) { 1531 String filename = file.getName().toLowerCase(); 1532 return (filename.endsWith(".txt") ||file.isDirectory()) ; 1533 } 1534 public String 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 sb = new StringBuffer (); 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 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 1579 public static void openURL(String url) { 1580 1581 String osName = System.getProperty("os.name"); 1582 try { 1583 if (osName.startsWith("Mac OS")) { 1584 Class fileMgr = Class.forName("com.apple.eio.FileManager"); 1585 java.lang.reflect.Method openURL = fileMgr.getDeclaredMethod("openURL", 1586 new Class [] {String .class}); 1587 openURL.invoke(null, new Object [] {url}); 1588 } 1589 else if (osName.startsWith("Windows")) 1590 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); 1591 else { String [] browsers = { 1593 "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "htmlview" }; 1594 String browser = null; 1595 for (int count = 0; count < browsers.length && browser == null; count++) 1596 { 1597 if (Runtime.getRuntime().exec(new String [] {"which", browsers[count]}).waitFor() == 0) 1598 { 1599 browser = browsers[count]; 1600 } 1601 } 1602 if (browser == null) 1603 throw new Exception (I18n.getString("misc.browserNotFound","Could not find web browser")); 1604 else 1605 Runtime.getRuntime().exec(new String [] {browser, url}); 1606 } 1607 } 1608 catch (Exception e) { 1609 JOptionPane.showMessageDialog(MainFrame.getMainInstance(), 1610 I18n.getString("misc.browserLunchError","Error attempting to launch web browser") + "\n" + e.getLocalizedMessage()); 1611 } 1612 } 1613 1614 1619 public static Object getComboboxSelectedValue(JComboBox combo) 1620 { 1621 Object 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 1637 public static void saveTemporaryLocale(java.util.Properties properties, String fileName) 1638 { 1639 if (properties == null) return; 1640 String 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 []{""+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 ex) 1663 { 1664 ex.printStackTrace(); 1665 } 1666 } 1667} | Popular Tags |