0001: package com.calipso.xmleditor;
0002:
0003: import org.w3c.dom.Node;
0004: import org.apache.log4j.FileAppender;
0005: import org.apache.log4j.PatternLayout;
0006: import org.apache.log4j.Logger;
0007: import org.apache.log4j.ConsoleAppender;
0008:
0009: import javax.swing.*;
0010: import javax.swing.tree.DefaultTreeModel;
0011: import java.awt.*;
0012: import java.awt.event.*;
0013: import java.io.*;
0014: import java.sql.*;
0015: import java.util.*;
0016:
0017: import com.calipso.reportgenerator.reportdefinitions.*;
0018: import com.calipso.reportgenerator.reportdefinitions.types.ReportDefinitionReportTypeType;
0019: import com.calipso.reportgenerator.common.*;
0020: import com.calipso.reportgenerator.client.ReportManagerService;
0021: import com.calipso.reportgenerator.userinterface.ExtensionFilter;
0022: import com.calipso.reportgenerator.common.ShowExceptionMessageDialog;
0023: import com.calipso.reportgenerator.common.InfoException;
0024:
0025: /**
0026: *
0027: * User: soliveri
0028: * Date: 24-sep-2003
0029: * Time: 17:42:50
0030: *
0031: */
0032:
0033: public class XmlEditorUI extends JFrame implements ActionListener {
0034:
0035: private JButton btAddNode;
0036: private JButton btDeleteNode;
0037: private JButton btFinish;
0038: private XmlEditorPanel pnlXmlEditor;
0039: private XmlEditorLoader xmlLoader;
0040: private JPanel pnlCenter;
0041: private XmlEditorConnectionPane connectionPane;
0042: private IReportManager reportManager = null;
0043: private String configPath = null;
0044: private ReportGeneratorConfiguration reportGeneratorConfiguration;
0045: private String reportDefinitionXsdPath;
0046: private String reportSourceDefinitionXsdPath;
0047: private String reportViewXsdPath;
0048: private XmlEditorMenu menuBar;
0049: private XmlEditorCache xmlCache;
0050: private static final String defaultErrorMsgTitle = "Error";
0051: private File currentXmlFile;
0052: private File currentXsdFile;
0053: private static Logger logger;
0054: private Map typeColumn = new HashMap();
0055:
0056: public File getCurrentXsdFile() {
0057: return currentXsdFile;
0058: }
0059:
0060: public void setCurrentXsdFile(File currentXsdFile) {
0061: setCurrentXmlFile(null);
0062: this .currentXsdFile = currentXsdFile;
0063: }
0064:
0065: /**
0066: * Inicializa la aplicacion y muestra el panel principal
0067: * @param path
0068: * @param args
0069: */
0070: public XmlEditorUI(String path, String args[]) {
0071: this .configPath = path;
0072: System.out.println("Init");
0073: getLogger().info(new String("Init"));
0074: try {
0075: reportGeneratorConfiguration = new ReportGeneratorConfiguration(
0076: ReportGeneratorConfiguration
0077: .getConfiguration(configPath));
0078: } catch (Exception e1) {
0079: JOptionPane.showMessageDialog(null, e1, "Init error",
0080: JOptionPane.ERROR_MESSAGE);
0081: System.exit(1);
0082: }
0083: Image icon = getReportGeneratorConfiguration().getImage("ICON");
0084: if (icon != null) {
0085: setIconImage(icon);
0086: }
0087: initializePaths();
0088: initialize();
0089: try {
0090: if ((args.length > 0) && (args[0] != null)
0091: && (args[0] != "")) {
0092: loadFromXml(true, args[0].toString());
0093: }
0094: } catch (Exception ee) {
0095: ee.printStackTrace();
0096: }
0097: }
0098:
0099: /**
0100: * Inicializa los path de los Xsd de los reportes segun los datos del reportGeneratorConfiguration
0101: */
0102: private void initializePaths() {
0103: reportDefinitionXsdPath = reportGeneratorConfiguration
0104: .getSourceReportSchemasPath()
0105: + "/" + "ReportDefinition.xsd";
0106: reportSourceDefinitionXsdPath = reportGeneratorConfiguration
0107: .getSourceReportSchemasPath()
0108: + "/" + "ReportSourceDefinition.xsd";
0109: reportViewXsdPath = reportGeneratorConfiguration
0110: .getSourceReportSchemasPath()
0111: + "/" + "ReportView.xsd";
0112: }
0113:
0114: private JMenuBar getMnuBar() {
0115: if (menuBar == null) {
0116: menuBar = new XmlEditorMenu(this );
0117: }
0118: return menuBar;
0119: }
0120:
0121: /**
0122: * Inicializa los paneles
0123: */
0124: private void initialize() {
0125: setTitle();
0126: LanguageTraslator.newLocaleFrom(reportGeneratorConfiguration
0127: .getLocaleLanguage(), reportGeneratorConfiguration
0128: .getCountry(), reportGeneratorConfiguration
0129: .getLanguagesPath());
0130: getContentPane().setLayout(new BorderLayout());
0131: setJMenuBar(getMnuBar());
0132: getContentPane().add(getCenterPanel(), BorderLayout.CENTER);
0133: getContentPane().add(getSouthPanel(), BorderLayout.SOUTH);
0134: addWindowListener(new Win());
0135: }
0136:
0137: private Component getSouthPanel() {
0138: JPanel panel = new JPanel();
0139: GridBagLayout bagLayout = new GridBagLayout();
0140: GridBagConstraints constraints = new GridBagConstraints();
0141: panel.setLayout(bagLayout);
0142:
0143: btAddNode = new JButton(LanguageTraslator.traslate("504"));
0144: btAddNode.addActionListener(this );
0145: panel.add(btAddNode);
0146: constraints.weightx = 30;
0147: constraints.weighty = 1;
0148: constraints.gridx = 0;
0149: constraints.gridy = 0;
0150: constraints.anchor = GridBagConstraints.EAST;
0151: constraints.fill = GridBagConstraints.PAGE_START;
0152: bagLayout.setConstraints(btAddNode, constraints);
0153:
0154: btDeleteNode = new JButton(LanguageTraslator.traslate("505"));
0155: btDeleteNode.addActionListener(this );
0156: panel.add(btDeleteNode);
0157: constraints.weightx = 1;
0158: constraints.weighty = 1;
0159: constraints.gridx = 1;
0160: constraints.gridy = 0;
0161: constraints.anchor = GridBagConstraints.EAST;
0162: constraints.fill = GridBagConstraints.HORIZONTAL;
0163: bagLayout.setConstraints(btDeleteNode, constraints);
0164:
0165: btFinish = new JButton(LanguageTraslator.traslate("506"));
0166: btFinish.addActionListener(this );
0167: panel.add(btFinish);
0168: constraints.weightx = 1;
0169: constraints.weighty = 1;
0170: constraints.gridx = 2;
0171: constraints.gridy = 0;
0172: constraints.anchor = GridBagConstraints.WEST;
0173: constraints.fill = GridBagConstraints.VERTICAL;
0174: bagLayout.setConstraints(btDeleteNode, constraints);
0175:
0176: return panel;
0177: }
0178:
0179: /**
0180: * Obtiene el panel central vacio
0181: * @return
0182: */
0183: private Component getCenterPanel() {
0184: pnlCenter = new JPanel(new GridLayout(1, 1));
0185: return pnlCenter;
0186: }
0187:
0188: /**
0189: * Resetea el panel principal con una cierta definicion
0190: * @param definition
0191: */
0192: protected void updateUIFrom(XmlEditorTreeDefinition definition) {
0193: try {
0194: pnlCenter.removeAll();
0195: pnlXmlEditor = new XmlEditorPanel(definition
0196: .getRootDefinition());
0197: pnlCenter.add(pnlXmlEditor);
0198: pnlCenter.validate();
0199: } catch (XmlEditorException e) {
0200: showException(e);
0201: }
0202: }
0203:
0204: public void actionPerformed(ActionEvent e) {
0205: if (pnlXmlEditor != null) {
0206: if (e.getSource() == btAddNode) {
0207: if (currentXsdFile == null) {
0208: JOptionPane.showMessageDialog(this ,
0209: LanguageTraslator.traslate("507"));
0210: } else {
0211: pnlXmlEditor.addNode();
0212: }
0213: } else if (e.getSource() == btDeleteNode) {
0214: pnlXmlEditor.deleteNode();
0215: } else if (e.getSource() == btFinish) {
0216: int result = JOptionPane.showConfirmDialog(this ,
0217: LanguageTraslator.traslate("508"),
0218: LanguageTraslator.traslate("509"),
0219: JOptionPane.YES_NO_OPTION,
0220: JOptionPane.QUESTION_MESSAGE);
0221: if (result == JOptionPane.YES_OPTION) {
0222: save(true);
0223: }
0224: System.exit(0);
0225: }
0226: } else {
0227: if (e.getSource() == btFinish) {
0228: System.exit(0);
0229: } else {
0230: showException(new XmlEditorException(LanguageTraslator
0231: .traslate("510")));
0232: }
0233: }
0234: }
0235:
0236: public File getCurrentXmlFile() {
0237: return currentXmlFile;
0238: }
0239:
0240: public void setCurrentXmlFile(File currentXmlFile) {
0241: this .currentXmlFile = currentXmlFile;
0242: }
0243:
0244: /**
0245: * Abre un Xml o Xsd que estaba en la lista de los utilizados recientemente
0246: * @param name: nombre del archivo a abrir
0247: */
0248: protected void openRecent(String name) {
0249: try {
0250: File file = new File(name);
0251: if (name.substring(name.lastIndexOf(".") + 1)
0252: .equalsIgnoreCase("xsd")) {
0253: loadTreeFromFile(name);
0254: setCurrentXsdFile(file);
0255: } else {
0256: if (currentXmlFile != null) {
0257: int result = JOptionPane.showConfirmDialog(this ,
0258: LanguageTraslator.traslate("508"),
0259: LanguageTraslator.traslate("509"),
0260: JOptionPane.YES_NO_OPTION,
0261: JOptionPane.QUESTION_MESSAGE);
0262: if (result == JOptionPane.YES_OPTION) {
0263: save(true);
0264: }
0265: }
0266: if (file.getName().startsWith(
0267: XmlEditorDefaultReports.defaultDefinitionTag)) {
0268: loadXmlFromSchema(reportDefinitionXsdPath, file);
0269: } else if (file.getName().startsWith(
0270: XmlEditorDefaultReports.defaultSourceTag)) {
0271: loadXmlFromSchema(reportSourceDefinitionXsdPath,
0272: file);
0273: } else {
0274: loadXml(file);
0275: }
0276: setCurrentXmlFile(file);
0277: }
0278: setTitle();
0279: } catch (XmlEditorException e) {
0280: showException(e);
0281: }
0282: }
0283:
0284: /**
0285: * Hace un ERROR_MESSAGE con la exception, para mostrar en pantalla con un cuadro generico
0286: * @param e
0287: */
0288: public void showException(XmlEditorException e) {
0289: //e.printStackTrace();
0290: ShowExceptionMessageDialog.initExceptionDialogMessage(
0291: LanguageTraslator.traslate("511"), e);
0292: }
0293:
0294: /**
0295: * Busca un nodo particular del arbol, con el atributo UserObject (valor) correspondiente al parametro nodeName
0296: * @param children: enumeracion de children de un nodo
0297: * @param nodeName: nombre a buscar
0298: * @param found
0299: * @return
0300: */
0301: private XmlEditorTreeModelNode getModelNodeFrom(
0302: Enumeration children, String nodeName, boolean found) {
0303: XmlEditorTreeModelNode returnVal = null;
0304: while (children.hasMoreElements() && !found) {
0305: XmlEditorTreeModelNode current = (XmlEditorTreeModelNode) children
0306: .nextElement();
0307: if (current.getUserObject().equals(nodeName)) {
0308: return current;
0309: } else {
0310: returnVal = getModelNodeFrom(current.children(),
0311: nodeName, found);
0312: if (returnVal != null) {
0313: found = true;
0314: }
0315: }
0316: }
0317: return returnVal;
0318: }
0319:
0320: //Todo: metodo repetido en XmlEditorLoader. Reparar el error arquitectonico.
0321: /**
0322: * Genera un report layout a partir de un Report Definition cargado actualmente en el modelo
0323: */
0324: protected void generateReportLayout() {
0325: XmlEditorTreeModelNode node = (XmlEditorTreeModelNode) pnlXmlEditor
0326: .getTreeModel().getRoot();
0327: String reportType = node.getUserObject().toString();
0328: if (reportType.equalsIgnoreCase("ReportDefinition")
0329: || reportType.equalsIgnoreCase("ReportView")) {
0330: XmlEditorTreeModelNode current = getModelNodeFrom(node
0331: .children(), reportType, false);
0332: if (current == null) {
0333: current = (XmlEditorTreeModelNode) node.children()
0334: .nextElement();
0335: }
0336: int result = JOptionPane.showConfirmDialog(this ,
0337: LanguageTraslator.traslate("512"),
0338: LanguageTraslator.traslate("513"),
0339: JOptionPane.YES_NO_OPTION,
0340: JOptionPane.WARNING_MESSAGE);
0341: if (result == JOptionPane.YES_OPTION) {
0342: try {
0343: Map attrs = getXmlLayoutProperties(current,
0344: reportType);
0345: String layoutName = XmlEditorDefaultReports
0346: .getLayoutId((String) attrs.get("ReportId"));
0347: if (((Integer) attrs.get("LayoutPos")).intValue() > 0) {
0348: current.getAttributes().set(
0349: ((Integer) attrs.get("LayoutPos"))
0350: .intValue(), layoutName);
0351: } else {
0352: showException(new XmlEditorException(
0353: LanguageTraslator.traslate("514")));
0354: }
0355: XmlEditorXmlGenerator.generateFrom(pnlXmlEditor
0356: .getTreeModel(), getCurrentXmlFile()
0357: .getAbsolutePath());
0358: getReportManager().registerDefinitions();
0359: ReportResult reportResult = getReportResultFromCurrent(
0360: reportType, attrs.get("ReportDefinitionId")
0361: .toString(), getCurrentXmlFile()
0362: .getAbsolutePath());
0363: writeReportLayout(reportResult, attrs.get(
0364: "ReportId").toString(), attrs.get(
0365: "ReportDefinitionId").toString());
0366: JOptionPane.showMessageDialog(this ,
0367: LanguageTraslator.traslate("515"));
0368: } catch (Exception e) {
0369: showException(new XmlEditorException(
0370: LanguageTraslator.traslate("516"), e));
0371: }
0372: }
0373: } else {
0374: showException(new XmlEditorException(LanguageTraslator
0375: .traslate("517")));
0376: }
0377: }
0378:
0379: private ReportResult getReportResultFromCurrent(String reportType,
0380: String reportDefinitionId, String viewFileName)
0381: throws XmlEditorException {
0382: ReportResult result = null;
0383: try {
0384: ReportDefinition definition = getReportManager()
0385: .getReportDefinitionFromID(reportDefinitionId);
0386: if (reportType.equalsIgnoreCase("ReportDefinition")) {
0387: if (definition.getReportType() != ReportDefinitionReportTypeType.STATICSQL) {
0388: result = getReportManager().ExecReportQuery(
0389: reportDefinitionId, new HashMap());
0390: }
0391: } else {
0392: if (definition.getReportType() != ReportDefinitionReportTypeType.STATICSQL) {
0393: int reportHandle = getReportManager()
0394: .PrepareReport(reportDefinitionId);
0395: ReportView view = ReportView
0396: .unmarshal(new FileReader(viewFileName));
0397: result = getReportManager().ExecReportQuery(
0398: reportHandle, view);
0399: }
0400: }
0401: } catch (Exception e) {
0402: throw new XmlEditorException(e);
0403: }
0404: return result;
0405: }
0406:
0407: private Map getXmlLayoutProperties(XmlEditorTreeModelNode current,
0408: String reportType) throws XmlEditorException {
0409: Map result = new HashMap();
0410: int titlePos = -1;
0411: int layoutPos = -1;
0412: if (reportType.equalsIgnoreCase("ReportDefinition")) {
0413: layoutPos = current.getAttributeNames().indexOf(
0414: "LayoutDesign");
0415: result.put("LayoutPos", new Integer(layoutPos));
0416: titlePos = current.getAttributeNames().indexOf("Title");
0417: String reportId = current.getId();
0418: result.put("ReportId", reportId);
0419: result.put("ReportDefinitionId", reportId);
0420: } else if (reportType.equalsIgnoreCase("ReportView")) {
0421: layoutPos = current.getAttributeNames().indexOf(
0422: "ReportLayout");
0423: result.put("LayoutPos", new Integer(layoutPos));
0424: titlePos = current.getAttributeNames().indexOf(
0425: "Description");
0426: result.put("ReportId", current.getId());
0427: int reportDefinitionIdPos = current.getAttributeNames()
0428: .indexOf("ReportDefinitionId");
0429: result.put("ReportDefinitionId", current.getAttributes()
0430: .elementAt(reportDefinitionIdPos));
0431: }
0432: try {
0433: result.put("LayoutName", current.getAttributes().elementAt(
0434: layoutPos));
0435: } catch (Exception e) {
0436: throw new XmlEditorException(LanguageTraslator
0437: .traslate("514"));
0438: }
0439: result
0440: .put("Title", current.getAttributes().elementAt(
0441: titlePos));
0442: return result;
0443: }
0444:
0445: /**
0446: * Muestra el connectionPane donde deberan setearse los valores para armar el reporte generico desde SQL.
0447: * Este retornara el control via "createReportDefinitionsFromSql()" y ya tendra los datos necesarios para establecer la
0448: * conexion y generar los reportes.
0449: */
0450: public void getParametersFromPane() {
0451: XmlEditorConnectionPane connectionPane = getConnectionPane();
0452: connectionPane.pack();
0453: connectionPane.setVisible(true);
0454: if (!connectionPane.isCancelled()) {
0455: createReportDefinitionsFromSql(connectionPane
0456: .getReportName(), connectionPane.getClassName(),
0457: connectionPane.getLocalUrl(), connectionPane
0458: .getUser(), String.valueOf(connectionPane
0459: .getPassword()), connectionPane
0460: .getSqlText());
0461: }
0462: }
0463:
0464: private XmlEditorConnectionPane getConnectionPane() {
0465: if (connectionPane == null) {
0466: connectionPane = new XmlEditorConnectionPane(this , true,
0467: reportGeneratorConfiguration.getValues());
0468: }
0469: return connectionPane;
0470: }
0471:
0472: /**
0473: * Carga el arbol de un schema dado y actualiza los paneles
0474: * @param schema: path del esquema a cargar
0475: * @throws XmlEditorException
0476: */
0477: private void loadTreeFromFile(String schema)
0478: throws XmlEditorException {
0479: XmlEditorTreeDefinition definition = new XmlEditorTreeDefinition(
0480: schema);
0481: updateUIFrom(definition);
0482: }
0483:
0484: /**
0485: * Carga un Xsd al modelo (vacio)
0486: */
0487: protected void loadFromXsd() {
0488: try {
0489: JFileChooser fileChooser = getFileChooser("xsd", "Schema");
0490: int result = fileChooser.showOpenDialog(this );
0491: if (result == JFileChooser.APPROVE_OPTION) {
0492: String schemaLocation = fileChooser.getSelectedFile()
0493: .getPath();
0494: menuBar.addXsdRecentItem(schemaLocation);
0495: loadTreeFromFile(schemaLocation);
0496: pnlXmlEditor.setOnlyXsd(true);
0497: setCurrentXsdFile(fileChooser.getSelectedFile());
0498: setTitle();
0499: }
0500: } catch (XmlEditorException e) {
0501: showException(e);
0502: }
0503: }
0504:
0505: /**
0506: * Obtiene un JFileChooser, especificandole un tipo de extension unico a filtrar en el dialogo
0507: * @param extension: extension unica que se mostrara (ej: ".xsd")
0508: * @param description: descripcion para esa extension (ej: "Schema")
0509: * @return
0510: */
0511: private JFileChooser getFileChooser(String extension,
0512: String description) {
0513: JFileChooser fileChooser;
0514: if (extension == "xml") {
0515: fileChooser = new JFileChooser(
0516: getReportGeneratorConfiguration()
0517: .getSourceReportDefinitionsPath());
0518: } else if (extension == "xsd") {
0519: fileChooser = new JFileChooser(
0520: getReportGeneratorConfiguration()
0521: .getSourceReportSchemasPath());
0522: } else {
0523: fileChooser = new JFileChooser(".");
0524: }
0525: fileChooser.setMultiSelectionEnabled(false);
0526: fileChooser.setFileFilter(new ExtensionFilter(extension,
0527: description));
0528: return fileChooser;
0529: }
0530:
0531: /**
0532: * Carga a los paneles un Xml si previamente existia un Xsd. Corrobora los valores contra esa
0533: * definicion
0534: * @param schemaPath
0535: * @param file
0536: * @throws XmlEditorException
0537: */
0538: private void loadXmlFromSchema(String schemaPath, File file)
0539: throws XmlEditorException {
0540: loadTreeFromFile(schemaPath);
0541: xmlLoader = new XmlEditorLoader(pnlXmlEditor.getTreeModel(),
0542: pnlXmlEditor.getNodeDefinition());
0543: DefaultTreeModel newModel = xmlLoader.loadFrom(file, true);
0544: pnlXmlEditor.getTree().setModel(newModel);
0545: pnlXmlEditor.getTree().repaint();
0546: pnlXmlEditor.setOnlyXsd(false);
0547: }
0548:
0549: /**
0550: * Carga un Xml sin xsd
0551: * @param file
0552: */
0553: private void loadXml(File file) {
0554: try {
0555: xmlLoader = new XmlEditorLoader();
0556: DefaultTreeModel newModel = xmlLoader.loadFrom(file, false);
0557: updateXmlPanelFrom(newModel, xmlLoader.getDomRoot());
0558: setCurrentXmlFile(file);
0559: } catch (XmlEditorException e) {
0560: showException(e);
0561: }
0562: }
0563:
0564: /**
0565: * Carga un Xml. Puede tener o no xsd (debera estar cargado en el modelo antes de llegar aqui).
0566: * El usuario seleccionara el archivo
0567: * @param justXml
0568: */
0569: protected void loadFromXml(boolean justXml, String fileName) {
0570: File file = null;
0571: try {
0572: if (fileName.equals("")) {
0573: JFileChooser fileChooser = getFileChooser("xml",
0574: "Xml file");
0575: int result = fileChooser.showOpenDialog(this );
0576: if (result == JFileChooser.APPROVE_OPTION) {
0577: file = fileChooser.getSelectedFile();
0578: }
0579: } else {
0580: file = new File(fileName);
0581: }
0582: if (file != null) {
0583: menuBar.addXmlRecentItem(file.getAbsolutePath());
0584: if (!justXml) {
0585: unloadCurrentXmlFromXsd();
0586: if (pnlXmlEditor == null) {
0587: throw new XmlEditorException(LanguageTraslator
0588: .traslate("518"));
0589: }
0590: xmlLoader = new XmlEditorLoader(pnlXmlEditor
0591: .getTreeModel(), pnlXmlEditor
0592: .getNodeDefinition());
0593: DefaultTreeModel newModel = xmlLoader.loadFrom(
0594: file, true);
0595: pnlXmlEditor.getTree().setModel(newModel);
0596: pnlXmlEditor.getTree().repaint();
0597: pnlXmlEditor.setOnlyXsd(false);
0598: } else {
0599: loadXml(file);
0600: setCurrentXsdFile(null);
0601: }
0602: setCurrentXmlFile(file);
0603: setTitle();
0604: }
0605: } catch (XmlEditorException e) {
0606: showException(e);
0607: }
0608: }
0609:
0610: /**
0611: * Remueve un arbol de una definicion xml, dejando el arbol del xsd que lo produjo.
0612: * Para ello, remueve toda la estructura y vuelve a cargar solo el xsd.
0613: * @throws XmlEditorException
0614: */
0615: private void unloadCurrentXmlFromXsd() throws XmlEditorException {
0616: File currentXsdFile = getCurrentXsdFile();
0617: unLoadxsd();
0618: loadTreeFromFile(currentXsdFile.getAbsolutePath());
0619: setCurrentXsdFile(currentXsdFile);
0620: }
0621:
0622: /**
0623: * Colapsa todos los nodos del arbol actual.
0624: */
0625: private void collapseAllNodes() {
0626: pnlXmlEditor.collapseAllNodes();
0627: }
0628:
0629: /**
0630: * Actualiza el panel Xml
0631: * @param newModel
0632: * @param domRoot
0633: */
0634: private void updateXmlPanelFrom(DefaultTreeModel newModel,
0635: Node domRoot) {
0636: if (pnlXmlEditor != null) {
0637: pnlXmlEditor.removeAll();
0638: }
0639: pnlCenter.removeAll();
0640: pnlXmlEditor = new XmlEditorPanel(newModel, domRoot);
0641: pnlCenter.add(pnlXmlEditor);
0642: pnlCenter.validate();
0643: }
0644:
0645: /**
0646: * Setea desde el connectionPane los parametros para establecer la conexcion SQL. Ejecuta el texto SQL ingresado, y obtiene
0647: * nombres de columnas y tipos de datos para generar los reportes. LLama a writereports, que se encarga de escribir los
0648: * reportes a disco.
0649: * @param reportName
0650: * @param className
0651: * @param localUrl
0652: * @param user
0653: * @param password
0654: * @param sql
0655:
0656: */
0657: public void createReportDefinitionsFromSql(String reportName,
0658: String className, String localUrl, String user,
0659: String password, String sql) {
0660: Map currentColumnsDimensions;
0661: Map currentColumnsMetrics;
0662: Map map2;
0663:
0664: try {
0665: connectionPane.setVisible(false);
0666: DataTypeTableFrame dataTypeTableFrame;
0667: Class.forName(className);
0668: getLogger().info(
0669: new String(LanguageTraslator.traslate("519")));
0670: System.out.print(LanguageTraslator.traslate("519"));
0671: Connection con = DriverManager.getConnection(localUrl,
0672: user, password);
0673: Statement stmt = con.createStatement();
0674: //TODO Reducir la query
0675: //cosas posibles
0676: //stmt.setMaxRows();
0677: //stmt.setFetchSize();
0678:
0679: ResultSet rs = stmt.executeQuery(sql);
0680: ResultSetMetaData meta = rs.getMetaData();
0681:
0682: getLogger().info(
0683: new String(LanguageTraslator.traslate("520")));
0684: System.out.println(LanguageTraslator.traslate("520"));
0685: currentColumnsDimensions = getColumnsDimensionsMap(meta);
0686: currentColumnsMetrics = getColumnsMetricsMap(meta);
0687: dataTypeTableFrame = new DataTypeTableFrame(this ,
0688: typeColumn);
0689: dataTypeTableFrame.setVisible(true);
0690: if (!dataTypeTableFrame.isCancelled()) {
0691: map2 = dataTypeTableFrame.getRowsLatestVersion();
0692: dataTypeTableFrame.setVisible(false);
0693: currentColumnsDimensions = getColumnsDimensionsMap(map2);
0694: currentColumnsMetrics = getColumnsMetricsMap(map2);
0695: }
0696:
0697: writeReports(reportName, currentColumnsDimensions,
0698: currentColumnsMetrics, sql, className, localUrl,
0699: user, password);
0700: File xmlFile = new File(reportGeneratorConfiguration
0701: .getSourceReportDefinitionsPath()
0702: + "/"
0703: + XmlEditorDefaultReports.getReportId(reportName)
0704: + ".xml");
0705: setCurrentXmlFile(xmlFile);
0706: loadXmlFromSchema(reportDefinitionXsdPath, xmlFile);
0707: setTitle();
0708: } catch (Exception e) {
0709: showException(new XmlEditorException(e));
0710: }
0711: }
0712:
0713: /**
0714: * Con los datos obtenidos de la query genera los archivos XML que seran la especificacion del reporte.
0715: * @param reportName
0716: * @param dimensionMap
0717: * @param metricMap
0718: * @param query
0719: * @param className
0720: * @param localUrl
0721: * @param user
0722: * @param password
0723: */
0724: private void writeReports(String reportName, Map dimensionMap,
0725: Map metricMap, String query, String className,
0726: String localUrl, String user, String password) {
0727: getLogger().info(new String(LanguageTraslator.traslate("521")));
0728: System.out.println(LanguageTraslator.traslate("521"));
0729: String reportPath = writeReportDefinition(reportName,
0730: dimensionMap, metricMap);
0731: System.out.println("reportName:" + reportName
0732: + "dimensionMap: " + dimensionMap.size() + "tostring:"
0733: + dimensionMap.toString() + "metricMap:"
0734: + metricMap.toString());
0735: menuBar.addXmlRecentItem(reportPath);
0736: getLogger().info(new String(LanguageTraslator.traslate("522")));
0737: System.out.println(LanguageTraslator.traslate("522"));
0738: reportPath = writeReportSourceDefinition(reportName,
0739: dimensionMap, metricMap, query, className, localUrl,
0740: user, password);
0741: menuBar.addXmlRecentItem(reportPath);
0742: }
0743:
0744: /**
0745: * Escribe a disco un XML con una definicion de Layout para ver el Reporte (especificado por los parametros)
0746: * @param reportName
0747: * @param definitionId
0748: * @return
0749: * @throws XmlEditorException
0750: */
0751: private String writeReportLayout(ReportResult result,
0752: String reportName, String definitionId)
0753: throws XmlEditorException {
0754: String layoutName = "";
0755: try {
0756: ReportDefinition definition = getReportManager()
0757: .getReportDefinitionFromID(definitionId);
0758: ReportSpec reportSpec = getReportManager().getReportSpec(
0759: definitionId);
0760: ReportLayoutBuilder builder = new ReportLayoutBuilder(
0761: getReportGeneratorConfiguration(), result,
0762: reportSpec);
0763: /*int reportHandle = getReportManager().PrepareReport(definitionId);
0764: ReportResult result = getReportManager().ExecReportQuery(reportHandle, reportView);*/
0765: //ReportLayoutBuilder builder = new ReportLayoutBuilder(getReportGeneratorConfiguration(), result, result.getReportSpec());
0766: //IJasperDefinition jasper = builder.getJasperDefinition();
0767: IJasperDefinition jasper = builder
0768: .buildDefaulJasperDefinition();
0769: //IJasperDefinition jasper = getJasperDefinition(result);
0770: if (reportName.equalsIgnoreCase("")) {
0771: reportName = definition.getTitle() != null ? definition
0772: .getTitle() : definitionId;
0773: }
0774: layoutName = XmlEditorDefaultReports
0775: .getLayoutId(reportName)
0776: + ".xml";
0777: new XMLWriter(jasper.getJasperDefinition(true))
0778: .saveDocument(reportGeneratorConfiguration
0779: .getSourceReportLayoutPath()
0780: + "/" + layoutName);
0781: } catch (Exception e) {
0782: throw new XmlEditorException(e);
0783: }
0784: return layoutName;
0785: }
0786:
0787: private IJasperDefinition getJasperDefinition(ReportResult result)
0788: throws XmlEditorException, InfoException {
0789: IJasperDefinition jasperDefinition = null;
0790: int groupingDimensionCount = result.getReportTableModel()
0791: .getGroupingDimCount();
0792: int nonGroupingDimensionCount = result.getReportTableModel()
0793: .getNonGroupingDimCount();
0794: int accumMetricCount = result.getReportTableModel()
0795: .getAccMetricsCount();
0796: int metricCount = result.getReportTableModel()
0797: .getCommonMetricsCount();
0798: if (result.getReportSpec().getReportType().getType() == ReportDefinitionReportTypeType.CUBE_TYPE) {
0799: jasperDefinition = new CubeJasperReportDefinition(result,
0800: result.getReportTableModel().getModel(),
0801: groupingDimensionCount, metricCount,
0802: nonGroupingDimensionCount, accumMetricCount, result
0803: .getReportSpec().getTitle());
0804: } else if (result.getReportSpec().getReportType().getType() == ReportDefinitionReportTypeType.ACCUM_TYPE) {
0805: jasperDefinition = new StaticJasperReportDefinition(result,
0806: result.getReportTableModel().getModel(),
0807: groupingDimensionCount, metricCount,
0808: nonGroupingDimensionCount, accumMetricCount, result
0809: .getReportSpec().getTitle());
0810: } else if (result.getReportSpec().getReportType().getType() == ReportDefinitionReportTypeType.STATICSQL_TYPE) {
0811: throw new XmlEditorException(LanguageTraslator
0812: .traslate("523"));
0813: /*com.calipso.reportgenerator.common.ReportTableModel model = new StaticReportTableModel(result.getReportSpec(), result.getReportQuery());
0814: jasperDefinition = new StaticSQLJasperReportDefinition(result.getReportSpec(), model.getModel(), model.getGroupingDimCount(), model.getCommonMetricsCount(),
0815: model.getNonGroupingDimCount(), model.getAccMetricsCount(), result.getReportSpec().getTitle());*/
0816: }
0817: jasperDefinition = addStyle(jasperDefinition);
0818: return jasperDefinition;
0819: }
0820:
0821: private IJasperDefinition addStyle(IJasperDefinition design) {
0822: String style = reportGeneratorConfiguration
0823: .getReportLayoutStyle();
0824: if (style == null || style.equalsIgnoreCase("")) {
0825: return design;
0826: } else if (style.equalsIgnoreCase("Calipso")) {
0827: return new CalipsoDecoratedReportLayout(design);
0828: }
0829: return design;
0830: }
0831:
0832: public IReportManager getReportManager() {
0833: if (reportManager == null) {
0834: try {
0835: reportManager = ReportManagerService
0836: .getReportManagerService("", null, "");
0837: } catch (Exception e) {
0838: showException(new XmlEditorException(e));
0839: System.exit(3);
0840: }
0841: }
0842: return reportManager;
0843: }
0844:
0845: /**
0846: * Genera en base a los datos obtenidos una ReportSourceDefinition estandar.
0847: * @param reportName
0848: * @param dimensionMap
0849: * @param metricMap
0850: * @param query
0851: * @param className
0852: * @param localUrl
0853: * @param user
0854: * @param password
0855: * @return
0856: */
0857: private String writeReportSourceDefinition(String reportName,
0858: Map dimensionMap, Map metricMap, String query,
0859: String className, String localUrl, String user,
0860: String password) {
0861: ReportSourceDefinition report = XmlEditorDefaultReports
0862: .getReportSourceDefinition(reportName, dimensionMap,
0863: metricMap, query, className, localUrl, user,
0864: password);
0865: String fullPath = reportGeneratorConfiguration
0866: .getSourceReportSourceDefinitionsPath()
0867: + "/"
0868: + XmlEditorDefaultReports.getSourceId(reportName)
0869: + ".xml";
0870: try {
0871: getLogger().info(
0872: new String(LanguageTraslator.traslate("524")));
0873: System.out.println(LanguageTraslator.traslate("524"));
0874: Writer wr = new FileWriter(fullPath);
0875: report.marshal(wr);
0876: wr.flush();
0877: wr.close();
0878: } catch (Exception e) {
0879: showException(new XmlEditorException(e));
0880: // e.printStackTrace();
0881: }
0882: return fullPath;
0883: }
0884:
0885: /**
0886: * Genera en base a los datos obtenidos una ReportDefinition estandar.
0887: * @param reportName
0888: * @param dimensionMap
0889: * @param metricMap
0890: * @return
0891: */
0892: private String writeReportDefinition(String reportName,
0893: Map dimensionMap, Map metricMap) {
0894: ReportDefinition report = XmlEditorDefaultReports
0895: .getReportDefinition(reportGeneratorConfiguration,
0896: reportName, dimensionMap, metricMap);
0897: System.out.println("report.toString():" + report.toString());
0898: System.out.println("report.toString():"
0899: + report.getDimensionDefinitions()
0900: .getDimensionDefinition().length
0901: + ":"
0902: + report.getDimensionDefinitions()
0903: .enumerateDimensionDefinition().toString());
0904: String fullPath = reportGeneratorConfiguration
0905: .getSourceReportDefinitionsPath()
0906: + "/"
0907: + XmlEditorDefaultReports.getReportId(reportName)
0908: + ".xml";
0909: try {
0910: getLogger().info(
0911: new String(LanguageTraslator.traslate("525")));
0912: System.out.println(LanguageTraslator.traslate("525"));
0913: Writer wr = new FileWriter(fullPath);
0914: report.marshal(wr);
0915: wr.flush();
0916: wr.close();
0917: } catch (Exception e) {
0918: e.printStackTrace();
0919: showException(new XmlEditorException(e));
0920: }
0921: return fullPath;
0922: }
0923:
0924: /**
0925: * Guarda el arbol visualizado actualmente a disco. El usuario selecciona el archivo destino.
0926: */
0927: public void save(boolean overrideFile) {
0928: try {
0929: pnlXmlEditor.valueChanged();
0930: if (pnlXmlEditor != null) {
0931: if ((getCurrentXmlFile() == null)
0932: || ((!overrideFile) && (getCurrentXmlFile() != null))) {
0933: JFileChooser fileChooser = getFileChooser("xml",
0934: "Xml file");
0935: int result = fileChooser.showSaveDialog(this );
0936: if (result == JFileChooser.APPROVE_OPTION) {
0937: File file = fileChooser.getSelectedFile();
0938: XmlEditorXmlGenerator
0939: .generateFrom(pnlXmlEditor
0940: .getTreeModel(), file
0941: .getAbsolutePath());
0942: menuBar
0943: .addXmlRecentItem(file
0944: .getAbsolutePath());
0945: }
0946: } else {
0947: XmlEditorXmlGenerator.generateFrom(pnlXmlEditor
0948: .getTreeModel(), currentXmlFile
0949: .getAbsolutePath());
0950: menuBar.addXmlRecentItem(currentXmlFile
0951: .getAbsolutePath());
0952: }
0953: }
0954: } catch (XmlEditorException e) {
0955: showException(e);
0956: }
0957: }
0958:
0959: class Win extends WindowAdapter {
0960: public void windowClosing(WindowEvent event) {
0961: System.exit(0);
0962: }
0963: }
0964:
0965: public void setTitle() {
0966:
0967: String title = "Calipso XML Editor";
0968: if (currentXsdFile != null) {
0969: title = title + " - XSD : " + currentXsdFile.getName();
0970: }
0971: if (currentXmlFile != null) {
0972: title = title + " - XML : " + currentXmlFile.getName();
0973: }
0974: setTitle(title);
0975: }
0976:
0977: public ReportGeneratorConfiguration getReportGeneratorConfiguration() {
0978: return reportGeneratorConfiguration;
0979: }
0980:
0981: public void unLoadxsd() {
0982: pnlCenter.removeAll();
0983: pnlXmlEditor.removeAll();
0984: repaint();
0985: setCurrentXsdFile(null);
0986: setTitle();
0987: }
0988:
0989: public static Logger getLogger() {
0990: if (logger == null) {
0991: PatternLayout patternLayout = new PatternLayout();
0992: try {
0993: ConsoleAppender consoleAppender = new ConsoleAppender();
0994: FileAppender fileAppender = new FileAppender(
0995: patternLayout, "xmleditorlog.txt", true);
0996: logger = Logger.getLogger("testlogxmleditor");
0997: logger.addAppender(consoleAppender);
0998: } catch (IOException e) {
0999: e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
1000: }
1001: }
1002: return logger;
1003: }
1004:
1005: public void generateReportView() {
1006: XmlEditorTreeModelNode node = (XmlEditorTreeModelNode) pnlXmlEditor
1007: .getTreeModel().getRoot();
1008: String reportType = node.getUserObject().toString();
1009: if (!reportType.equalsIgnoreCase("ReportDefinition")) {
1010: showException(new XmlEditorException(LanguageTraslator
1011: .traslate("527")));
1012: }
1013: XmlEditorTreeModelNode dimensionsGroup = this .getModelNodeFrom(
1014: node.children(), "DimensionDefinitions", false);
1015: XmlEditorTreeModelNode dimensions = this .getModelNodeFrom(
1016: dimensionsGroup.children(), "DimensionDefinition",
1017: false);
1018: XmlEditorTreeModelNode metricsGroup = this .getModelNodeFrom(
1019: node.children(), "MetricDefinitions", false);
1020: XmlEditorTreeModelNode metrics = this .getModelNodeFrom(
1021: metricsGroup.children(), "MetricDefinition", false);
1022: String reportDefinitionId = "";
1023: XmlEditorTreeModelNode mainNode = this .getModelNodeFrom(node
1024: .children(), "ReportDefinition", false);
1025: if (mainNode != null) {
1026: reportDefinitionId = mainNode.getId();
1027: } else {
1028: reportDefinitionId = getReportDefintionId(node);
1029: }
1030: String reportPath = writeReportView(dimensions, metrics,
1031: reportDefinitionId);
1032: menuBar.addXmlRecentItem(reportPath);
1033: File xmlFile = new File(reportPath);
1034: setCurrentXmlFile(xmlFile);
1035: try {
1036: loadXmlFromSchema(reportViewXsdPath, xmlFile);
1037: } catch (XmlEditorException e) {
1038: showException(e);
1039: }
1040: setTitle();
1041: }
1042:
1043: private String writeReportView(XmlEditorTreeModelNode dimensions,
1044: XmlEditorTreeModelNode metrics, String reportDefinitionId) {
1045: ReportView reportView = XmlEditorDefaultReports.getReportView(
1046: dimensions, metrics, reportDefinitionId);
1047: //System.out.println("reportView.toString():"+reportView.toString());
1048: String fullPath = reportGeneratorConfiguration
1049: .getSourceReportViewsPath()
1050: + "/" + reportView.getId() + ".xml";
1051: try {
1052: getLogger().info(
1053: new String(LanguageTraslator.traslate("528")));
1054: System.out.println(LanguageTraslator.traslate("528"));
1055: Writer wr = new FileWriter(fullPath);
1056: reportView.marshal(wr);
1057: wr.flush();
1058: wr.close();
1059: } catch (Exception e) {
1060: e.printStackTrace();
1061: showException(new XmlEditorException(e));
1062: }
1063: return fullPath;
1064: }
1065:
1066: private String getReportDefintionId(XmlEditorTreeModelNode node) {
1067: Collection reportDefinitionElementNames = Arrays
1068: .asList(new String[] { "ActionDefinitions",
1069: "DimensionDefinitions", "DrillDownDefinitions",
1070: "MetricDefinitions", "FilterDefinitions",
1071: "ParameterValues", "ReportDefinition",
1072: "Localizations", "Roles" });
1073: Enumeration enumeration = node.children();
1074: while (enumeration.hasMoreElements()) {
1075: XmlEditorTreeModelNode child = (XmlEditorTreeModelNode) enumeration
1076: .nextElement();
1077: if (!reportDefinitionElementNames.contains(child
1078: .getUserObject().toString())) {
1079: return child.getId();
1080: }
1081: }
1082: return "";
1083: }
1084:
1085: private Map getColumnsDimensionsMap(ResultSetMetaData meta) {
1086: Map result = new HashMap();
1087: int cantidad = 0;
1088:
1089: try {
1090: cantidad = meta.getColumnCount();
1091: for (int i = 0; i < cantidad; i++) {
1092: if (!(isMetric(meta.getColumnType(i + 1)))) {
1093: System.out.println(LanguageTraslator
1094: .traslate("280")
1095: + meta.getColumnName(i + 1));
1096: result.put(meta.getColumnName(i + 1), new Integer(
1097: meta.getColumnType(i + 1)));
1098: Vector data = new Vector(3);
1099: data.add(meta.getColumnName(i + 1));
1100: data.add("Dimension");
1101: data.add(new Integer(meta.getColumnType(i + 1)));
1102: ; // ver si es necesario q devuelva int ...
1103: typeColumn.put(new Integer(i + 1), data);
1104: }
1105: }
1106: } catch (Exception e) {
1107: showException(new XmlEditorException(e));
1108: }
1109: return result;
1110: }
1111:
1112: private Map getColumnsMetricsMap(ResultSetMetaData meta) {
1113: Map result = new HashMap();
1114: int cantidad = 0;
1115: try {
1116: cantidad = meta.getColumnCount();
1117: for (int i = 0; i < cantidad; i++) {
1118: if (isMetric(meta.getColumnType(i + 1))) {
1119: System.out.println(LanguageTraslator
1120: .traslate("529")
1121: + meta.getColumnName(i + 1));
1122: result.put(meta.getColumnName(i + 1), new Integer(
1123: meta.getColumnType(i + 1)));
1124: Vector data = new Vector(3);
1125: data.add(meta.getColumnName(i + 1));
1126: data.add("Metric");
1127: data.add(new Integer(meta.getColumnType(i + 1))); // ver si es necesario q devuelva int ...
1128: typeColumn.put(new Integer(i + 1), data);
1129: }
1130: }
1131: } catch (Exception e) {
1132: showException(new XmlEditorException(e));
1133: }
1134: return result;
1135: }
1136:
1137: /**
1138: * Verifica que el tipo de dato de la columna sea acumulable(metrica)
1139: * @param typeColumn
1140: * @return
1141: */
1142:
1143: private boolean isMetric(int typeColumn) {
1144:
1145: switch (typeColumn) {
1146: case Types.TINYINT:
1147: case Types.SMALLINT:
1148: case Types.INTEGER:
1149: case Types.BIGINT:
1150: case Types.FLOAT:
1151: case Types.DOUBLE:
1152: case Types.REAL:
1153: case Types.DECIMAL:
1154: case Types.NUMERIC:
1155: return true;
1156: default:
1157: return false;
1158: }
1159: }
1160:
1161: private Map getColumnsDimensionsMap(Map map) {
1162: Map mapAux = new HashMap();
1163: for (int i = 0; i < (this .typeColumn.keySet().size()); i++) {
1164: Vector vector = (Vector) map.get(new Integer(1 + i));
1165: if (vector != null) {
1166: String columnName;
1167: Vector vec = new Vector(2);
1168: Integer columnType;
1169: String extData;
1170: if (vector.get(1).equals("Dimension")) {
1171: columnName = (String) vector.get(0);
1172: columnType = getIdType((String) vector.get(2));
1173: extData = (String) vector.get(3);
1174: vec.add(columnType);
1175: vec.add(extData);
1176: mapAux.put(columnName, vec);
1177: }
1178: }
1179: }
1180: return mapAux;
1181: }
1182:
1183: private Integer getIdType(String s) {
1184: if (s.equalsIgnoreCase("DECIMAL")) {
1185: return new Integer(3);
1186: }
1187: if (s.equalsIgnoreCase("INTEGER")) {
1188: return new Integer(4);
1189: }
1190: if (s.equalsIgnoreCase("FLOAT")) {
1191: return new Integer(6);
1192: }
1193: if (s.equalsIgnoreCase("BOOLEAN")) {
1194: return new Integer(16);
1195: }
1196: if (s.equalsIgnoreCase("DATETIME")) {
1197: return new Integer(91);
1198: } else {
1199: return new Integer(12);
1200: }
1201: }
1202:
1203: private Map getColumnsMetricsMap(Map map) {
1204: Map mapAux = new HashMap();
1205: for (int i = 0; i < (this .typeColumn.keySet().size()); i++) {
1206: Vector vector = (Vector) map.get(new Integer(1 + i));
1207: if (vector != null) {
1208: String columnName;
1209: Vector vec = new Vector(2);
1210: Integer columnType;
1211: String extData;
1212: if (vector.get(1).equals("Metric")) {
1213: columnName = (String) vector.get(0);
1214: columnType = getIdType((String) vector.get(2));
1215: extData = (String) vector.get(3);
1216: vec.add(columnType);
1217: vec.add(extData);
1218: mapAux.put(columnName, vec);
1219: }
1220: }
1221: }
1222: return mapAux;
1223: }
1224: }
|