Building jtree from database query

I am trying to build a JTREE from a database result-set. The resultset is listed below. I'm thinking I can somehow build a dynamic array of objects to build a TreePath, then use that to build the JTREE. Any input is appreciated.
ResultSet Output:
Here is how the results would be retrieved from the database (including the order of the output).
usr 1
local 2
sbin 2 file4
bin 3 file1
bin 3 file2
logs 3 file3
tmpdir 4
The first column is the directory name, the second column is the directory/file level/position, and the third column is the filename, if one exists.
So from above:
/usr/local/sbin has file "file4"
/usr/local/bin has files "file1" and "file2"
/usr/local/logs has file "file3" and directory "tmpdir"
How could I gather this information into an appropriate structure and create a JTREE from it.
Thanks.
-Jim

So each line would:basically...
If I don't know the entire path of the parent (because I've read in a
line that only has the "one-up" parent name) .... However, when I
read the line from the database result-set, I don't know where "local" is.See... that's another problem with that data. Maybe you know cuz it's the last node if it's all in a proper order. In which case maybe you only need to hold the last parent node... Some recursive function would be useful.
If I were going to store the data, I would store either the name as a full path:
/usr
/usr/local
/usr/loca/bin
or
usr /
local /usr
bin /usr/local
If you have that, it might be easier to figure out without having to worry about what belongs where.

