dataset.java
来自「java实现浏览器等本地桌面的功能」· Java 代码 · 共 1,035 行 · 第 1/3 页
JAVA
1,035 行
/** * Requests that each {@link DataTable} in this DataSet save itself; this is * an <em>asynchronous</em> operation. See {@link DataTable#save()}; tables must have * been assigned a {@link DataProvider} already. */ public void save() { for (DataTable table : tables.values()) { if (!(table instanceof DataRelationTable)) { table.save(); } } } /** * Requests that each {@link DataTable} in this DataSet save itself; this is * a <em>synchronous</em> operation. See {@link DataTable#saveAndWait()}; tables must have * been assigned a {@link DataProvider} already. */ public void saveAndWait() { for (DataTable table : tables.values()) { if (!(table instanceof DataRelationTable)) { table.saveAndWait(); } } } /** * @return the Functor parser */ Parser getParser() { return parser; } /** * @deprecated use DataSetUtils.createFromXmlSchema instead */ public static DataSet createFromSchema(String schema) { return DataSetUtils.createFromXmlSchema(schema); } /** * Construct and return a proper schema file describing the DataSet * * @return A schema representing this DataSet. * @deprecated use DataSetUtils.getXmlSchema instead */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public String getSchema() { return DataSetUtils.getXmlSchema(this); } /** * Same as {@link #createFromSchema(String)}, but using a File as input source. * * @param f The File to read from. * @return a newly instantiated DataSet. * @deprecated use DataSetUtils.createFromXmlSchema instead */ public static DataSet createFromSchema(File f) throws FileNotFoundException { return DataSetUtils.createFromXmlSchema(f); } /** * Same as {@link #createFromSchema(String)}, but using a InputStream as input source. * * @param is The InputStream to read from. * @return a newly instantiated DataSet. * @deprecated use DataSetUtils.createFromXmlSchema instead */ public static DataSet createFromSchema(InputStream is) { return DataSetUtils.createFromXmlSchema(is); } /** * Same as {@link #readXml(String)}, but using a File as input source. * * @param f The XML Document, as a File. */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public void readXml(File f) { String xml = ""; try { FileInputStream fis = new FileInputStream(f); readXml(fis); fis.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Same as {@link #readXml(String)}, but using an InputStream as input source. * * @param is The XML Document, as an InputStream. */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public void readXml(InputStream is) { String xml = ""; try { StringBuilder builder = new StringBuilder(); byte[] bytes = new byte[4096]; int length = -1; while ((length = is.read(bytes)) != -1) { builder.append(new String(bytes, 0, length)); } xml = builder.toString(); readXml(xml); } catch (Exception e) { e.printStackTrace(); } } /** * Loads DataSet data from an XML Document in String format; when complete, the DataSet * will have been populated from the Document. * * @param xml The XML Document, as a String. */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public void readXml(String xml) { //TODO when parsing the xml, validate it against the xml schema try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(xml.getBytes())); //create the xpath XPath xpath = XPathFactory.newInstance().newXPath(); String path = null; //for each table, find all of its items for (DataTable table : tables.values()) { if (!(table instanceof DataRelationTable)) { table.fireDataTableChanged(TableChangeEvent.newLoadStartEvent(table)); //clear out the table table.clear(); if ( !table.isAppendRowSupported()) { LOG.fine("Table '" + table.getName() + "' does " + "not support append row; skipping (regardless of " + "input)."); continue; } LOG.finer("loading table " + table.getName()); //get the nodes path = "/" + name + "/" + table.getName(); NodeList nodes = (NodeList)xpath.evaluate(path, dom, XPathConstants.NODESET); LOG.finer(" found " + nodes.getLength() + " rows for path " + path); //for each node, iterate through the columns, loading their values for (int i=0; i<nodes.getLength(); i++) { //each rowNode node represents a row Node rowNode = nodes.item(i); DataRow row = table.appendRowNoEvent(); NodeList cols = rowNode.getChildNodes(); for (int j=0; j<cols.getLength(); j++) { Node colNode = cols.item(j); if (colNode.getNodeType() == Node.ELEMENT_NODE) { //TODO this doesn't take into account type conversion... //could use a default converter...// System.out.println(colNode.getNodeName() + "=" + colNode.getTextContent()); String text = colNode.getTextContent(); //convert the text to the appropriate object of the appropriate type Object val = text; Class type = table.getColumn(colNode.getNodeName()).getType(); if (type == BigDecimal.class) { val = new BigDecimal(text); } //TODO do the other types row.setValue(colNode.getNodeName(), val); } } row.setStatus(DataRow.DataRowStatus.UNCHANGED); } table.fireDataTableChanged(TableChangeEvent.newLoadCompleteEvent(table)); } } } catch (Exception e) { e.printStackTrace(); } } /** * Writes out the data in this DataSet as XML, and returns this as a String; * all rows are exported. * * @return the contents of this DataSet, as XML, in a String. */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public String writeXml() { return writeXml(OutputControl.ALL_ROWS); } /** * Writes out the data in this DataSet as XML, and returns this as a String. * * @param flags Value indicating whether all rows (OutputControl.ALL_ROWS) * or only new and modified rows should be spit out. * @return the contents of this DataSet, as XML, in a String. */ //* TODO: need the schema documented somewhere; we might want to list the URL for the schema here (PWW 04/27/05) public String writeXml(OutputControl flags) { StringBuilder builder = new StringBuilder(); builder.append("<?xml version=\"1.0\" ?>\n"); builder.append("<"); builder.append(name); builder.append(">\n"); for (DataTable table : tables.values()) { if (!(table instanceof DataRelationTable)) { for (DataRow row : table.rows) { if ( flags == OutputControl.MODIFIED_ONLY && row.getStatus() == DataRow.DataRowStatus.UNCHANGED ) { continue; } builder.append("\t<"); builder.append(table.getName()); builder.append(">\n"); for (DataColumn col : table.columns.values()) { builder.append("\t\t<"); builder.append(col.getName()); builder.append(">"); String val = row.getValue(col) == null ? "" : row.getValue(col).toString(); //escape val val = val.replaceAll("&", "&"); val = val.replaceAll("<", "<"); val = val.replaceAll(">", ">"); val = val.replaceAll("'", "'"); val = val.replaceAll("\"", """); builder.append(val); builder.append("</"); builder.append(col.getName()); builder.append(">\n"); } builder.append("\t</"); builder.append(table.getName()); builder.append(">\n"); } } } builder.append("</"); builder.append(name); builder.append(">"); return builder.toString(); } public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("DataSet: ").append(name).append("\n"); for (DataTable table : tables.values()) { if (table instanceof DataRelationTable) { buffer.append("\tDataRelationTable: ").append(table.getName()).append("\n"); } else { buffer.append("\tDataTable: ").append(table.getName()).append("\n"); } for (DataColumn col : table.getColumns()) { buffer.append("\t\tDataColumn: ").append(col.getName()).append("\n"); } } for (DataRelation relation : relations.values()) { buffer.append("\tRelation: ").append(relation.getName()).append("\n"); DataColumn parentColumn = relation.getParentColumn(); buffer.append("\t\tParentColumn: ").append(parentColumn == null ? "<none>" : parentColumn.getTable().getName()).append(".").append(parentColumn == null ? "<none>" : parentColumn.getName()).append("\n"); DataColumn childColumn = relation.getChildColumn(); buffer.append("\t\tChildColumn: ").append(childColumn == null ? "<none>" : childColumn.getTable().getName()).append(".").append(childColumn == null ? "<none>" : childColumn.getName()).append("\n"); } buffer.append(getSchema()); return buffer.toString(); } /** * Test function from command line; no arguments needed */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); try { DataSet ds = DataSetUtils.createFromXmlSchema(new File("/usr/local/src/databinding/src/test/org/jdesktop/dataset/contact.ds")); } catch (Exception e) { e.printStackTrace(); } long stopTime = System.currentTimeMillis();// System.out.println(ds.toString()); System.out.println((stopTime - startTime)); // //now, populate// ds.readXml(new File("/usr/local/src/swinglabs-demos/src/java/org/jdesktop/demo/adventure/resources/dataset.xml"));// System.out.println(ds.getTable("package").getRowCount());// DataTable table = ds.getTable("activity");// double total = 0;// for (DataRow row : table.getRows()) {// total += ((Number)row.getValue("price")).doubleValue();// }// System.out.println(total);// System.out.println(ds.getValue("totalValue").getValue()); // try {// Class.forName("org.postgresql.Driver");// java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost/ab", "rb156199", "Tesooc7x");// java.util.Set<String> names = new java.util.HashSet<String>();// names.add("package.name");// names.add("activity");// names.add("activitylist");// DataSet ds = DataSetUtils.createFromDatabaseSchema(conn, "ab", names);// System.out.println(ds);// java.io.File f = new java.io.File("/usr/local/src/databinding/src/test/org/jdesktop/dataset/blar.ds");// java.io.OutputStream os = new java.io.FileOutputStream(f);// os.write(ds.getSchema().getBytes());// os.close();// } catch (Exception e) {// e.printStackTrace();// } } /** * A PropertyChangeListener--used to track changes to table, relation and * value names as our Maps are keyed by those names--will automatically * pick up new names and adjust Map entries. Tables, relations and values * have this listener attached when added to the DataSet. */ private final class NameChangeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { Object source = evt.getSource(); if (source instanceof DataTable) { DataTable table = (DataTable)source; tables.remove(evt.getOldValue()); tables.put((String)evt.getNewValue(), table); } else if (source instanceof DataRelation) { DataRelation relation = (DataRelation)source; relations.remove(evt.getOldValue()); relations.put((String)evt.getNewValue(), relation); } else if (source instanceof DataValue) { DataValue value = (DataValue)source; values.remove(evt.getOldValue()); values.put((String)evt.getNewValue(), value); } } }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?