List of usage examples for javax.swing.table TableModel getColumnCount
public int getColumnCount();
From source file:pt.webdetails.cda.exporter.HtmlExporter.java
@Override public void export(OutputStream out, TableModel tableModel) throws ExporterException { final Document document = DocumentHelper.createDocument(); Element table = null;//from w w w . j a v a 2 s .co m if (fullHtml) { final Element html = document.addElement("html"); final Element head = html.addElement("head"); head.addElement("title").addText(title); table = html.addElement("body").addElement("table"); } else { table = document.addElement("table"); } final int columnCount = tableModel.getColumnCount(); //table headers final Element headerRow = table.addElement("tr"); for (int i = 0; i < columnCount; i++) { String colName = tableModel.getColumnName(i); headerRow.addElement("th").addText(colName); } //table body for (int i = 0; i < tableModel.getRowCount(); i++) { Element row = table.addElement("tr"); for (int j = 0; j < columnCount; j++) { Element tableCell = row.addElement("td"); Object value = tableModel.getValueAt(i, j); tableCell.setText(valueToText(value)); if (value instanceof Date) { tableCell.setText(format.format(value)); } else if (value != null) { // numbers can be safely converted via toString, as they use a well-defined format there tableCell.setText(value.toString()); } } } try { document.setXMLEncoding("UTF-8"); OutputFormat outFormat = new OutputFormat(); outFormat.setOmitEncoding(true); outFormat.setSuppressDeclaration(true);//otherwise msexcel/oocalc may not recognize content outFormat.setNewlines(true); outFormat.setIndentSize(columnCount); final Writer writer = new BufferedWriter(new OutputStreamWriter(out)); XMLWriter xmlWriter = new XMLWriter(writer, outFormat); xmlWriter.write(document); xmlWriter.flush(); } catch (IOException e) { throw new ExporterException("IO Exception converting to utf-8", e); } }
From source file:pt.webdetails.cda.exporter.JsonExporter.java
public JSONObject getTableAsJson(TableModel tableModel, Integer rowLimit) throws JSONException, ExporterException { JSONObject json = new JSONObject(); // Generate metadata final JSONArray metadataArray = new JSONArray(); final int columnCount = tableModel.getColumnCount(); int rowCount = tableModel.getRowCount(); if (rowLimit != null) { rowCount = Math.min(rowCount, rowLimit); }// w w w . j ava2 s.com boolean[] isColumnDouble = new boolean[columnCount]; for (int i = 0; i < columnCount; i++) { JSONObject info = new JSONObject(); info.put("colIndex", i); info.put("colName", tableModel.getColumnName(i)); Class<?> columnClass = tableModel.getColumnClass(i); isColumnDouble[i] = (columnClass.isAssignableFrom(Double.class)); info.put("colType", getColType(columnClass)); metadataArray.put(info); } json.put("metadata", metadataArray); if (tableModel instanceof MetadataTableModel) { json.put("queryInfo", ((MetadataTableModel) tableModel).getAllMetadata()); } final JSONArray valuesArray = new JSONArray(); for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { final JSONArray rowArray = new JSONArray(); for (int colIdx = 0; colIdx < columnCount; colIdx++) { Object value = tableModel.getValueAt(rowIdx, colIdx); try { if (value != null && isColumnDouble[colIdx] && ((Double) value).isInfinite()) { value = null; //value = Double.POSITIVE_INFINITY == (Double) value ? "Infinity" : "-Infinity";//workaround for JSON // issue with Infinity } } catch (ClassCastException e) { } //just because it says Double doesn't mean we don't get oranges rowArray.put(value); } valuesArray.put(rowArray); } json.put("resultset", valuesArray); return json; }
From source file:pt.webdetails.cda.exporter.XmlExporter.java
public void export(final OutputStream out, final TableModel tableModel) throws ExporterException { final Document document = DocumentHelper.createDocument(); // Generate metadata final Element root = document.addElement("CdaExport"); final Element metadata = root.addElement("MetaData"); final int columnCount = tableModel.getColumnCount(); final int rowCount = tableModel.getRowCount(); for (int i = 0; i < columnCount; i++) { final Element columnInfo = metadata.addElement("ColumnMetaData"); columnInfo.addAttribute("index", (String.valueOf(i))); columnInfo.addAttribute("type", getColType(tableModel.getColumnClass(i))); columnInfo.addAttribute("name", tableModel.getColumnName(i)); }/*from w w w. ja v a2 s . c om*/ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US); final Element resultSet = root.addElement("ResultSet"); for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { final Element row = resultSet.addElement("Row"); for (int colIdx = 0; colIdx < columnCount; colIdx++) { final Element col = row.addElement("Col"); final Object value = tableModel.getValueAt(rowIdx, colIdx); if (value instanceof Date) { col.setText(format.format(value)); } else if (value != null) { // numbers can be safely converted via toString, as they use a well-defined format there col.setText(value.toString()); } else { col.addAttribute("isNull", "true"); } } } try { final Writer writer = new BufferedWriter(new OutputStreamWriter(out)); document.setXMLEncoding("UTF-8"); document.write(writer); writer.flush(); } catch (IOException e) { throw new ExporterException("IO Exception converting to utf-8", e); } }
From source file:pt.webdetails.cda.filetests.CacheKeysTest.java
@Test public void testParam() throws Exception { final CdaSettings cdaSettings = parseSettingsFile("sample-securityParam.cda"); QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId("junitDataAccess"); TableModel tableModel = cdaSettings.getDataAccess(queryOptions.getDataAccessId()).doQuery(queryOptions); assertEquals(1, tableModel.getRowCount()); assertEquals(1, tableModel.getColumnCount()); String result = (String) tableModel.getValueAt(0, 0); assertEquals("thisIsAGoodValue", result); }
From source file:pt.webdetails.cda.filetests.MdxJdbcTest.java
public void testMondrianCompactQueries() throws Exception { final CdaSettings cdaSettings = parseSettingsFile("sample-mondrian-compact.cda"); QueryOptions queryOptions = new QueryOptions(); queryOptions.setOutputType("json"); queryOptions.addParameter("status", "Shipped"); // 1//from w w w . j a v a 2 s . c om queryOptions.setDataAccessId("1"); TableModel result = doQuery(cdaSettings, queryOptions); TypedTableModel expected1 = new TypedTableModel(new String[] { "Time", "Sales", "Quantity" }, new Class<?>[] { String.class, Double.class, Double.class }); expected1.addRow("2003", 3573701.2500000023d, 35313.0); expected1.addRow("QTR1", 445094.69d, 4561.0); expected1.addRow("QTR2", 564842.02d, 5695.0); expected1.addRow("QTR3", 687268.8699999998d, 6629.0); expected1.addRow("QTR4", 1876495.6699999985d, 18428.0); expected1.addRow("2004", 4750205.889999998d, 47151.0); expected1.addRow("QTR1", 877418.9699999997d, 8694.0); expected1.addRow("QTR2", 660518.8399999997d, 6647.0); expected1.addRow("QTR3", 1145308.08d, 11311.0); expected1.addRow("QTR4", 2066959.999999998d, 20499.0); expected1.addRow("2005", 1513074.4600000002d, 14607.0); expected1.addRow("QTR1", 1013171.0199999999d, 9876.0); expected1.addRow("QTR2", 499903.43999999977d, 4731.0); TableModelChecker checker = new TableModelChecker(true, true); checker.setDoubleComparison(1, 1e-8); checker.setDoubleComparison(2, 1e-8); checker.assertEquals(expected1, result); // 2 queryOptions.setDataAccessId("2"); result = doQuery(cdaSettings, queryOptions); for (int i = 1; i < result.getColumnCount(); i++) { checker.setDoubleComparison(i, 1e-8); } Class<?>[] classes2 = new Class[14]; Arrays.fill(classes2, Double.class); classes2[0] = String.class; String[] names2 = new String[14]; names2[0] = "Measures"; for (int i = 0; i < expected1.getRowCount(); i++) { names2[i + 1] = (String) expected1.getValueAt(i, 0); } // flip expected1 TypedTableModel expected2 = new TypedTableModel(names2, classes2); Object[] row1 = new Object[14]; row1[0] = "Sales"; for (int i = 0; i < expected1.getRowCount(); i++) { row1[i + 1] = expected1.getValueAt(i, 1); } expected2.addRow(row1); Object[] row2 = new Object[14]; row2[0] = "Quantity"; for (int i = 0; i < expected1.getRowCount(); i++) { row2[i + 1] = expected1.getValueAt(i, 2); } expected2.addRow(row2); checker.assertEquals(expected2, result); // 3... TypedTableModel expected3 = new TypedTableModel(new String[] { "Product", "Time", "Sales", "Quantity" }, new Class<?>[] { String.class, String.class, Double.class, Double.class }); for (int i = 0; i < expected1.getRowCount(); i++) { Object[] row = new Object[4]; row[0] = "All Products"; for (int j = 0; j < expected1.getColumnCount(); j++) { row[j + 1] = expected1.getValueAt(i, j); } expected3.addRow(row); } checker.setDefaultComparison(1); queryOptions.setDataAccessId("3"); result = doQuery(cdaSettings, queryOptions); checker.assertEquals(expected3, result); // 4! queryOptions.setDataAccessId("4"); result = doQuery(cdaSettings, queryOptions); for (int i = 1; i < expected2.getColumnCount(); i++) { expected2.setColumnName(i, "All Products/" + expected2.getColumnName(i)); } checker.setDoubleComparison(1, 1e-8); checker.assertEquals(expected2, result); }
From source file:pt.webdetails.cda.tests.ColumnDefinitionIT.java
@Test public void testColumnNames() throws Exception { final CdaSettings cdaSettings = parseSettingsFile("sample-columnDefinition.cda"); logger.debug("Doing query on Cda - Initializing CdaEngine"); QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId("1"); queryOptions.addParameter("status", "Shipped"); DataAccess dataAccess = cdaSettings.getDataAccess("1"); logger.info("Doing query"); TableModel table = TableModelUtils.postProcessTableModel(dataAccess, queryOptions, doQuery(cdaSettings, queryOptions)); assertEquals(table.getColumnCount(), 3); assertEquals(table.getColumnName(0), "Year"); assertEquals(table.getColumnName(1), "STATUS"); assertEquals(table.getColumnName(2), "PriceInK"); }
From source file:pt.webdetails.cda.tests.OutputColumnsIT.java
public void testSingleOutputColumn() throws Exception { final CdaSettings cdaSettings = getSettingsManager().parseSettingsFile("sample-sql.cda"); final CdaEngine engine = getEngine(); QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId("1"); List<String> outputColumnNames = new LinkedList<String>(); outputColumnNames.add("Year"); queryOptions.setOutputColumnName(outputColumnNames); TableModel tm = engine.doQuery(cdaSettings, queryOptions); Assert.assertEquals(tm.getColumnCount(), 1); Assert.assertEquals(tm.getColumnName(0), "Year"); }
From source file:pt.webdetails.cda.tests.OutputColumnsIT.java
public void testMultipleOutputColumn() throws Exception { final CdaSettings cdaSettings = getSettingsManager().parseSettingsFile("sample-sql.cda"); final CdaEngine engine = getEngine(); QueryOptions queryOptions = new QueryOptions(); queryOptions.setDataAccessId("1"); List<String> outputColumnNames = new LinkedList<String>(); outputColumnNames.add("Year"); outputColumnNames.add("STATUS"); queryOptions.setOutputColumnName(outputColumnNames); TableModel tm = engine.doQuery(cdaSettings, queryOptions); Assert.assertEquals(tm.getColumnCount(), 2); Assert.assertEquals(tm.getColumnName(0), "Year"); Assert.assertEquals(tm.getColumnName(1), "STATUS"); }
From source file:pt.webdetails.cda.utils.TableModelUtils.java
public static TableModel postProcessTableModel(final DataAccess dataAccess, final QueryOptions queryOptions, final TableModel rawTableModel) throws SortException, InvalidOutputIndexException { if (rawTableModel == null) { throw new IllegalArgumentException("Cannot process null table."); }//from www. j a va 2 s .c om // We will: // 1. Evaluate Calculated columns // 2. Show only the output columns we want; // 3. Sort // 4. Pagination TableModel table; // 1 Evaluate Calculated columns table = evaluateCalculatedColumns(dataAccess, rawTableModel); // 2. Show only the output columns we want, filter rows List<Integer> outputIndexes = getOutputIndexes(dataAccess, queryOptions, table); DataTableFilter rowFilter = getRowFilter(queryOptions, outputIndexes); //mdx and denormalizedMdx queries with an empty result set can return different metadata (less columns), //in this cases, the output indexes will be ignored boolean useOutputIndexes = true; if (table.getRowCount() == 0 && (dataAccess.getType().equals("mdx") || dataAccess.getType().equals("denormalizedMdx"))) { useOutputIndexes = false; logger.warn("Mdx query returned empty result set, output indexes will be ignored."); } table = useOutputIndexes ? filterTable(table, outputIndexes, rowFilter) : filterTable(table, new ArrayList<Integer>(), rowFilter); // 3. Sort if (!queryOptions.getSortBy().isEmpty()) { // no action table = (new SortTableModel()).doSort(table, queryOptions.getSortBy()); } // Create a metadata-aware table model final Class<?>[] colTypes = new Class[table.getColumnCount()]; final String[] colNames = new String[table.getColumnCount()]; for (int i = 0; i < table.getColumnCount(); i++) { colTypes[i] = table.getColumnClass(i); colNames[i] = table.getColumnName(i); } final int rowCount = table.getRowCount(); MetadataTableModel result = new MetadataTableModel(colNames, colTypes, rowCount); result.setMetadata("totalRows", rowCount); for (int r = 0; r < rowCount; r++) { for (int j = 0; j < table.getColumnCount(); j++) { result.setValueAt(table.getValueAt(r, j), r, j); } } // 4. Pagination return paginateTableModel(result, queryOptions); }
From source file:pt.webdetails.cda.utils.TableModelUtils.java
/** * @param table//from w ww . j a va2 s .c om * @param outputIndexes * @param rowFilter (optional) * @return * @throws InvalidOutputIndexException */ private static TableModel filterTable(final TableModel table, List<Integer> outputIndexes, final DataTableFilter rowFilter) throws InvalidOutputIndexException { int columnCount = outputIndexes.size(); if (columnCount == 0 && rowFilter != null) { //still have to go through the motions if we need to filter rows for (int i = 0; i < table.getColumnCount(); i++) { outputIndexes.add(i); } columnCount = outputIndexes.size(); } if (columnCount != 0) { //logger.info(Collections.max(outputIndexes)+" "+table.getColumnCount()); if ((Collections.max(outputIndexes) > table.getColumnCount() - 1)) { String errorMessage = String.format( "Output index higher than number of columns in tableModel. %s > %s", Collections.max(outputIndexes), table.getColumnCount()); logger.error(errorMessage); if (table.getColumnCount() > 0) { throw new InvalidOutputIndexException(errorMessage, null); } else { logger.warn( "Unable to validate output indexes because table metadata is empty. Returning table."); return table; } } final int rowCount = table.getRowCount(); logger.debug(rowCount == 0 ? "No data found" : "Found " + rowCount + " rows"); final Class<?>[] colTypes = new Class[columnCount]; final String[] colNames = new String[columnCount]; //just set the number of rows/columns final TypedTableModel typedTableModel = new TypedTableModel(colNames, colTypes, rowCount); for (int rowIn = 0, rowOut = 0; rowIn < rowCount; rowIn++, rowOut++) { //filter rows if (rowFilter != null && !rowFilter.rowContainsSearchTerms(table, rowIn)) { rowOut--; continue; } //filter columns for (int j = 0; j < outputIndexes.size(); j++) { final int outputIndex = outputIndexes.get(j); typedTableModel.setValueAt(table.getValueAt(rowIn, outputIndex), rowOut, j); } } //since we set the calculated table model to infer types, they will be available after rows are evaluated for (int i = 0; i < outputIndexes.size(); i++) { final int outputIndex = outputIndexes.get(i); typedTableModel.setColumnName(i, table.getColumnName(outputIndex)); typedTableModel.setColumnType(i, table.getColumnClass(outputIndex)); } return typedTableModel; } return table; }