Similar Messages

  • Populating JTree from database

    Hi experts,
    I need some feedbacks about the way i populate my JTree from database, Is there any better alternatives?
    If yes, try explain it in detail.. I'm still new in Java.
    Sample database table:
    |       node_id      |       name      |       parent       |       hasChild      |
    |         1          |     garbage     |        null        |           1         |
    |         2          |       item      |          1         |           1         |
    |         3          |      mouse      |          2         |           0         |
    |         4          |       board     |          2         |           0         |
    |         5          |       item2     |          1         |           1         |
    |         6          |       item3     |          1         |           1         |
    |         7          |       pants     |          5         |           0         |
    -----------------------------------------------------------------------------------Here's the sample of my code:
    //... ResultSet rs = .....
    rs.last();
    int rowCount = rs.getRow(); //Get the total number of row in database table
    rs.beforeFirst();
    int i = 0;
    int j = 0;
    String [] nodeID = new String[rowCount];  //The node ID
    String [] parentID = new String[rowCount];  //A pointer to its parent ID
    DefaultMutableTreeNode [] node = new DefaultMutableTreeNode[rowCount]; //The node
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean bool = rs.getBoolean("hasChild");
         node[i] = new DefaultMutableTreeNode(name,bool);
         parentID[i] = rs.getString("parent");
         nodeID[i] = rs.getInt("node_id") + "";
            //Set as root node when the pointer is null               
         if(parentID.equals("null")) {
              rootNode = node[i];
         i++;
    for(i=0; i<rowCount; i++) {
         for(j=0; j<rowCount; j++) {
              if(parentID[j].equals(nodeID[i]) && node[i] != null) {
                   node[i].add(node[j]);
    node[i] = null; //Obligates the parent after finish adding the child (to prevent unnecessary loops)
    //... tree = new JTree(rootNode);
    Thanks for the trouble,
    Regards,
    David

    The execution time are base on the code i post'ed here.
    Average over 30times using Vector = 640048 nanosecond to execute.
    Vector<String> nodeID = new Vector<String>();
    Vector<DefaultMutableTreeNode> node = new Vector<DefaultMutableTreeNode>();
    Vector<String> parentID = new Vector<String>();
    rs.last();
    int rowCount = rs.getRow();
    rs.beforeFirst();
    k=0;
    while(rs.next()) {
         String name = rs.getString("name");
         Boolean hasChild = rs.getBoolean("hasChild");
         node.addElement(new DefaultMutableTreeNode(name,hasChild));
         nodeID.addElement(rs.getInt("node_id")+"");
         parentID.addElement(rs.getString("parent"));
         if(parentID.elementAt(k).equals("null")) {
              rootNode = node.elementAt(k);
         k++;
    i=0;
    while(i<rowCount) {
         j=0;
         while(j<rowCount) {
              if(parentID.elementAt(j).equals(nodeID.elementAt(i)) && node.elementAt(j) != null) {
                   node.elementAt(i).add(node.elementAt(j));
                   if(!node.elementAt(i).getAllowsChildren())
                        node.insertElementAt(null,j);
              j++;
         i++;
    }Average over 30times using LinkedList = 95623 nanosecond to execute.
    //This section will have a class Nodes
    LinkedList<Nodes> gather = new LinkedList<Nodes>();
    while(rs.next()) {
         node = new DefaultMutableTreeNode(rs.getString("name"),rs.getBoolean("hasChild"));                    
         gather.add(new Nodes(rs.getInt("node_id") + "",node,rs.getString("parent")));
    for(Nodes findParent : gather) {                    
         if(findParent.getParentID().equals("null")) {
              findParent.setRoot(findParent.getNode());
              rootNode = findParent.getRoot();
         for(Nodes findChild : gather){
              if(findChild.getParentID().equals(findParent.getNodeID()))
                   findParent.getNode().add(findChild.getNode());               
    }As for the Array method i used from the previous post, the Average code execution time is x3 larger than the vector i used. So please do not use that method.
    Note: 1. The code i post can be improved further. 2. Execution time is based on individual computer.
    Well, I think i'll stop here. Anyone who wanted to know which method is more efficient currently, here's the answer.
    Hope that it helps anyone who have the problem here =).
    Edited by: DavidTW on May 23, 2011 3:14 PM
    Improved Version : Using for-each loop ( Effective Java, Second Edition, Joshua Bloch, Pg. 210).

  • Building JTrees from Filename strings????

    Does anybody know or have code to build JTrees from fileName string so that the tree is expandable and uses expansion listeners.

    Does anybody have code that allows you to show the local filesystem and also file strings contained say in a file so they can both be viewed at the same time. ie if you know somebody else has a file but you want it reflected in your local filesystem.
    Come on somebody must

  • Query builder: tables from Database Link

    Hi APEX people,
    Is there a way to use tables from a (remote) Database Link in the Query Builder?
    In the Query Builder I seem to have only access to locally (schema) stored tables.
    I already tried to define a Synonym for the remote tables I wanted to use, but that didn't work either.
    Thanks in advance.
    Maurice

    Hi,
    First of all, can you select from them ie
    SELECT  *
    FROM my_table@my_linkAlso you can't see them as tables in the schema because they're not tables in the schema.
    Try creating a view like...
    CREATE OR REPLACE FORCE VIEW m_table_vw AS
    SELECT *
    FROM my_table@my_link;You should be able to see the view in the schema in the query builder and use that.
    Cheers
    Ben

  • Creating dynamically JTree from database values

    Hi,
    I have a local database with some node values. I receive these values from database as a String[].
    short example:
    String[] Values = {"mainNode","Processors","mainNode","RAM","mainNode","Monitors",
    "Processors","INTEL","Processors","AMD","RAM","Kingston","RAM","GoodRAM",
    "Kingston","400MHz","Kingston","433MHz"}First value is higher node, second is a child.
    I'd like to produce dynamically JTree from Values[] like below:
    MainNode
    |----Processors
          |----INTEL
          |----AMD
    |----RAM
          |----Kingston
                |----400MHz
                |----433MHz
          |----GoodRam
    |----MonitorsI can't build up any working and fast solution :(
    Can anyone help me ?
    Please for any advices (samples) which will help me to apply it.
    Dearly regards!

    This is a relatively straight forward task but it smacks of being homework so unless you post what you have already done you are unlikely to be given any code.
    As a hint -
    Go through the data creating a Map between the parent value and a child DefaultMutableTreeNode which contains as user object the child String.
    When you extract a parent String from the data lookup the parent DefaultMutableTreeNode in the map and add the child DefaultMutableTreeNode to the parent DefaultMutableTreeNode.
    Note - All the map is doing is giving you a quick way of looking up a DefaultMutableTreeNode given a parent name.
    Note - that your tree will have problems if the same value appears in two or more branches!

  • Generate an xml file from Database query results

    Hi, can anyone help me out with this problem I'm having. What are the steps in creating an xml file directly from the results of a database query. I currently have a very simply process that queries a database via a partner link. The query returns the data but it's from this point that I am stuck. I need to create an xml file with the data along with the xml tags. I've looked at dozens of tutorials with no luck.
    I would greatly appreciate help with this.
    bpel rookie

    Should be quite simple.
    Create another partnerlink, configure it to use the file adapter, and write to an XML file. In this case you need to create an XML Schema (.xsd) of the file you want to create.
    Before you write to the file, either add assign steps to copy individual attributes or use a transform activity to convert from the database format to the file (xml) format.

  • Displaying carriage returns from database query

    hi i'm fairly new to colfusion but have a good basic
    understanding.
    i'm trying to build a community website that has a guestbook
    and forums. i want to build these from scratch.
    i'm using cfmx7 and sqlserver 2005.
    the problem i'm having is when my cfm page retrieves posts
    made to the guestbook or forum, the carriage return characters are
    missing. posts are coming out all on one line.
    how do i get the retrieved posts to display new lines and
    paragraphs the way they were input into the database?
    just like these forums do?
    thanx so much. adella.

    Here is the code. Just replace body with your db field name.
    <cfoutput>
    #Replace(body, newLine, "<br>", "ALL")#
    </cfoutput>

  • Jtree from database

    hii all,
    Does any one know hw to populate a Jtree from a database.pls hlep me with an example.
    thanx

    Hi there,
    Im having exactly the same problem. If you find out, please let me know, and I will do the same for you.
    Thanks
    Simon

  • Retrieving Strings from Database query ??

    Hi,
    The problem i'm having at the moment is, with the following code:
    connect = DriverManager.getConnection("jdbc:mysql://ash.bc.ic.ac.uk/KEGG_devel?user=null&password=guest");
    Statement stmnt1 = connect.createStatement();
    ResultSet rs1 = stmnt1.executeQuery("SELECT DISTINCT A.ReactID, A.ECid FROM ECReact As A INNER JOIN ECReact As B ON A.ECid = B.ECid AND A.id <> B.id ");
    System.out.println("the size of rs1 is: " +rs1.getFetchSize());
    while (rs1.next()){
    String reactionId = rs1.getString("ReactID");
    String ecNumb = rs1.getString("ECid");
    System.out.println("the value of ecNumb is :" +ecNumb);
    I want to be able to retrieve a String from the query called ECid - an example of such a String would be 4.2.1.86 or 4.2.1.44. However, when i'm Storing the "ECid" in a String called ecNumb and then printing the String all that i get returned is the last 2 digits !
    Does anyone know how to resolve this ??
    Thanks very much for any help
    (oh yeah + for future reference, how do i highlight code in topics??)

    to highlight code... isSimple...
    [bold] [ code][bold]
    your code pasted in here
    [bold] [ / code][bold]
    but leave out the spaces in the []
    i had to add them to get [ c o d e ] to show up.
    m.

  • Confusion building JTree from path strings

    If I have a bunch of strings like this:
    "/dira/dir1/file1"
    "/dira/dir1/file2"
    "/dira/dir2/file1"
    "/dira/dir3/anotherdir/file1"
    etc.
    Does anybody have an easy solution to getting them in a JTree that looks like this:
       dira
        |
        +-dir1
        |  |
        |  +-file1
        |  |
        |  +-file2
        |
        +-dir2
        |  |
        |  +-file1
        |
        +-dir3
           |
           +-anotherdir
              |
              +-file1Mainly I am having trouble getting the tree to populate without duplicating nodes. For example dir1 gets listed twice. I am looking for a solution that will parse these strings and build the tree. I have found demos that read a file system, but nothing that works with strings. I have tried to pick apart the file system demos, but so far I can't get it to work correctly.
    Thanks,
    Jeff

    This compiles and works (with 1.4):
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.HashMap;
    public class TreeStrings extends JFrame {
        public TreeStrings() {
            super("Tree strings");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(500, 400);
            String[] inputStrings = {"/dira/dir1/file1", "/dira/dir2/file1", "/dira/dir2/file2"}; // your bunch of Strings     
         DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("www");
         HashMap nodeMap = new HashMap();
         for(int i = 0; i < inputStrings.length; i++) {
             String s = inputStrings;
         DefaultMutableTreeNode lastNode = rootNode;
         int lastIndex = 0;
         while(true) {
              DefaultMutableTreeNode tempNode = null;
              int nextIndex = s.indexOf("/", lastIndex + 1); // <- i forgot + 1
              if(nextIndex != -1) { //we are somewhere in middle of s, checking nodes from root to leaf, one by one.
         String nodeKey = s.substring(0, nextIndex);
         if(nodeMap.get(nodeKey) == null) { //no such node, must make one
              String nodeName = s.substring(lastIndex, nextIndex); // you want the last nodeKey word for node name
         DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName);
         nodeMap.put(nodeKey, newNode);
         lastNode.add(newNode);
         lastNode = newNode;
         else { //allready such node, just put it to be lastNode
         lastNode = (DefaultMutableTreeNode) nodeMap.get(nodeKey);
    lastIndex = nextIndex;
         else { //no more "/" , it means we are at end of s, and that all parent nodes for this leaf-node exist.
         // and we just add the leaf node to last node
         String leafName = s.substring(lastIndex, s.length());
         DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(leafName);
         lastNode.add(leafNode);
         break; // go to next s
         //You first make your tree structure with DefaultMutableNodes,
         //Then make a DefaultTreeModel with the root node,
         //Then make a Tree with the DefaultTreeModel
         DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree yourTree = new JTree(treeModel);
    getContentPane().add(yourTree, BorderLayout.CENTER);
    show();
    public static void main(String[] args) {
         new TreeStrings();
    Anything else?

  • KEY-EXEQRY trigger and FROM CLAUSE QUERY problem

    Hi,
    I have a form designed in Oracle Forms6i. I have two block on it, BlockA and BlockB.
    When BlockA is queried with some data to search, I need to build the FROM CLAUSE QUERY for BlockB. It uses the same WHERE condition as I used to search BlockA.
    I am building the FROM CLAUSE QUERY and executing query for BlockB on KEY-EXEQRY trigger of BlockA.
    It works fine, if first time, I query the BlockA without any specific data. But it gives me error 'ORA-01008: not all variables bound' if I query the BlockA with specific data very first time.
    Please advise.
    Thanx
    Zaaf

    No, I am not using any substitution variables. To get the LAST_QUERY for BlockA, I am using Get_Block_Property.
    But now I switched it to :system.LAST_QUERY and it worked.
    Thank you!

  • How to find controlfile size by using database query

    Dear All,
    Is it possible to get controlfile size from database query.
    Db Version :- 10.2.0.1.0
    Os :--- Linux RHEL 4
    Waiting for your reply.
    Thanks & Regards,
    Praful
    Nothing is impossible.........................

    OK but the control file block size is different from database block size (at least on XE):
    SQL> select * from v$controlfile;
    STATUS
    NAME
    IS_ BLOCK_SIZE FILE_SIZE_BLKS
    C:\ORACLEXE\ORADATA\XE\CONTROL.DBF
    NO       16384            450
    SQL> show parameter block_s
    NAME                                 TYPE        VALUE
    db_block_size                        integer     8192

  • Build a JTree from data

    Hello everyone,
    I have to build a JTree from a table data from database. The table structure is
    (id,parent_id,name). In order to build the tree, I have to the following 2 loop searching for the parent_id
    while (i<size){
    while(j<size){
    //find it's parent_id
    j++;
    i++;
    It is too slow! Can anyone help me?
    Thanks!
    --tc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You just add children to whatever the parent node is for that object.DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    child1 = new DefaultMutableTreeNode();
    root.add( child1 );
    grandChild = new DefaultMutableTreeNode();
    child1.add( grandChild );
    greatGrandChild = new DefaultMutableTreeNode();
    grandChild.add( greatGrandChild );Etc.

  • Jtree examples of populating data from database

    I have searched many of the solutions here, but the threads that contain examples of jtree loading from an sql database are not available. Does anyone have a good example of populating a jTree from the database?
    Thank You

    Hi,
    AFAIK, there is no direct approach to populate a JTree directly from a resultset. However, JTree can use a DOM tree as its model by using the adapter pattern. The procedure to do this is well-documented in the SUN website and the link is provided below. The code to convert a resultset to XML is provided below:
    protected void resultSetToXML(OutputStream out,
    ResultSet rs,
    String stylesheet)
    throws IOException, ServletException {
    // Create reader and source objects
    SqlXMLReader sxreader = new SqlXMLReader();
    SqlInputSource sis = new SqlInputSource(rs);
    // Create SAX source and StreamResult for transform
    SAXSource source = new SAXSource(sxreader, sis);
    StreamResult result = new StreamResult(out);
    // Perform XSLT transform to get results. If "stylesheet"
    // is NULL, then use identity transform. Otherwise, parse
    // stylesheet and build transformer for it.
    try {
    // Create XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;
    if (stylesheet == null) {
    t = tf.newTransformer();
    } else {
    // Read XSL stylesheet from app archive and wrap it as
    // a StreamSource. Then use it to construct a transformer.
    InputStream xslstream = _config.getServletContext().
    getResourceAsStream(stylesheet);
    StreamSource xslsource = new StreamSource(xslstream);
    t = tf.newTransformer(xslsource);
    // Do transform
    t.transform(source, result);
    } catch (TransformerException tx) {
    throw new ServletException(tx);
    The classes SQLXMLReader and other classes used in this example are available in the following java packages.
    import java.sql.*;
    import javax.sql.DataSource;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.sax.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.AttributesImpl;
    The following is the link that explains how to load a JTree from DOM.
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM6.html
    Cheers,
    vidyut

  • Want JTree e.g. of populating data from database.

    I want ur JTree example of populating data from database, can u plz give me that eg.?
    Awaiting 4 ur reply.

    Hi,
    AFAIK, there is no direct approach to populate a JTree directly from a resultset. However, JTree can use a DOM tree as its model by using the adapter pattern. The procedure to do this is well-documented in the SUN website and the link is provided below. The code to convert a resultset to XML is provided below:
    protected void resultSetToXML(OutputStream out,
    ResultSet rs,
    String stylesheet)
    throws IOException, ServletException {
    // Create reader and source objects
    SqlXMLReader sxreader = new SqlXMLReader();
    SqlInputSource sis = new SqlInputSource(rs);
    // Create SAX source and StreamResult for transform
    SAXSource source = new SAXSource(sxreader, sis);
    StreamResult result = new StreamResult(out);
    // Perform XSLT transform to get results. If "stylesheet"
    // is NULL, then use identity transform. Otherwise, parse
    // stylesheet and build transformer for it.
    try {
    // Create XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;
    if (stylesheet == null) {
    t = tf.newTransformer();
    } else {
    // Read XSL stylesheet from app archive and wrap it as
    // a StreamSource. Then use it to construct a transformer.
    InputStream xslstream = _config.getServletContext().
    getResourceAsStream(stylesheet);
    StreamSource xslsource = new StreamSource(xslstream);
    t = tf.newTransformer(xslsource);
    // Do transform
    t.transform(source, result);
    } catch (TransformerException tx) {
    throw new ServletException(tx);
    The classes SQLXMLReader and other classes used in this example are available in the following java packages.
    import java.sql.*;
    import javax.sql.DataSource;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.sax.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.AttributesImpl;
    The following is the link that explains how to load a JTree from DOM.
    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM6.html
    Cheers,
    vidyut

Maybe you are looking for

  • Best Practice for sugar refinery process

    hello, my company need to deploy a new business concerning raw sugar refinery. so we need to analyze the business requirements and propose a process for refinery management  . step 1: arrival of goods in docks step 2: raw sugar need to be charged in

  • Can't see my second site

    I've published my 1st site and can see it via my browser, but when I created a second site with iWeb08 and tried to see how it looked via my browser I get an error of "We're sorry but we can't find the iWeb page you've requested. It's possible that"

  • Critical Battery alarm needs to be heard, even when muted.

    Hello all and thanks for the support. I have a DV7 w/Vista Home Premium SP2 64-bit that is used for telecommuting. The Citrix app I remotely log into fills the entire screen including the task bar of the local machine with the desktop of the remote m

  • Can't charge Apple BT headset through iPhone 3G Dock?

    Is this correct? I plugged the BT charging cable into the Apple iPhone 3G dock. I put the iPhone in the dock to charge, and the headset in its charging port, and left it overnight. This morning I noticed the headset had lost charging! Then I just plu

  • How to access a function of PopupWindow from a Main file

    Hello All, I have a function in a PopupWindow. I want to access that function from another file. Can someone help me in this respect. Thanks in Advance, Nirmal Kumar Bhogadi.