0001: /*
0002: * Copyright (C) 2005 - 2008 JasperSoft Corporation. All rights reserved.
0003: * http://www.jaspersoft.com.
0004: *
0005: * Unless you have purchased a commercial license agreement from JasperSoft,
0006: * the following license terms apply:
0007: *
0008: * This program is free software; you can redistribute it and/or modify
0009: * it under the terms of the GNU General Public License version 2 as published by
0010: * the Free Software Foundation.
0011: *
0012: * This program is distributed WITHOUT ANY WARRANTY; and without the
0013: * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
0014: * See the GNU General Public License for more details.
0015: *
0016: * You should have received a copy of the GNU General Public License
0017: * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
0018: * or write to:
0019: *
0020: * Free Software Foundation, Inc.,
0021: * 59 Temple Place - Suite 330,
0022: * Boston, MA USA 02111-1307
0023: *
0024: *
0025: *
0026: *
0027: * Misc.java
0028: *
0029: * Created on 14 febbraio 2003, 16.35
0030: *
0031: */
0032:
0033: package it.businesslogic.ireport.util;
0034:
0035: import it.businesslogic.ireport.Band;
0036: import it.businesslogic.ireport.ConditionedStyle;
0037: import it.businesslogic.ireport.IReportConnection;
0038: import it.businesslogic.ireport.Report;
0039: import it.businesslogic.ireport.Style;
0040: import it.businesslogic.ireport.SubDataset;
0041: import it.businesslogic.ireport.gui.ExpressionEditor;
0042: import it.businesslogic.ireport.gui.JRTextExpressionArea;
0043: import it.businesslogic.ireport.gui.MainFrame;
0044: import it.businesslogic.ireport.gui.sheet.Tag;
0045: import java.awt.*;
0046: import java.awt.event.KeyEvent;
0047: import java.awt.event.KeyListener;
0048: import java.awt.image.*;
0049: import java.util.*;
0050: import java.util.jar.*;
0051: import java.net.*;
0052: import java.io.*;
0053: import javax.swing.DefaultComboBoxModel;
0054: import javax.swing.JComboBox;
0055: import javax.swing.JComponent;
0056: import javax.swing.JFileChooser;
0057: import javax.swing.JOptionPane;
0058: import javax.swing.JTree;
0059: import javax.swing.UIDefaults;
0060: import javax.swing.UIManager;
0061: import javax.swing.border.LineBorder;
0062: import javax.swing.text.JTextComponent;
0063: import javax.swing.tree.DefaultMutableTreeNode;
0064: import javax.swing.tree.TreePath;
0065: import org.apache.xerces.parsers.DOMParser;
0066: import org.flexdock.docking.Dockable;
0067: import org.flexdock.docking.DockingConstants;
0068: import org.flexdock.docking.defaults.DefaultDockingStrategy;
0069: import org.flexdock.view.View;
0070: import org.w3c.dom.Document;
0071: import org.w3c.dom.NamedNodeMap;
0072: import org.w3c.dom.Node;
0073: import org.w3c.dom.NodeList;
0074: import org.xml.sax.SAXException;
0075:
0076: /**
0077: *
0078: * @author Administrator
0079: */
0080: public class Misc {
0081: public static final String[] special_chars = new String[] { "&",
0082: "&", "\"", """, "'", "'", "<", "<", ">",
0083: ">" };
0084:
0085: /*
0086: "&","&",
0087: "?","á",
0088: "?","â",
0089: "?","æ",
0090: "?","à",
0091: "?","å",
0092: "?","ã",
0093: "?","ä",
0094: "?","ç",
0095: "?","é",
0096: "?","ê",
0097: "?","è",
0098: "?","ð",
0099: "?","ë",
0100: ">",">",
0101: "?","í",
0102: "?","î",
0103: "?","ì",
0104: "?","ï",
0105: "<","<",
0106: "?","ñ",
0107: "?","ó",
0108: "?","ô",
0109: "?","ò",
0110: "?","ø",
0111: "?","õ",
0112: "?","ö",
0113: "\"",""",
0114: "?","ß",
0115: "?","þ",
0116: "?","ú",
0117: "?","û",
0118: "?","ù",
0119: "?","ü",
0120: "?","ý",
0121: "?","ÿ",
0122: "?","¡",
0123: "?","ª",
0124: "?","·",
0125: "?","¢",
0126: "?","«",
0127: "?","¸",
0128: "?","£",
0129: "?","®",
0130: "?","¹",
0131: "?","¤",
0132: "?","°",
0133: "?","º",
0134: "?","¥",
0135: "?","±",
0136: "?","»",
0137: "?","¦",
0138: "?","²",
0139: "?","¼",
0140: "?","§",
0141: "?","³",
0142: "?","½",
0143: "?","¨",
0144: "?","µ",
0145: "?","¾",
0146: "?","©",
0147: "?","¶",
0148: "?","¿",
0149: "?","¬",
0150: "?","×",
0151: "?","÷",
0152: "?","±",
0153: "?","·",
0154: "?","½",
0155: "?","«",
0156: "?","²",
0157: "?","¹",
0158: "?","¾",
0159: "?","¬",
0160: "?","³",
0161: "?","»",
0162: "?","×",
0163: "?","°",
0164: "?","µ",
0165: "?","¼",
0166: "?","÷"};
0167: */
0168:
0169: /** Creates a new instance of Misc */
0170: public Misc() {
0171: }
0172:
0173: public static String xmlEscape(String text) {
0174: if (text == null)
0175: return "";
0176: int i = 0;
0177: String tmp = "";
0178: for (i = 0; i < special_chars.length; i += 2) {
0179: text = string_replace(special_chars[i + 1],
0180: special_chars[i], text);
0181: //text = string_replace(special_chars[i], special_chars[i+1], text);
0182: }
0183:
0184: return text;
0185: }
0186:
0187: /*
0188: public static java.awt.Image loadImageFromResources(String filename) {
0189: try {
0190: ClassLoader cl = ClassLoader.getSystemClassLoader();
0191: //java.io.InputStream in = new java.io.FileInputStream( cl.getResource(filename).getPath() );
0192: java.io.InputStream in = cl.getResourceAsStream(filename);
0193: byte[] data = getBytesFromInputStream(in, in.available());
0194: return java.awt.Toolkit.getDefaultToolkit().createImage(data);
0195: } catch (Exception ex) {
0196: System.out.println("Exception loading resource: "+filename);
0197: //ex.getMessage();
0198: //ex.printStackTrace();
0199: }
0200: return null;
0201: }
0202: */
0203: /** New version by Umberto Uderzo */
0204: public static java.awt.Image loadImageFromResources(String filename) {
0205: try {
0206: return new javax.swing.ImageIcon(Misc.class.getResource("/"
0207: + filename)).getImage();
0208: } catch (Exception ex) {
0209: System.out.println("Exception loading resource: "
0210: + filename);
0211: }
0212: return null;
0213: }
0214:
0215: /**
0216: * Returns an array of bytes containing the bytecodes for
0217: * the class represented by the InputStream
0218: * @param in the inputstream of the class file
0219: * @return the bytecodes for the class
0220: * @exception java.io.IOException if the class cannot be read
0221: */
0222: private static byte[] getBytesFromInputStream(
0223: java.io.InputStream in, int length)
0224: throws java.io.IOException {
0225: java.io.DataInputStream din = new java.io.DataInputStream(in);
0226: byte[] bytecodes = new byte[length];
0227: try {
0228: din.readFully(bytecodes);
0229: } finally {
0230: if (din != null)
0231: din.close();
0232: }
0233: return bytecodes;
0234: }
0235:
0236: public static java.awt.image.BufferedImage loadBufferedImageFromResources(
0237: Component c, String filename) {
0238:
0239: try {
0240: Misc m = new Misc();
0241: java.awt.Image img = loadImageFromResources(filename);
0242: MediaTracker mt = new MediaTracker(c);
0243: mt.addImage(img, 0);
0244: mt.waitForID(0);
0245: int width = img.getWidth(null);
0246: int height = img.getHeight(null);
0247: BufferedImage bi = new BufferedImage(width, height,
0248: BufferedImage.TYPE_INT_RGB);
0249: Graphics gg = bi.getGraphics();
0250: gg.drawImage(img, 0, 0, null);
0251: gg.dispose();
0252: return bi;
0253: } catch (Exception ex) {
0254: System.out.println(ex.toString());
0255: }
0256: return null;
0257: }
0258:
0259: public static void updateComboBox(javax.swing.JComboBox comboBox,
0260: Vector newItems) {
0261: updateComboBox(comboBox, newItems, false);
0262: }
0263:
0264: public static void updateComboBox(javax.swing.JComboBox comboBox,
0265: Vector newItems, boolean addNullEntry) {
0266: Object itemSelected = null;
0267: if (comboBox.getSelectedIndex() >= 0) {
0268: itemSelected = comboBox.getSelectedItem();
0269: }
0270:
0271: //comboBox.removeAllItems();
0272:
0273: java.util.Vector items = new java.util.Vector(newItems.size(),
0274: 1);
0275: boolean selected = false;
0276: boolean foundNullItem = false;
0277: Enumeration e = newItems.elements();
0278: int selectedIndex = -1;
0279: int currentelement = 0;
0280: while (e.hasMoreElements()) {
0281: Object item = e.nextElement();
0282: items.add(item);
0283: if (item == itemSelected) {
0284: selectedIndex = currentelement;
0285: }
0286: if (item.equals("")) {
0287: foundNullItem = true;
0288: }
0289:
0290: currentelement++;
0291: }
0292:
0293: if (addNullEntry) {
0294: if (!foundNullItem)
0295: items.add(0, "");
0296: if (selectedIndex < 0)
0297: selectedIndex = 0;
0298: }
0299:
0300: comboBox.setModel(new DefaultComboBoxModel(items));
0301: comboBox.setSelectedIndex(selectedIndex);
0302:
0303: }
0304:
0305: /** Mthis method perform equals based on string rapresentation of objects
0306: *
0307: */
0308: public static void updateStringComboBox(
0309: javax.swing.JComboBox comboBox, Vector newItems,
0310: boolean addNullEntry) {
0311: Object itemSelected = null;
0312: if (comboBox.getSelectedIndex() >= 0) {
0313: itemSelected = comboBox.getSelectedItem() + "";
0314: }
0315:
0316: //comboBox.removeAllItems();
0317:
0318: java.util.Vector items = new java.util.Vector(newItems.size(),
0319: 1);
0320:
0321: boolean selected = false;
0322: boolean foundNullItem = false;
0323: Enumeration e = newItems.elements();
0324: int selectedIndex = -1;
0325: int currentelement = 0;
0326:
0327: while (e.hasMoreElements()) {
0328: String item = "" + e.nextElement();
0329: items.add(item);
0330: //comboBox.addItem(item);
0331: if (item.equals(itemSelected)) {
0332: selectedIndex = currentelement;
0333: }
0334: if (item.equals("")) {
0335: foundNullItem = true;
0336: }
0337: currentelement++;
0338: }
0339:
0340: if (addNullEntry) {
0341: if (!foundNullItem)
0342: items.add(0, "");
0343: if (selectedIndex < 0)
0344: selectedIndex = 0;
0345: }
0346:
0347: comboBox.setModel(new DefaultComboBoxModel(items));
0348: comboBox.setSelectedIndex(selectedIndex);
0349:
0350: }
0351:
0352: public static String nvl(Object obj, String def) {
0353: return (obj == null) ? def : obj.toString();
0354: }
0355:
0356: public static void centerFrame(java.awt.Component c) {
0357: java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
0358: c.setLocation((int) ((tk.getScreenSize().getWidth() - c
0359: .getWidth()) / 2), (int) ((tk.getScreenSize()
0360: .getHeight() - c.getHeight()) / 2));
0361: }
0362:
0363: /**
0364: * Replace s2 with s1 in s3
0365: **/
0366: public static String string_replace(String s1, String s2, String s3) {
0367: String string = "";
0368: string = "";
0369:
0370: if (s2 == null || s3 == null || s2.length() == 0)
0371: return s3;
0372:
0373: int pos_i = 0; // posizione corrente.
0374: int pos_f = 0; // posizione corrente finale
0375:
0376: int len = s2.length();
0377: while ((pos_f = s3.indexOf(s2, pos_i)) >= 0) {
0378: string += s3.substring(pos_i, pos_f) + s1;
0379: //+string.substring(pos+ s2.length());
0380: pos_f = pos_i = pos_f + len;
0381:
0382: }
0383:
0384: string += s3.substring(pos_i);
0385: return string;
0386: }
0387:
0388: public static java.awt.Image loadImageFromFile(String path) {
0389: java.io.File file = new java.io.File(path);
0390: if (file.exists()) {
0391: java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
0392: java.awt.Image img = tk.createImage(path);
0393: try {
0394: java.awt.MediaTracker mt = new java.awt.MediaTracker(
0395: new javax.swing.JPanel());
0396: mt.addImage(img, 0);
0397: mt.waitForID(0);
0398: } catch (Exception ex) {
0399: return null;
0400: }
0401: return img;
0402: }
0403: return null;
0404: }
0405:
0406: /**
0407: * This method inserts a blank character between to consecutive
0408: * newline characters if encoutered. Also appends a blank character at
0409: * the beginning of the text, if the first character is a newline character
0410: * and at the end of the text, if the last character is also a newline.
0411: * This is useful when trying to layout the paragraphs.
0412: * Thanks to Teodor Danciu for this this method (c) 2003 Teodor Danciu
0413: */
0414: public static String treatNewLineChars(String source) {
0415: String result = source;
0416:
0417: if (source != null && source.length() > 0) {
0418: StringBuffer sbuffer = new StringBuffer(source);
0419:
0420: // insert a blank character between every two consecutives
0421: // newline characters
0422: int offset = source.length() - 1;
0423: int pos = source.lastIndexOf("\n\n", offset);
0424: while (pos >= 0 && offset > 0) {
0425: sbuffer = sbuffer.insert(pos + 1, " ");
0426: offset = pos - 1;
0427: pos = source.lastIndexOf("\n\n", offset);
0428: }
0429:
0430: // append a blank character at the and of the text
0431: // if the last character is a newline character
0432: if (sbuffer.charAt(sbuffer.length() - 1) == '\n') {
0433: sbuffer.append(' ');
0434: }
0435:
0436: // append a blank character at the begining of the text
0437: // if the first character is a newline character
0438: if (sbuffer.charAt(0) == '\n') {
0439: sbuffer.insert(0, ' ');
0440: }
0441:
0442: result = sbuffer.toString();
0443: }
0444:
0445: // remove this if you want to treat the tab characters in a special way
0446: result = replaceTabWithBlank(result);
0447:
0448: return result;
0449: }
0450:
0451: /**
0452: * Thanks to Teodor Danciu for this method (c) 2003 Teodor Danciu
0453: */
0454: public static String replaceTabWithBlank(String source) {
0455: String result = source;
0456:
0457: if (source != null && source.length() > 0) {
0458: StringBuffer sbuffer = new StringBuffer(source);
0459:
0460: int offset = 0;
0461: int pos = source.indexOf("\t", offset);
0462: while (pos >= 0) {
0463: sbuffer.setCharAt(pos, ' ');
0464: offset = pos + 1;
0465: pos = source.indexOf("\t", offset);
0466: }
0467:
0468: result = sbuffer.toString();
0469: }
0470:
0471: return result;
0472: }
0473:
0474: public static String toHTML(String s) {
0475: s = Misc.string_replace(">", ">", s);
0476: s = Misc.string_replace("<", "<", s);
0477: s = Misc.string_replace(" ", " ", s);
0478: s = Misc.string_replace(" ", "\t", s);
0479: s = Misc.string_replace("<br>", "\n", s);
0480: return s;
0481: }
0482:
0483: static public String getShortFileName(String filename) {
0484: if (filename.length() > 50) {
0485: java.io.File f = new java.io.File(filename);
0486: if (nvl(f.getParentFile(), "").length() > 10) {
0487: String dir = f.getParentFile().getPath()
0488: + java.io.File.separatorChar;
0489:
0490: String shortDir = dir.substring(0, dir
0491: .indexOf(java.io.File.separatorChar) + 1);
0492: dir = dir.substring(dir
0493: .indexOf(java.io.File.separatorChar) + 1);
0494: if (dir.indexOf(java.io.File.separatorChar) > 0) {
0495: shortDir += dir.substring(0, dir
0496: .indexOf(java.io.File.separatorChar) + 1);
0497: }
0498: return shortDir + "..." + java.io.File.separatorChar
0499: + f.getName();
0500: }
0501: }
0502:
0503: return filename;
0504:
0505: }
0506:
0507: /**
0508: * Thanx to Jackie Manning j.m@programmer.net for this method!!
0509: */
0510: public static String getJdbcTypeClass(
0511: java.sql.ResultSetMetaData rsmd, int t) {
0512: String cls = "java.lang.Object";
0513:
0514: try {
0515: cls = rsmd.getColumnClassName(t);
0516: cls = getJRFieldType(cls);
0517:
0518: } catch (Exception ex) {
0519: // if getColumnClassName is not supported...
0520: try {
0521: int type = rsmd.getColumnType(t);
0522: switch (type) {
0523: case java.sql.Types.TINYINT:
0524: case java.sql.Types.BIT:
0525: cls = "java.lang.Byte";
0526: break;
0527: case java.sql.Types.SMALLINT:
0528: cls = "java.lang.Short";
0529: break;
0530: case java.sql.Types.INTEGER:
0531: cls = "java.lang.Integer";
0532: break;
0533: case java.sql.Types.FLOAT:
0534: case java.sql.Types.REAL:
0535: case java.sql.Types.DOUBLE:
0536: case java.sql.Types.NUMERIC:
0537: case java.sql.Types.DECIMAL:
0538: cls = "java.lang.Double";
0539: break;
0540: case java.sql.Types.CHAR:
0541: case java.sql.Types.VARCHAR:
0542: cls = "java.lang.String";
0543: break;
0544:
0545: case java.sql.Types.BIGINT:
0546: cls = "java.lang.Long";
0547: break;
0548: case java.sql.Types.DATE:
0549: cls = "java.util.Date";
0550: break;
0551: case java.sql.Types.TIME:
0552: cls = "java.sql.Time";
0553: break;
0554: case java.sql.Types.TIMESTAMP:
0555: cls = "java.sql.Timestamp";
0556: break;
0557: }
0558: } catch (Exception ex2) {
0559: ex2.printStackTrace();
0560: }
0561: }
0562: return cls;
0563: }
0564:
0565: /**
0566: * Return the correct field type...
0567: *
0568: */
0569: public static String getJRFieldType(String type) {
0570:
0571: if (type == null)
0572: return "java.lang.Object";
0573:
0574: if (type.equals("java.lang.Boolean") || type.equals("boolean"))
0575: return "java.lang.Boolean";
0576: if (type.equals("java.lang.Byte") || type.equals("byte"))
0577: return "java.lang.Byte";
0578: if (type.equals("java.lang.Integer") || type.equals("int"))
0579: return "java.lang.Integer";
0580: if (type.equals("java.lang.Long") || type.equals("long"))
0581: return "java.lang.Long";
0582: if (type.equals("java.lang.Double") || type.equals("double"))
0583: return "java.lang.Double";
0584: if (type.equals("java.lang.Float") || type.equals("float"))
0585: return "java.lang.Float";
0586: if (type.equals("java.lang.Short") || type.equals("short"))
0587: return "java.lang.Short";
0588: if (type.startsWith("["))
0589: return "java.lang.Object";
0590: /*
0591: if (type.equals("java.util.Date") ||
0592: type.equals("java.sql.Timestamp") ||
0593: type.equals("java.io.InputStream") ||
0594: type.equals("java.math.BigDecimal") ||
0595: type.equals("java.lang.String") ||
0596: type.equals("java.sql.Time")) return type;
0597:
0598: return "java.lang.Object";
0599: */
0600: return type;
0601: }
0602:
0603: public static long getLastWriteTime(String filename) {
0604: try {
0605: java.io.File f = new java.io.File(filename);
0606: if (f.exists()) {
0607: return f.lastModified();
0608: }
0609: } catch (Exception ex) {
0610:
0611: }
0612: return -1;
0613: }
0614:
0615: /**
0616: *Method used to grab the Frame which is above this component in the hierarchy.
0617: *This allows programmers to make any component the parent of any window or
0618: *dialog easier.
0619: *@param comp the component to get the Frame for
0620: *@return the Frame above this component in the hierarchy
0621: */
0622: public static java.awt.Frame frameFromComponent(
0623: java.awt.Component parent) {
0624: java.awt.Frame f = (java.awt.Frame) javax.swing.SwingUtilities
0625: .getAncestorOfClass(java.awt.Frame.class, parent);
0626: return f;
0627: }//end frameFromComponent
0628:
0629: //ErtanO 12.03.2004
0630: public static java.util.List getAvailablePLAF() {
0631: java.util.List l = new java.util.ArrayList();
0632: l.add("System");
0633: l.add("TinyLAF");
0634: l.add("TonicLAF");
0635: l.add("JGoodiesLAF-PlasticXP");
0636: l.add("JGoodiesLAF-Plastic");
0637: l.add("JGoodiesLAF-Plastic3D");
0638: l.add("JGoodiesLAF-ExtWindows");
0639: l.add("JGoodiesLAF-ExtWindows");
0640: //l.add("KunststofLAF");
0641:
0642: javax.swing.UIManager.LookAndFeelInfo[] lfinfo = javax.swing.UIManager
0643: .getInstalledLookAndFeels();
0644:
0645: for (int i = 0; i < lfinfo.length; ++i) {
0646: l.add(lfinfo[i].getName());
0647: }
0648:
0649: return l;
0650: }
0651:
0652: public static void setPLAF(String s) {
0653: try {
0654:
0655: if (s.equals("TinyLAF")) {
0656: javax.swing.UIManager
0657: .setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel");
0658: } else if (s.equals("TonicLAF")) {
0659: javax.swing.UIManager
0660: .setLookAndFeel("com.digitprop.tonic.TonicLookAndFeel");
0661: } else if (s.equals("JGoodiesLAF-PlasticXP")) {
0662: javax.swing.UIManager
0663: .setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
0664: } else if (s.equals("JGoodiesLAF-Plastic")) {
0665: javax.swing.UIManager
0666: .setLookAndFeel("com.jgoodies.looks.plastic.PlasticLookAndFeel");
0667: } else if (s.equals("JGoodiesLAF-Plastic3D")) {
0668: javax.swing.UIManager
0669: .setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
0670: } else if (s.equals("JGoodiesLAF-ExtWindows")) {
0671: javax.swing.UIManager
0672: .setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel");
0673: //} else if(s.equals("KunststofLAF")) {
0674: // javax.swing.UIManager.setLookAndFeel("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
0675: } else if (s.equals("System")) {
0676: javax.swing.UIManager
0677: .setLookAndFeel(javax.swing.UIManager
0678: .getSystemLookAndFeelClassName());
0679:
0680: UIDefaults uiDefaults = UIManager.getDefaults();
0681: Object obj = uiDefaults.get("Panel.background");
0682: if (obj instanceof javax.swing.plaf.ColorUIResource) {
0683: javax.swing.plaf.ColorUIResource cr = (javax.swing.plaf.ColorUIResource) obj;
0684: uiDefaults.put("Desktop.background",
0685: new javax.swing.plaf.ColorUIResource(cr
0686: .darker()));
0687: }
0688: } else {
0689: javax.swing.UIManager.LookAndFeelInfo[] lfinfo = javax.swing.UIManager
0690: .getInstalledLookAndFeels();
0691: for (int i = 0; i < lfinfo.length; ++i) {
0692: if (lfinfo[i].getName().equalsIgnoreCase(s)) {
0693: javax.swing.UIManager.setLookAndFeel(lfinfo[i]
0694: .getClassName());
0695:
0696: if (s.equals("Metal")) {
0697: if (MainFrame.getMainInstance()
0698: .getProperties().getProperty(
0699: "overrideDefaultFont",
0700: "true").equals("true")) {
0701:
0702: String fontFamily = MainFrame
0703: .getMainInstance()
0704: .getProperties()
0705: .getProperty(
0706: "overrideDefaultFontName",
0707: I18n.getString(
0708: "defaultFont",
0709: "Tahoma"));
0710:
0711: int fontSize = 11;
0712: try {
0713: fontSize = Integer
0714: .parseInt(MainFrame
0715: .getMainInstance()
0716: .getProperties()
0717: .getProperty(
0718: "overrideDefaultFontSize",
0719: "11"));
0720: } catch (Exception ex) {
0721: ex.printStackTrace();
0722: }
0723: String sNum = MainFrame
0724: .getMainInstance()
0725: .getProperties()
0726: .getProperty(
0727: "overrideDefaultFontAttrs",
0728: "0");
0729: if (sNum == null || !sNum.equals("1"))
0730: sNum = "0";
0731: int fontAttrs = Integer.parseInt(sNum);
0732:
0733: javax.swing.plaf.FontUIResource f = new javax.swing.plaf.FontUIResource(
0734: fontFamily, fontAttrs, fontSize);
0735: java.util.Enumeration keys = javax.swing.UIManager
0736: .getDefaults().keys();
0737: while (keys.hasMoreElements()) {
0738: Object key = keys.nextElement();
0739: Object value = javax.swing.UIManager
0740: .get(key);
0741: if (value instanceof javax.swing.plaf.FontUIResource)
0742: javax.swing.UIManager.put(key,
0743: f);
0744: }
0745: }
0746: }
0747: return;
0748: }
0749: }
0750: }
0751:
0752: } catch (Exception ex) {
0753: ex.printStackTrace();
0754: }
0755: }
0756:
0757: public static String getClassPath() {
0758: String cp = (String) System.getProperty("java.class.path");
0759: if (it.businesslogic.ireport.gui.MainFrame.getMainInstance() != null) {
0760: Vector cp_v = it.businesslogic.ireport.gui.MainFrame
0761: .getMainInstance().getClasspath();
0762: for (int i = 0; i < cp_v.size(); ++i) {
0763: cp += File.pathSeparator + cp_v.elementAt(i);
0764: }
0765: }
0766: return cp;
0767: }
0768:
0769: /**
0770: * Enumerates the resouces in a give package name.
0771: * This works even if the resources are loaded from a jar file!
0772: *
0773: * Adapted from code by mikewse
0774: * on the java.sun.com message boards.
0775: * http://forum.java.sun.com/thread.jsp?forum=22&thread=30984
0776: *
0777: * @param packageName The package to enumerate
0778: * @return A Set of Strings for each resouce in the package.
0779: */
0780: public static Set getResoucesInPackage(String packageName)
0781: throws IOException {
0782: String localPackageName;
0783: if (packageName.endsWith("/")) {
0784: localPackageName = packageName;
0785: } else {
0786: localPackageName = packageName + '/';
0787: }
0788:
0789: ClassLoader cl = Misc.class.getClassLoader();
0790: if (MainFrame.getMainInstance() != null) {
0791: cl = MainFrame.getMainInstance().getReportClassLoader();
0792: }
0793:
0794: Enumeration dirEnum = cl.getResources(localPackageName);
0795:
0796: Set names = new HashSet();
0797:
0798: // Loop CLASSPATH directories
0799: while (dirEnum.hasMoreElements()) {
0800: URL resUrl = (URL) dirEnum.nextElement();
0801:
0802: // Pointing to filesystem directory
0803: if (resUrl.getProtocol().equals("file")) {
0804: try {
0805: File dir = new File(resUrl.getFile());
0806: File[] files = dir.listFiles();
0807: if (files != null) {
0808: for (int i = 0; i < files.length; i++) {
0809: File file = files[i];
0810: if (file.isDirectory())
0811: continue;
0812: names
0813: .add(localPackageName
0814: + file.getName());
0815: }
0816: }
0817: } catch (Exception ex) {
0818: ex.printStackTrace();
0819: }
0820:
0821: // Pointing to Jar file
0822: } else if (resUrl.getProtocol().equals("jar")) {
0823: JarURLConnection jconn = (JarURLConnection) resUrl
0824: .openConnection();
0825: JarFile jfile = jconn.getJarFile();
0826: Enumeration entryEnum = jfile.entries();
0827: while (entryEnum.hasMoreElements()) {
0828: JarEntry entry = (JarEntry) entryEnum.nextElement();
0829: String entryName = entry.getName();
0830: // Exclude our own directory
0831: if (entryName.equals(localPackageName))
0832: continue;
0833: String parentDirName = entryName.substring(0,
0834: entryName.lastIndexOf('/') + 1);
0835: if (!parentDirName.equals(localPackageName))
0836: continue;
0837: names.add(entryName);
0838: }
0839: } else {
0840: // Invalid classpath entry
0841: }
0842: }
0843:
0844: return names;
0845: }
0846:
0847: /**
0848: * Take a filename, strip out the extension and append the new extension
0849: * newExtension = ".xyz" or "xyz"
0850: * If filename is null, ".xyz" is returned
0851: */
0852: public static String changeFileExtension(String filename,
0853: String newExtension) {
0854: if (!newExtension.startsWith("."))
0855: newExtension = "." + newExtension;
0856: if (filename == null || filename.length() == 0) {
0857: return newExtension;
0858: }
0859:
0860: int index = filename.lastIndexOf(".");
0861: if (index >= 0) {
0862: filename = filename.substring(0, index);
0863: }
0864: return filename += newExtension;
0865: }
0866:
0867: /**
0868: * Take a string like _it_IT or it_IT or it
0869: * and return the right locale
0870: * Default return value is Locale.getDefault()
0871: */
0872: static public java.util.Locale getLocaleFromString(String localeName) {
0873: return getLocaleFromString(localeName, Locale.getDefault());
0874: }
0875:
0876: /**
0877: * Take a string like _it_IT or it_IT or it
0878: * and return the right locale
0879: *
0880: */
0881: static public java.util.Locale getLocaleFromString(
0882: String localeName, Locale defaultLocale) {
0883: String language = "";
0884: String country = "";
0885: String variant = "";
0886: Locale locale = defaultLocale;
0887:
0888: if (localeName == null || localeName.length() == 0)
0889: return locale;
0890: if (localeName.startsWith("_"))
0891: localeName = localeName.substring(1);
0892: if (localeName.indexOf("_") > 0) {
0893: language = localeName.substring(0, localeName.indexOf("_"));
0894: localeName = localeName
0895: .substring(localeName.indexOf("_") + 1);
0896:
0897: if (localeName.indexOf("_") > 0) {
0898: country = localeName.substring(0, localeName
0899: .indexOf("_"));
0900: localeName = localeName.substring(localeName
0901: .indexOf("_") + 1);
0902:
0903: if (localeName.indexOf("_") > 0) {
0904: variant = localeName.substring(0, localeName
0905: .indexOf("_"));
0906: localeName = localeName.substring(localeName
0907: .indexOf("_") + 1);
0908: } else {
0909: variant = localeName;
0910: }
0911: } else {
0912: country = localeName;
0913: }
0914: } else {
0915: language = localeName;
0916: }
0917:
0918: locale = new Locale(language, country, variant);
0919:
0920: return locale;
0921: }
0922:
0923: public static void setComboboxSelectedTagValue(
0924: javax.swing.JComboBox comboBox, String itemValue) {
0925: for (int i = 0; i < comboBox.getItemCount(); ++i) {
0926: Object val = comboBox.getItemAt(i);
0927: if (val instanceof it.businesslogic.ireport.gui.sheet.Tag) {
0928: if (((it.businesslogic.ireport.gui.sheet.Tag) val)
0929: .getValue().equals(itemValue)) {
0930: comboBox.setSelectedIndex(i);
0931: break;
0932: }
0933: }
0934: }
0935: }
0936:
0937: /**
0938: * Return the named connection configured in iReport
0939: * Return a java.sql.Connection;
0940: */
0941: public static java.sql.Connection getConnection(String name) {
0942: Vector v = MainFrame.getMainInstance().getConnections();
0943: for (int i = 0; i < v.size(); ++i) {
0944: IReportConnection irc = (IReportConnection) v.get(i);
0945: if (irc.getName().equals(name)) {
0946: return irc.getConnection();
0947: }
0948: }
0949:
0950: return null;
0951: }
0952:
0953: /**
0954: * Return the named connection configured in iReport
0955: * Return a net.sf.jasperreports.engine.getJRDataSource
0956: */
0957: public static net.sf.jasperreports.engine.JRDataSource getJRDataSource(
0958: String name) {
0959: Vector v = MainFrame.getMainInstance().getConnections();
0960: for (int i = 0; i < v.size(); ++i) {
0961: IReportConnection irc = (IReportConnection) v.get(i);
0962: if (irc.getName().equals(name)) {
0963: return irc.getJRDataSource();
0964: }
0965: }
0966:
0967: return null;
0968: }
0969:
0970: public static Vector loadStyleLibrary(String fileName) {
0971: Vector v = new Vector();
0972: try {
0973:
0974: File f = new File(fileName);
0975: InputStream fis = null;
0976:
0977: if (!f.exists()) {
0978: fis = Misc.class
0979: .getClassLoader()
0980: .getResourceAsStream(
0981: "it/businesslogic/ireport/res/defaultStyleLibrary.xml");
0982: fileName = ""
0983: + Misc.class
0984: .getClassLoader()
0985: .getResource(
0986: "it/businesslogic/ireport/res/defaultStyleLibrary.xml");
0987: } else {
0988: fis = new FileInputStream(f);
0989: fileName = "file:///" + fileName;
0990: }
0991:
0992: v.addAll(loadStyleLibrary(fis, fileName));
0993: } catch (Exception ex) {
0994: ex.printStackTrace();
0995: }
0996:
0997: return v;
0998: }
0999:
1000: public static Vector loadStyleLibrary(InputStream is,
1001: String filename) {
1002: Vector v = new Vector();
1003: try {
1004: DOMParser parser = new DOMParser();
1005: org.xml.sax.InputSource input_sss = new org.xml.sax.InputSource(
1006: is);
1007: //input_sss.setSystemId(filename);
1008: parser.parse(input_sss);
1009:
1010: Document document = parser.getDocument();
1011: Node node = document.getDocumentElement();
1012:
1013: NodeList list_child = node.getChildNodes();
1014: for (int ck = 0; ck < list_child.getLength(); ck++) {
1015: Node styleNode = (Node) list_child.item(ck);
1016: if (styleNode.getNodeName() != null
1017: && styleNode.getNodeName().equals("style")) {
1018: Style s = readStyle(styleNode, null);
1019: v.add(s);
1020: }
1021: }
1022: } catch (Exception ex) {
1023: ex.printStackTrace();
1024: }
1025:
1026: return v;
1027: }
1028:
1029: /**
1030: * If a ConditionedStyle, the style is interpreted like part of the tag conditionalStyle
1031: */
1032: public static it.businesslogic.ireport.Style readStyle(
1033: Node styleNode, ConditionedStyle cStyle) {
1034: Style style = new Style();
1035: if (cStyle != null)
1036: style = cStyle;
1037: NamedNodeMap nnm = styleNode.getAttributes();
1038:
1039: for (int i = 0; i < Style.JRXMLStyleAttributes.length; ++i) {
1040: if (nnm.getNamedItem(Style.JRXMLStyleAttributes[i]) != null) {
1041: style.getAttributes().put(
1042: Style.JRXMLStyleAttributes[i],
1043: nnm.getNamedItem(Style.JRXMLStyleAttributes[i])
1044: .getNodeValue());
1045: }
1046: }
1047:
1048: //conditionalStyle
1049: // Check for description and expression...
1050: NodeList children = styleNode.getChildNodes();
1051: if (children != null) {
1052: for (int k = 0; k < children.getLength(); k++) {
1053: Node nodeChild = (Node) children.item(k);
1054: if (nodeChild.getNodeType() == Node.ELEMENT_NODE
1055: && nodeChild.getNodeName().equals(
1056: "conditionalStyle")) {
1057: ConditionedStyle childStyle = readConditionalStyle(nodeChild);
1058: style.getConditionedStyles().add(childStyle);
1059: }
1060: }
1061: }
1062:
1063: return style;
1064: }
1065:
1066: /**
1067: * If a ConditionedStyle, the style is interpreted like part of the tag conditionalStyle
1068: */
1069: private static it.businesslogic.ireport.ConditionedStyle readConditionalStyle(
1070: Node styleNode) {
1071: ConditionedStyle style = new ConditionedStyle();
1072:
1073: //conditionalStyle
1074: // Check for description and expression...
1075: NodeList children = styleNode.getChildNodes();
1076: if (children != null) {
1077: for (int k = 0; k < children.getLength(); k++) {
1078: Node nodeChild = (Node) children.item(k);
1079: if (nodeChild.getNodeType() == Node.ELEMENT_NODE
1080: && nodeChild.getNodeName().equals(
1081: "conditionExpression")) {
1082: style.setCondition(Report.readPCDATA(nodeChild));
1083: } else if (nodeChild.getNodeType() == Node.ELEMENT_NODE
1084: && nodeChild.getNodeName().equals("style")) {
1085: style = (ConditionedStyle) readStyle(nodeChild,
1086: style);
1087: }
1088: }
1089: }
1090:
1091: return style;
1092: }
1093:
1094: public static void saveStyleLibrary(String filename, Vector styles) {
1095: try {
1096: PrintWriter pw = new PrintWriter(
1097: new java.io.OutputStreamWriter(
1098: new java.io.FileOutputStream(filename),
1099: "UTF8")); //UTF8
1100:
1101: pw.print("<?xml version=\"1.0\"?>");
1102: pw.println("<!-- iReport styles library -->");
1103: pw.println("<styles>");
1104:
1105: writeXMLStyles(styles, pw, "\t");
1106: pw.println("</styles>");
1107:
1108: pw.close();
1109:
1110: } catch (Exception ex) {
1111: JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
1112: I18n.getFormattedString(
1113: "messages.misc.errorSavingStyles",
1114: "Error saving styles library: {0}",
1115: new Object[] { ex.getMessage() }));
1116: ex.printStackTrace();
1117: }
1118: }
1119:
1120: private static void writeXMLStyles(Vector styles,
1121: java.io.PrintWriter pw, String tabs) {
1122:
1123: Enumeration e = styles.elements();
1124: if (styles.size() > 0)
1125: pw.println("");
1126: while (e.hasMoreElements()) {
1127: it.businesslogic.ireport.Style style = (it.businesslogic.ireport.Style) e
1128: .nextElement();
1129:
1130: String tabs2 = tabs;
1131: if (style instanceof ConditionedStyle) {
1132: pw.println(tabs2 + "<conditionalStyle>");
1133: tabs += "\t";
1134: pw.print(tabs + "<conditionExpression");
1135: pw.println(">"
1136: + Report.getCDATAString(
1137: ((ConditionedStyle) style)
1138: .getCondition(),
1139: tabs2.length() + 1)
1140: + "</conditionExpression>");
1141: }
1142: pw.println(tabs + "<style ");
1143: for (int i = 0; i < Style.JRXMLStyleAttributes.length; ++i) {
1144: if (style.getAttributes().containsKey(
1145: Style.JRXMLStyleAttributes[i])
1146: && style.getAttributes().get(
1147: Style.JRXMLStyleAttributes[i]) != null) {
1148: Object obj = style.getAttributes().get(
1149: Style.JRXMLStyleAttributes[i]);
1150: String value = "" + obj;
1151: if (obj instanceof java.awt.Color) {
1152: value = Report
1153: .writeEncodedColor((java.awt.Color) obj);
1154: }
1155: if (Style.JRXMLStyleAttributes[i].toLowerCase()
1156: .endsWith("color")
1157: && value.startsWith("[")) {
1158: // The color is in the form [r,g,b]...
1159: try {
1160: value = Report
1161: .writeEncodedColor(it.businesslogic.ireport.gui.sheet.ColorSelectorPanel
1162: .parseColorString(value));
1163: } catch (Exception ex) {
1164: value = "black";
1165: }
1166: }
1167: if (Style.JRXMLStyleAttributes[i].equals("style")) {
1168: if (value == null || value.trim().length() == 0)
1169: continue;
1170: }
1171: pw.println(tabs + "\t"
1172: + Style.JRXMLStyleAttributes[i] + "=\""
1173: + value + "\"");
1174: }
1175: }
1176:
1177: if (style.getConditionedStyles().size() == 0) {
1178: pw.println(tabs + "/>");
1179: } else {
1180: pw.println(tabs + ">");
1181: writeXMLStyles(style.getConditionedStyles(), pw, tabs
1182: + "\t");
1183: pw.println(tabs + "</style>");
1184: }
1185: if (style instanceof ConditionedStyle) {
1186: pw.println(tabs2 + "</conditionalStyle>");
1187: }
1188: }
1189: }
1190:
1191: /**
1192: * Save the query asking for a file.
1193: * see saveSQLQuery(String query, Component c)
1194: */
1195: public static boolean saveSQLQuery(String query) {
1196: return saveSQLQuery(query, MainFrame.getMainInstance());
1197: }
1198:
1199: /**
1200: * Save the query asking for a file.
1201: * The optional component is used as parent for the file selection dialog
1202: * Default is the MainFrame
1203: */
1204: public static boolean saveSQLQuery(String query, Component c) {
1205: JFileChooser jfc = new JFileChooser();
1206: jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
1207: public boolean accept(java.io.File file) {
1208: String filename = file.getName().toLowerCase();
1209: return (filename.endsWith(".sql")
1210: || filename.endsWith(".txt") || file
1211: .isDirectory());
1212: }
1213:
1214: public String getDescription() {
1215: return "SQL query (*.sql, *.txt)";
1216: }
1217: });
1218:
1219: if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) {
1220:
1221: try {
1222:
1223: String fileName = jfc.getSelectedFile().getName();
1224: if (fileName.indexOf(".") < 0) {
1225: fileName += ".sql";
1226: }
1227:
1228: File f = new File(jfc.getSelectedFile().getParent(),
1229: fileName);
1230:
1231: FileWriter fw = new FileWriter(f);
1232: fw.write(query);
1233: fw.close();
1234:
1235: return true;
1236: } catch (Exception ex) {
1237: JOptionPane.showMessageDialog(c,
1238: "Error saving the query: " + ex.getMessage(),
1239: I18n.getString("message.title.error", "Error"),
1240: JOptionPane.ERROR_MESSAGE);
1241: ex.printStackTrace();
1242: }
1243: }
1244:
1245: return false;
1246: }
1247:
1248: /**
1249: * See loadSQLQuery(Component c)
1250: */
1251: public static String loadSQLQuery() {
1252: return loadSQLQuery(MainFrame.getMainInstance());
1253: }
1254:
1255: /**
1256: * Load the query asking for a file.
1257: * The optional component is used as parent for the file selection dialog
1258: * Default is the MainFrame
1259: */
1260: public static String loadSQLQuery(Component c) {
1261: JFileChooser jfc = new JFileChooser();
1262: jfc.setMultiSelectionEnabled(false);
1263: jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
1264: public boolean accept(java.io.File file) {
1265: String filename = file.getName().toLowerCase();
1266: return (filename.endsWith(".sql")
1267: || filename.endsWith(".txt") || file
1268: .isDirectory());
1269: }
1270:
1271: public String getDescription() {
1272: return "SQL query (*.sql, *.txt)";
1273: }
1274: });
1275:
1276: if (jfc.showOpenDialog(c) == JFileChooser.APPROVE_OPTION) {
1277:
1278: try {
1279:
1280: FileReader fr = new FileReader(jfc.getSelectedFile());
1281: StringBuffer sb = new StringBuffer();
1282: char[] cbuf = new char[1024];
1283: int i = fr.read(cbuf);
1284: while (i > 0) {
1285: sb.append(cbuf, 0, i);
1286: i = fr.read(cbuf);
1287: }
1288: fr.close();
1289:
1290: return sb.toString();
1291: } catch (Exception ex) {
1292: JOptionPane.showMessageDialog(c,
1293: "Error loading the query: " + ex.getMessage(),
1294: I18n.getString("message.title.error", "Error"),
1295: JOptionPane.ERROR_MESSAGE);
1296: ex.printStackTrace();
1297: }
1298: }
1299:
1300: return null;
1301: }
1302:
1303: /**
1304: * Save the expressions list to the specified file...
1305: */
1306: public static boolean saveExpressionsList(Vector v, String xmlFile) {
1307: // Get the path of this class...
1308: // this.getClass().getResource("MainFrame");
1309: try {
1310: PrintWriter pw = new PrintWriter(new FileWriter(xmlFile));
1311: // Find iReport configuration in the home directory...
1312: // 1. Save all properties using am XML style...
1313: pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
1314: pw.println("<!-- iReport 2 expressions list - "
1315: + new Date() + " -->");
1316: pw
1317: .println("<!DOCTYPE iReportExpressionsList PUBLIC \"-//iReport/DTD iReport Configuration//EN\" \"http://ireport.sourceforge.net/dtds/iReportExpressionsList.dtd\">");
1318: pw.println("<iReportExpressionsList>");
1319:
1320: Enumeration e = v.elements();
1321:
1322: while (e.hasMoreElements()) {
1323: String exp = (String) e.nextElement();
1324: pw.println("\t<expression><![CDATA[" + exp
1325: + "]]></expression>");
1326: }
1327: pw.println("</iReportExpressionsList>");
1328: pw.close();
1329: } catch (Exception ex) {
1330: //ex.printStackTrace(s
1331: try {
1332: MainFrame.getMainInstance().logOnConsole(
1333: "Error saving iReport file: " + xmlFile + "\n"
1334: + ex.getMessage() + "\n");
1335:
1336: } catch (Exception exsx) {
1337: }
1338: return false;
1339: }
1340: try {
1341: MainFrame.getMainInstance().logOnConsole(
1342: "iReport file " + xmlFile
1343: + " successfully updated!\n");
1344: } catch (Exception ex) {
1345: }
1346: return true;
1347: }
1348:
1349: /**
1350: * Read the expressions list from the specified file...
1351: */
1352: public static Vector loadExpressionsList(String xmlFile) {
1353: File file = null;
1354: Vector v = new Vector();
1355: try {
1356: file = new File(xmlFile);
1357: } catch (Exception ex) {
1358: }
1359: if (file == null || !file.exists() || file.isDirectory()) {
1360:
1361: return ExpressionEditor.defaultExpressions;
1362: }
1363: // Create a Xerces DOM Parser
1364: DOMParser parser = new DOMParser();
1365: // Parse the Document
1366: // and traverse the DOM
1367: try {
1368:
1369: parser.setEntityResolver(new org.xml.sax.EntityResolver() {
1370: /* Code by Teodor Danciu */
1371: public org.xml.sax.InputSource resolveEntity(
1372: String publicId, String systemId)
1373: throws SAXException//, java.io.IOException
1374: {
1375: org.xml.sax.InputSource inputSource = null;
1376:
1377: if (systemId != null) {
1378: String dtd = null;
1379:
1380: if (systemId
1381: .equals("http://ireport.sourceforge.net/dtds/iReportExpressionsList.dtd")) {
1382: dtd = "it/businesslogic/ireport/dtds/iReportExpressionsList.dtd";
1383: } else {
1384: return new org.xml.sax.InputSource(systemId);
1385: }
1386:
1387: ClassLoader classLoader = this .getClass()
1388: .getClassLoader();
1389:
1390: java.net.URL url = null;
1391:
1392: if (classLoader != null) {
1393: url = classLoader.getResource(dtd);
1394: }
1395: if (url == null) {
1396: classLoader = this .getClass()
1397: .getClassLoader();
1398: }
1399:
1400: java.io.InputStream is = classLoader
1401: .getResourceAsStream(dtd);
1402: if (is != null) {
1403: java.io.InputStreamReader isr = new java.io.InputStreamReader(
1404: is);
1405: inputSource = new org.xml.sax.InputSource(
1406: isr);
1407: }
1408:
1409: }
1410:
1411: return inputSource;
1412: }
1413: });
1414: /* End Code by Teodor Danciu */
1415: parser.parse(new java.io.File(xmlFile).toURI().toString());
1416: Document document = parser.getDocument();
1417:
1418: // Traverse the tree until we don't find a iReportFilesList element...
1419: System.out.println("FL3: " + document.getDocumentElement());
1420: Node fileList = document.getDocumentElement();
1421: //System.out.println("FL: " + fileList);
1422: if (fileList == null)
1423: return v;
1424: NodeList list = fileList.getChildNodes();
1425: for (int i = 0; i < list.getLength(); ++i) {
1426: Node child = list.item(i);
1427: //System.out.println("FL: " + i + ">>" + child);
1428: if (child.getNodeType() == Node.ELEMENT_NODE
1429: && child.getNodeName().equals("expression")) {
1430: String expression = Report.readPCDATA(child);
1431: if (expression != null
1432: && expression.trim().length() > 0) {
1433: v.addElement(expression);
1434: }
1435: }
1436: }
1437:
1438: } catch (Exception ex) {
1439: }
1440:
1441: return v;
1442: }
1443:
1444: /*
1445: public static Style getDefaultStyle(ReportElement re)
1446: {
1447: // 1. Look for the report to wich this element belong...
1448: JReportFrame frames = MainFrame.getMainInstance()
1449: }
1450:
1451: public static Report getReportByBand(Band b)
1452: {
1453:
1454: }
1455:
1456: public static Report getReportByReportElement(ReportElement re)
1457: {
1458: if (re instanceof CrosstabReportElement)
1459: {
1460:
1461: }
1462: }
1463: */
1464:
1465: /**
1466: * side can be:
1467: * DockingConstants.NOTRH_REGION
1468: * DockingConstants.EAST_REGION
1469: * DockingConstants.SOUTH_REGION
1470: * DockingConstants.WEST_REGION
1471: *
1472: * index is the position into a side
1473: *
1474: * i.e.
1475: * dockAt( dockable, DockingConstants.WEST_REGION, 0) means the top left position
1476: *
1477: *
1478: */
1479: static public boolean dockAt(Dockable toDock, String side, int index) {
1480: Dockable rootDockable = MainFrame.getMainInstance()
1481: .getDesktopView();
1482: Dockable dockable = rootDockable;
1483:
1484: String directionV = null;
1485: String directionH = null;
1486: String directionIndex = null;
1487:
1488: if (side.equals(DockingConstants.NORTH_REGION)) {
1489: directionV = DockingConstants.NORTH_REGION;
1490: directionH = DockingConstants.WEST_REGION;
1491: directionIndex = DockingConstants.EAST_REGION;
1492: }
1493: if (side.equals(DockingConstants.WEST_REGION)) {
1494: directionV = DockingConstants.NORTH_REGION;
1495: directionH = DockingConstants.WEST_REGION;
1496: directionIndex = DockingConstants.SOUTH_REGION;
1497: }
1498: if (side.equals(DockingConstants.EAST_REGION)) {
1499: directionV = DockingConstants.NORTH_REGION;
1500: directionH = DockingConstants.EAST_REGION;
1501: directionIndex = DockingConstants.SOUTH_REGION;
1502: }
1503: if (side.equals(DockingConstants.SOUTH_REGION)) {
1504: directionV = DockingConstants.SOUTH_REGION;
1505: directionH = DockingConstants.WEST_REGION;
1506: directionIndex = DockingConstants.EAST_REGION;
1507: }
1508:
1509: String counterDirectionIndex = null;
1510: if (directionIndex.equals(DockingConstants.NORTH_REGION))
1511: counterDirectionIndex = DockingConstants.SOUTH_REGION;
1512: if (directionIndex.equals(DockingConstants.SOUTH_REGION))
1513: counterDirectionIndex = DockingConstants.NORTH_REGION;
1514: if (directionIndex.equals(DockingConstants.WEST_REGION))
1515: counterDirectionIndex = DockingConstants.EAST_REGION;
1516: if (directionIndex.equals(DockingConstants.EAST_REGION))
1517: counterDirectionIndex = DockingConstants.WEST_REGION;
1518:
1519: try {
1520: if (((View) rootDockable).getSibling(side) != null) {
1521: dockable = ((View) rootDockable).getSibling(side);
1522: while (DefaultDockingStrategy.getSibling(dockable,
1523: directionV) != null
1524: || DefaultDockingStrategy.getSibling(dockable,
1525: directionH) != null) {
1526: Dockable tmp = DefaultDockingStrategy.getSibling(
1527: dockable, directionV);
1528: dockable = (tmp != null) ? tmp
1529: : DefaultDockingStrategy.getSibling(
1530: dockable, directionH);
1531: }
1532: }
1533:
1534: } catch (Throwable ex) {
1535:
1536: ex.printStackTrace();
1537: }
1538:
1539: if (dockable == rootDockable) // there are no siblings in side direction...
1540: {
1541:
1542: return dockable.dock(toDock, side);
1543: }
1544:
1545: // dockable is now the root...
1546: // Go in the indexDirection for index times (if possible)...
1547: int i = 0;
1548: for (i = 0; i < index; ++i) {
1549: // Look for the right sibling..
1550: try {
1551: System.out.println("Index " + i);
1552: if (DefaultDockingStrategy.getSibling(dockable,
1553: directionIndex) == null)
1554: break;
1555: dockable = DefaultDockingStrategy.getSibling(dockable,
1556: directionIndex);
1557:
1558: } catch (Throwable ex) {
1559:
1560: ex.printStackTrace();
1561: }
1562: }
1563:
1564: if (i == index) {
1565:
1566: return dockable.dock(toDock, counterDirectionIndex);
1567: } else {
1568: return dockable.dock(toDock, directionIndex);
1569: }
1570:
1571: }
1572:
1573: /**
1574: * Save the expression asking for a file.
1575: * see saveSQLQuery(String query, Component c)
1576: */
1577: public static boolean saveExpression(String expression) {
1578: return saveExpression(expression, MainFrame.getMainInstance());
1579: }
1580:
1581: /**
1582: * Save the query asking for a file.
1583: * The optional component is used as parent for the file selection dialog
1584: * Default is the MainFrame
1585: */
1586: public static boolean saveExpression(String expression, Component c) {
1587: JFileChooser jfc = new JFileChooser();
1588: jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
1589: public boolean accept(java.io.File file) {
1590: String filename = file.getName().toLowerCase();
1591: return (filename.endsWith(".txt") || file.isDirectory());
1592: }
1593:
1594: public String getDescription() {
1595: return "Text file (*.txt)";
1596: }
1597: });
1598:
1599: if (jfc.showSaveDialog(c) == JFileChooser.APPROVE_OPTION) {
1600:
1601: try {
1602:
1603: String fileName = jfc.getSelectedFile().getName();
1604: if (fileName.indexOf(".") < 0) {
1605: fileName += ".txt";
1606: }
1607:
1608: File f = new File(jfc.getSelectedFile().getParent(),
1609: fileName);
1610:
1611: FileWriter fw = new FileWriter(f);
1612: fw.write(expression);
1613: fw.close();
1614:
1615: return true;
1616: } catch (Exception ex) {
1617: JOptionPane.showMessageDialog(c,
1618: "Error saving the expression: "
1619: + ex.getMessage(), I18n.getString(
1620: "message.title.error", "Error"),
1621: JOptionPane.ERROR_MESSAGE);
1622: ex.printStackTrace();
1623: }
1624: }
1625:
1626: return false;
1627: }
1628:
1629: /**
1630: * See loadSQLQuery(Component c)
1631: */
1632: public static String loadExpression() {
1633: return loadExpression(MainFrame.getMainInstance());
1634: }
1635:
1636: /**
1637: * Load the query asking for a file.
1638: * The optional component is used as parent for the file selection dialog
1639: * Default is the MainFrame
1640: */
1641: public static String loadExpression(Component c) {
1642: JFileChooser jfc = new JFileChooser();
1643: jfc.setMultiSelectionEnabled(false);
1644: jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
1645: public boolean accept(java.io.File file) {
1646: String filename = file.getName().toLowerCase();
1647: return (filename.endsWith(".txt") || file.isDirectory());
1648: }
1649:
1650: public String getDescription() {
1651: return "Text file (*.txt)";
1652: }
1653: });
1654:
1655: if (jfc.showOpenDialog(c) == JFileChooser.APPROVE_OPTION) {
1656:
1657: try {
1658:
1659: FileReader fr = new FileReader(jfc.getSelectedFile());
1660: StringBuffer sb = new StringBuffer();
1661: char[] cbuf = new char[1024];
1662: int i = fr.read(cbuf);
1663: while (i > 0) {
1664: sb.append(cbuf, 0, i);
1665: i = fr.read(cbuf);
1666: }
1667: fr.close();
1668:
1669: return sb.toString();
1670: } catch (Exception ex) {
1671: JOptionPane.showMessageDialog(c,
1672: "Error loading the expression: "
1673: + ex.getMessage(), I18n.getString(
1674: "message.title.error", "Error"),
1675: JOptionPane.ERROR_MESSAGE);
1676: ex.printStackTrace();
1677: }
1678: }
1679:
1680: return null;
1681: }
1682:
1683: /** This method uses the code from: http://www.centerkey.com/java/browser/
1684: *
1685: * Bare Bones Browser Launch
1686: * Version 1.5
1687: * December 10, 2005
1688: * Supports: Mac OS X, GNU/Linux, Unix, Windows XP
1689: * Example Usage:
1690: * String url = "http://www.centerkey.com/";
1691: * BareBonesBrowserLaunch.openURL(url);
1692: * Public Domain Software -- Free to Use as You Like
1693: *
1694: **/
1695: public static void openURL(String url) {
1696:
1697: String osName = System.getProperty("os.name");
1698: try {
1699: if (osName.startsWith("Mac OS")) {
1700: Class fileMgr = Class
1701: .forName("com.apple.eio.FileManager");
1702: java.lang.reflect.Method openURL = fileMgr
1703: .getDeclaredMethod("openURL",
1704: new Class[] { String.class });
1705: openURL.invoke(null, new Object[] { url });
1706: } else if (osName.startsWith("Windows"))
1707: Runtime.getRuntime().exec(
1708: "rundll32 url.dll,FileProtocolHandler " + url);
1709: else { //assume Unix or Linux
1710: String[] browsers = { "firefox", "opera", "konqueror",
1711: "epiphany", "mozilla", "netscape", "htmlview" };
1712: String browser = null;
1713: for (int count = 0; count < browsers.length
1714: && browser == null; count++) {
1715: if (Runtime.getRuntime().exec(
1716: new String[] { "which", browsers[count] })
1717: .waitFor() == 0) {
1718: browser = browsers[count];
1719: }
1720: }
1721: if (browser == null)
1722: throw new Exception(I18n.getString(
1723: "misc.browserNotFound",
1724: "Could not find web browser"));
1725: else
1726: Runtime.getRuntime().exec(
1727: new String[] { browser, url });
1728: }
1729: } catch (Exception e) {
1730: JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
1731: I18n.getString("misc.browserLunchError",
1732: "Error attempting to launch web browser")
1733: + "\n" + e.getLocalizedMessage());
1734: }
1735: }
1736:
1737: /**
1738: * If the selected value is a Tag, tag.getValue is returned,
1739: * otherwise the selected item itself is returned.
1740: * If not item is selected, the method return null.
1741: */
1742: public static Object getComboboxSelectedValue(JComboBox combo) {
1743: Object result = null;
1744: if (combo != null) {
1745: result = combo.getSelectedItem();
1746: if (result != null && result instanceof Tag) {
1747: return ((Tag) result).getValue();
1748: }
1749: }
1750: return result;
1751: }
1752:
1753: /**
1754: * Creates fileName inside <user home>/classes/it/businesslogic/ireport/locale
1755: * and stores there the properties keys
1756: */
1757: public static void saveTemporaryLocale(
1758: java.util.Properties properties, String fileName) {
1759: if (properties == null)
1760: return;
1761: // Save in the user directory....
1762: String dir = MainFrame.getMainInstance().IREPORT_USER_HOME_DIR
1763: + File.separator + "classes" + File.separator + "it"
1764: + File.separator + "businesslogic" + File.separator
1765: + "ireport" + File.separator + "locale";
1766: File fdir = new File(dir);
1767: if (!fdir.exists()) {
1768: fdir.mkdirs();
1769: if (!fdir.exists()) {
1770: JOptionPane
1771: .showMessageDialog(
1772: null,
1773: I18n
1774: .getFormattedString(
1775: "translationStatusDialog.messages.unableToCreateDir",
1776: "Unable to create directory: {0}",
1777: new Object[] { ""
1778: + fdir }));
1779: return;
1780: }
1781: }
1782: try {
1783: File outFile = new File(fdir, fileName);
1784:
1785: properties.store(new FileOutputStream(outFile), "");
1786:
1787: } catch (Exception ex) {
1788: ex.printStackTrace();
1789: }
1790: }
1791:
1792: /**
1793: * If treePath is not in the current jTree selection, set it as selected.
1794: *
1795: */
1796: public static void ensurePathIsSelected(TreePath treePath,
1797: JTree jTree) {
1798: if (jTree == null || treePath == null)
1799: return;
1800:
1801: TreePath[] selectedPaths = jTree.getSelectionPaths();
1802: for (int i = 0; selectedPaths != null
1803: && i < selectedPaths.length; ++i) {
1804: if (selectedPaths[i].equals(treePath))
1805: return;
1806: }
1807: jTree.setSelectionPath(treePath);
1808: }
1809:
1810: /**
1811: * This method select the whole text inside a textarea and set there the focus.
1812: * It should be used to select a component that contains a wrong expression.
1813: * In the future other properties of the componenct can be modified
1814: */
1815: public static void selectTextAndFocusArea(final JComponent expArea) {
1816: if (expArea == null)
1817: return;
1818:
1819: if (expArea instanceof JRTextExpressionArea) {
1820: ((JRTextExpressionArea) expArea).setSelectionStart(0);
1821: ((JRTextExpressionArea) expArea)
1822: .setSelectionEnd(((JRTextExpressionArea) expArea)
1823: .getText().length());
1824: ((JRTextExpressionArea) expArea).setHasErrors(true);
1825: } else if (expArea instanceof JTextComponent) {
1826: ((JTextComponent) expArea).setSelectionStart(0);
1827: ((JTextComponent) expArea)
1828: .setSelectionEnd(((JTextComponent) expArea)
1829: .getText().length());
1830: ((JTextComponent) expArea).setBorder(new LineBorder(
1831: Color.RED.darker(), 2));
1832: }
1833:
1834: //Border b = expArea.getBorder();
1835:
1836: expArea.requestFocusInWindow();
1837: /*
1838: SwingUtilities.invokeLater( new Runnable() {
1839: public void run() {
1840:
1841: Graphics2D g = (Graphics2D)expArea.getGraphics();
1842: Stroke s = g.getStroke();
1843: g.setStroke( ReportElement.getPenStroke("4Point",1.0));
1844: g.setColor( ReportElement.getAlphaColor(Color.RED, 128) );
1845: g.drawRect(0,0,expArea.getWidth(), expArea.getHeight() );
1846: g.setStroke(s);
1847: }
1848: });
1849: */
1850: }
1851:
1852: /**
1853: * Find the DefaultMutableTreeNode containing the userObject as UserObject
1854: *
1855: * Returns null if node == null or userObject == null
1856: */
1857: public static DefaultMutableTreeNode findNodeWithUserObject(
1858: Object userObject, javax.swing.tree.TreeNode node) {
1859: if (node == null || userObject == null) {
1860: return null;
1861: }
1862:
1863: if (node instanceof DefaultMutableTreeNode) {
1864: DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) node;
1865: if (dmtn.getUserObject() != null
1866: && dmtn.getUserObject().equals(userObject))
1867: return dmtn;
1868: }
1869:
1870: // look in the children...
1871: for (int i = 0; i < node.getChildCount(); ++i) {
1872: DefaultMutableTreeNode dmtn = findNodeWithUserObject(
1873: userObject, node.getChildAt(i));
1874: if (dmtn != null)
1875: return dmtn;
1876: }
1877:
1878: return null;
1879:
1880: }
1881:
1882: /**
1883: * Add the properties in resourceUri to props.
1884: * If resourceUri does not exists, nothing happen.
1885: *
1886: */
1887: public static void addProperties(String resourceUri,
1888: java.util.Properties props) {
1889: try {
1890:
1891: InputStream is = Misc.class
1892: .getResourceAsStream(resourceUri);
1893: if (is == null)
1894: return;
1895: props.load(is);
1896: } catch (Exception ex) {
1897: ex.printStackTrace();
1898: }
1899: }
1900:
1901: /**
1902: * Get the content of a text resource file...
1903: *
1904: */
1905: public static String getResourceContent(String resourceUri) {
1906: String content = "";
1907: if (resourceUri == null)
1908: return content;
1909: try {
1910:
1911: InputStream is = Misc.class
1912: .getResourceAsStream(resourceUri);
1913: if (is == null)
1914: return content;
1915:
1916: LineNumberReader lnr = new LineNumberReader(
1917: new InputStreamReader(is));
1918: String line = null;
1919: boolean first = true;
1920: while ((line = lnr.readLine()) != null) {
1921: if (!first)
1922: content += "\n";
1923: content += line;
1924: first = false;
1925: }
1926:
1927: lnr.close();
1928:
1929: } catch (Exception ex) {
1930: ex.printStackTrace();
1931: }
1932:
1933: return content;
1934: }
1935:
1936: public static HashMap opTimes = new HashMap();
1937:
1938: /**
1939: * This function is used for debug porpuses. It is used to misure the time
1940: * of an operation.
1941: * Sample usage:
1942: * <pre><code>
1943: * ....some code
1944: * Misc.optime("My operation"); // Start the timer
1945: * ....block to measure....
1946: * Misc.optime("My operation"); // Stop the timer
1947: * </code></pre>
1948: * Result on video:
1949: * <pre><code>
1950: * My operation START (1)
1951: * My operation END (1) 20ms
1952: * </code></pre>
1953: */
1954: public static void optime(String opName) {
1955: long t = new java.util.Date().getTime();
1956: if (opTimes.containsKey(opName)) {
1957: long t0 = ((Long) opTimes.get(opName)).longValue();
1958: long opCounter = ((Long) opTimes.get(opName + "_coutner"))
1959: .longValue();
1960:
1961: opTimes.remove(opName);
1962: System.out.println(opName + " END (" + opCounter + ")\t"
1963: + (t - t0) + "ms");
1964: System.out.flush();
1965:
1966: } else {
1967: long opCounter = 0;
1968: opTimes.put(opName, new Long(t));
1969: if (opTimes.containsKey(opName + "_coutner")) {
1970: opCounter = ((Long) opTimes.get(opName + "_coutner"))
1971: .longValue();
1972: }
1973: opCounter++;
1974: opTimes.put(opName + "_coutner", new Long(opCounter));
1975: System.out.println(opName + " START (" + opCounter + ")");
1976: System.out.flush();
1977: }
1978: }
1979:
1980: /**
1981: * This method validates URL like:
1982: *
1983: * 123.123.123[:port]
1984: * domain.domain.dom[:port]
1985: *
1986: */
1987: public static boolean isValidUrl(String url) {
1988: String strRegex = "((([0-9]{1,3}\\.){3})[0-9]{1,3})" + // IP- 199.194.52.184
1989: "|" + // allows either IP or domain
1990: "(([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\.?)++" + // domain pice
1991: "(:[0-9]{1,4})?"; // port number- :80
1992:
1993: return url.matches(strRegex);
1994: }
1995:
1996: /**
1997: * Look for the SubDataset of an Object in the given report / subDataset.
1998: * If the subDataset is a report, it looks recursively in each subdataset...
1999: * @param report Report or SubDataset to look in
2000: * @param object Object to search for (Parameter, Field, Variable)
2001: *
2002: * @return a subdataset or null if the object is not found
2003: */
2004: public static SubDataset getObjectSubDataset(SubDataset report,
2005: Object object) {
2006: if (report.getParameters().contains(object))
2007: return report;
2008: if (report.getFields().contains(object))
2009: return report;
2010: if (report.getVariables().contains(object))
2011: return report;
2012:
2013: if (report instanceof Report) {
2014: for (int i = 0; i < ((Report) report).getSubDatasets()
2015: .size(); ++i) {
2016: SubDataset s = (SubDataset) ((Report) report)
2017: .getSubDatasets().get(i);
2018: if (getObjectSubDataset(s, object) != null) {
2019: return s;
2020: }
2021: }
2022: }
2023:
2024: return null;
2025: }
2026:
2027: public static final KeyListener ARABIC_KEY_LISTENER = new KeyListener() {
2028:
2029: boolean pressedRightShift = false;
2030: boolean pressedRightCtl = false;
2031:
2032: public void keyTyped(KeyEvent e) {
2033: }
2034:
2035: public void keyPressed(KeyEvent e) {
2036:
2037: if (pressedRightShift && pressedRightCtl)
2038: return;
2039:
2040: if (e.getKeyCode() == KeyEvent.VK_SHIFT
2041: && e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) {
2042: pressedRightShift = true;
2043: } else if (e.getKeyCode() == KeyEvent.VK_CONTROL
2044: && e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) {
2045: pressedRightCtl = true;
2046: }
2047:
2048: if (pressedRightShift && pressedRightCtl) {
2049: if (e.getSource() instanceof JComponent) {
2050: ((JComponent) e.getSource())
2051: .setComponentOrientation((((JComponent) e
2052: .getSource())
2053: .getComponentOrientation()
2054: .equals(ComponentOrientation.RIGHT_TO_LEFT)) ? java.awt.ComponentOrientation.LEFT_TO_RIGHT
2055: : java.awt.ComponentOrientation.RIGHT_TO_LEFT);
2056: }
2057: }
2058: }
2059:
2060: public void keyReleased(KeyEvent e) {
2061:
2062: if (e.getKeyCode() == KeyEvent.VK_SHIFT
2063: && e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) {
2064: pressedRightShift = false;
2065: //System.out.println("Released: RIGHT SHIFT");
2066: }
2067: if (e.getKeyCode() == KeyEvent.VK_CONTROL
2068: && e.getKeyLocation() == KeyEvent.KEY_LOCATION_RIGHT) {
2069: pressedRightCtl = false;
2070: //System.out.println("Released: RIGHT CTL");
2071: }
2072: }
2073: };
2074:
2075: public static int getMaxBandHeight(Report report, Band band) {
2076: int available_height = report.getHeight()
2077: - report.getTopMargin() - report.getBottomMargin();
2078:
2079: String bname = band.getName();
2080: if (bname.equals("background"))
2081: return available_height;
2082: if (bname.equals("title") && report.isIsTitleNewPage())
2083: return available_height;
2084: if (bname.equals("summary") && report.isIsSummaryNewPage())
2085: return available_height;
2086: if (bname.equals("noData"))
2087: return available_height;
2088:
2089: // Group header should go with column/page header and footers...
2090: if (band.isGroupHeader() || band.isGroupFooter()) {
2091: if (!report.isIsTitleNewPage()) {
2092: available_height -= report.getBandByName("title")
2093: .getHeight();
2094: }
2095: available_height -= report.getBandByName("pageHeader")
2096: .getHeight();
2097: available_height -= report.getBandByName("pageFooter")
2098: .getHeight();
2099: available_height -= report.getBandByName("columnHeader")
2100: .getHeight();
2101: available_height -= report.getBandByName("columnFooter")
2102: .getHeight();
2103: } else if (bname.equals("lastPageFooter")) {
2104: available_height -= report.getBandByName("pageHeader")
2105: .getHeight();
2106: available_height -= report.getBandByName("columnHeader")
2107: .getHeight();
2108: available_height -= report.getBandByName("columnFooter")
2109: .getHeight();
2110: } else {
2111: if (!bname.equals("pageHeader"))
2112: available_height -= report.getBandByName("pageHeader")
2113: .getHeight();
2114: if (!bname.equals("columnHeader"))
2115: available_height -= report
2116: .getBandByName("columnHeader").getHeight();
2117: if (!bname.equals("columnFooter"))
2118: available_height -= report
2119: .getBandByName("columnFooter").getHeight();
2120: if (!bname.equals("detail"))
2121: available_height -= report.getBandByName("detail")
2122: .getHeight();
2123:
2124: }
2125:
2126: return available_height;
2127:
2128: }
2129: }//end class Misc
|