Java Connector for dhtmlxGantt

If I connect the Gantt chart to DB through Java connector, do I then also load the data from JSON?. I am not getting this point.My requirement is to load the parent task and then to load the sub tasks only when the user expand the tree. Can I implement this with the current plugin?.

Thanks for your help.

If you have end_date and start_date columns that is fine as well
Try to use the code like next

conn.render_table("yourtable", "idkey", "yourstartdate(start_date), yourenddate(end_date), yourtext(text)");

here you need to replace the names of fields, but preserve values in brackets ( it instruct the connector to take the custom field from db, but process it as one of standard fields )

Yes, connector will generate json for the gantt ( you can any custom java code for the same task, connector is just one of options, it is not a mandatory requirement )

to load the sub tasks only when the user expand the tree
Not possible. Unless you are having thousands of tasks - it will cause significant effect on chart’s performance anyway.

It won’t work on Tomcat6 cause of “javax.servlet.annotation” usage.

I have tried that one with Tomcat7 and it worked to some extend (there also were some LoadXML errors while connecting task with dependency lines), however the most important issue for me is that if I try to go for Tomcat6, then I’m either having errors in lines cause of missing annotations support in Tomcat6/Dynamic Web Module 2.5:

import javax.servlet.annotation.WebServlet; @WebServlet(description = "The Gantt test", urlPatterns = { "/thegantt" })
or when I manually add the servlet-api.jar 3.0 from Tomcat7 to build path or change target back to Tomcat7, then it does compile fine in both cases (manual servlet-api 3.0 or target Tomcat7), but the gantts are not working after deployment to Tomcat6, it start, but displays empty grid/no tasks.

Please advise, how to maintain the Dynamic Web Module 2.5 compatibility in code to have it compile and running on Tomcat6 - so basically, how change the mentioned two lines in code to avoid using the annotations.

Regards,
TheUser.

The annotations are used only in the samples, and not used in the connector library itself.
You can use connector and gantt, just remove annotations and use any other way to configure url to servlet mapping.

Hello, java connector is excellent feature.
where can I get latest java connector for dhtmlxGantt? Is it still only beta version or there are release version? Are there any samples how use it?

Top post contains a code snippet, that contains ALL java code that you need. The component is fully client side, so it requires just a single servlet for data loading and data saving.

As for connector, there was not official updates ( there was no bug reports against Java Gantt Connector as well )

Please support the MariaDB.
How that can be mapped to an MVC Controller in Spring Framework environment is also required. I connector.jar configuration is too difficult to use.

There was no official update yet, so beta version is the latest one.

Need to say - it is quite stable, there are no known issues with Java Connector and dhtmlxGantt

This is not stable, you have a new version with a fixed bug (viewtopic.php?f=15&t=40534&start=0) but that .jar doesn’t come with source code so I can’t recompile it with java6. Any solution?

In this thread viewtopic.php?f=15&t=37572 there is another jar with source code. I think you should pin that version.

Yep, I have replaced jar package in the top post with the latest one.

Hello,
I am evaluating your dhtmlxGantt Java Connector. So far I got it connected to a MySQL and SqlServer environment using the methods render_table() and render_links(). This works quite well.

Now to the methods render_sql() and render_complex_sql(). As far as I understand, the Java Connector expects a table result, i.e. the output of a sql-select-statement, and will convert this into JSON by itself.

Concerning the dhtmlxGantt Java Connector I have two questions here:

Question 1) I managed to render a task table by a simple select statement as follows:

gantt.render_sql("SELECT * FROM gantt_tasks", "id", "start_date,duration,text,progress,sortorder, parent");

But how could I additionally render the corresponding links within the same chart as I did with render_table() and render_links()? Putting another statement as follows ended up with an exception:

gantt.render_sql("SELECT * FROM gantt_links", "id", "source, target, type");

Maybe I am blind, but I haven’t found a clue by reading through the documentation and form entries.

Question 2) We have a scalar sql function that already returns a valid JSON string containing a data-element for the tasks and a links-element for the links:

 {"data":[...], "collections":{"links":[...]}}

Is there a possibility to read this JSON string with one of the render_sql-methods? Not sure if we could easily refactor the sql-funktion.

Question 3) Ok, i said it was two questions and here comes number 3 :wink:
I only found your precompiled dhtmlGantt Java Connector here in the forum area. Unfortunately I could not find it at your download area. Is there some place were we could find the latest jars and/or sources even in beta stage?

Thank you in advance!

(1) Yes, there is no simple method. You can try to replace render_links with next lines

//gantt.render_links
OptionsConnector links = new OptionsConnector(gantt.get_connection(), DBType.MySQL);
links.render_sql(sql, "id", "id, source, target, type");
gantt.set_options("links", links);

(2) Nope, but why do you want to use a connector in such case? You can use your own code for data loading, which will use your custom code. There is no any extra benefit in using a connector for data loading.

(3)
Yep, you can get the full sources from github - github.com/DHTMLX/connector-java

Hello Stanislav,

thank you for your quick response!

(1) Code looked great - but had unfortunately no effect at my site. Well, I had to exhcange “gantt.get_connection()” because it seems to be private. But I already had a connection object.

Besides I found an IOException, when using the render_sql() method. Not sure where it is thrown exactly. My example code is:

@Override
protected void configure(HttpServletRequest request, HttpServletResponse response) {
// Init DB connection
...

// Init gantt connector
JSONGanttConnector gantt = new JSONGanttConnector(connection, DBType.MSSQL);
gantt.servlet(request, response);

// Render tasks
if (gantt.is_select_mode()) { // Code for loading data
    gantt.render_sql(SQL_SELECT_GANTT_TASKS, "id", "start_date,duration,text,progress,sortorder, parent");
} else { // Code for other operations, i.e. insert, update, delete.
    gantt.render_table("gantt_tasks", "id", "start_date,duration,text,progress,sortorder, parent");
}

// Render links
OptionsConnector links = new OptionsConnector(connection, DBType.MSSQL);
links.render_sql(SQL_SELECT_GANTT_LINKS, "id", "source, target, type");
gantt.set_options("links", links);
...
}

The exception already shows up without the “render links” part. Did I forget to close anything? Didn’t find such methods at JSONGanttConnector class.

java.io.IOException: Stream closed
      at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:45)
      at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:140)
      at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
      at com.dhtmlx.connector.LogManager.close(LogManager.java:114)
      at com.dhtmlx.connector.ThreadSafeConnectorServlet.doGet(ThreadSafeConnectorServlet.java:21)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
      at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
      at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
      at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
      at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
      at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
      at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
      at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
      at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
      at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
      at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
      at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
      at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
      at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
      at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
      at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
      at java.lang.Thread.run(Thread.java:745)|#]

(2) Yes, you are right… I should take a rest sometimes to get a clearer view :wink:

(3) Thanks, I will check that out.

Does anybody have a working example in how to use dhtmlx with java (jsf), thanks in advance

Hello Orlando,
Connectors are not actively developed. Although it is easier to configure a connector for a quick start, you cannot create a complex solution with it. So, it is recommended to use a backend:
https://docs.dhtmlx.com/gantt/desktop__howtostart_guides.html

Hello Ramil, I am starting with dhtmlx and java JSF, started following the contacs-manager demo, i’ll be using dhtmlx -> java servlet -> MSSql server data base.

After initialization and running the servlet on page load, the grid is not populated, its looks like the render_table(“TCiudades”,“id”,“csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo”); is not returning data.

Do you any idea what’s happening, some help, sorry for my bad english.

Initialization page:

dhtmlxEvent(window,“load”,function()
{ //provides the script as a handler of the ‘onload’ HTML event
//dhtmlx.message({ type: “alert”, text: “Starting dhtmlx test” });

        var layout,menu,toolbar,contactsGrid,contactForm;
        dhtmlx.image_path = "contact_manager/codebase/imgs/";
        layout = new dhtmlXLayoutObject(document.body,"2U");                       //initializes dhtmlxLayout
        layout.cells("a").setText("Contacts");                                     //sets the text in the header of the 'grid' column
        layout.cells("b").setText("Contact Details");                              //sets the text in the header of the 'form' column
        layout.cells("b").setWidth(500);                                           //sets the width of the 'form' column

        menu = layout.attachMenu();                                                //initializes dhtmlxMenu
        menu.setIconsPath("contact_manager/icons/");                                               //sets the path to custom icons
        menu.loadStruct("contact_manager/data/menu.xml");                                           //loads items from the "data/menu.xml" file to the menu

        toolbar = layout.attachToolbar();                                          //initializes dhtmlxToolbar
        toolbar.setIconsPath("contact_manager/icons/");                                            //sets the path to custom images
        toolbar.loadStruct("contact_manager/data/toolbar.xml");                                      //loads items from the "data/toolbar.xml" file to the toolbar

        contactsGrid = layout.cells("a").attachGrid();                             //initializes dhtmlxGrid
        contactsGrid.setHeader("Codigo,Descripcion,Riesgo");   //sets the headers of columns
        contactsGrid.setColumnIds("csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo");    //sets the columns' values                           //sets the column ids
        //contactsGrid.setInitWidths("200,200,*");                                 //sets the initial widths of columns
        contactsGrid.setColAlign("left,left,left");                                //sets the horizontal alignment
        contactsGrid.setColTypes("ro,ro,ro");                                      //sets the types of columns
        contactsGrid.setColSorting("str,str,str");                                 //sets the sorting types of columns
        contactsGrid.attachHeader("#text_filter,#text_filter,#text_filter");       //sets the filters for columns
        contactsGrid.init();                                                       //renders  dhtmlxGrid on the page
        
        //----------------- load data from server --------------------//
        contactsGrid.load("dhtmlx_Servlet");                                    //loads data from the "data/contacts.php" file to the grid
        //------------------------------------------------------------//
        
        contactForm = layout.cells("b").attachForm();                              //initializes dhtmlxForm
        contactForm.loadStruct("contact_manager/data/form.xml");                                   //loads controls, specified in the "data/form.xml" file to the form
        contactForm.bind(contactsGrid);                                            //binds the form to the grid

        var dpg = new dataProcessor("data/contacts.php");                          //inits dataProcessor
        dpg.init(contactsGrid);                                                    //associates the dataProcessor instance with the grid

        dpg.attachEvent("onAfterUpdate", function(sid, action, tid, tag){
            if (action == "inserted"){
                contactsGrid.selectRowById(tid);                                   //selects a row
                contactForm.setFocusOnFirstActive();                               //sets focus to the 1st form's input
            }
        })

        contactForm.attachEvent("onButtonClick", function(id){                     //attaches a handler function to the "onButtonClick" event
            contactForm.save();                                                    //sends the values of the updated row to the server
        });
        toolbar.attachEvent("onclick",function(id){                                //attaches a handler function to the "onclick" event
            if(id=="newContact"){                                                  //'newContact' is the id of the button in the toolbar
                var rowId=contactsGrid.uid();                                      //generates an unique id
                var pos = contactsGrid.getRowsNum();                               //gets the number of rows in the grid
                contactsGrid.addRow(rowId,["New contact","",""],pos);              //adds a new row to the grid. The 'addRow()' method takes 3 parameters: the row id (must be unique), the initial values of the row, the  position where the new must be inserted
            };
            if(id=="delContact"){                                                  //'delContact' is the id of the button in the toolbar
                var rowId = contactsGrid.getSelectedRowId();                       //gets the id of the currently selected row
                var rowIndex = contactsGrid.getRowIndex(rowId);                    //gets the index of the row with the specified id

                if(rowId!=null){
                    contactsGrid.deleteRow(rowId);                                 //deletes the currently selected row
                    if(rowIndex!=(contactsGrid.getRowsNum()-1)){                   //checks whether  the currently selected row is NOT last in the grid
                        contactsGrid.selectRow(rowIndex+1,true);                   //if the currently selected row isn't last - moves selection to the next row
                    } else{                                                        //otherwise, moves selection to the previous row
                        contactsGrid.selectRow(rowIndex-1,true)
                    }
                }
            }
        });

    })
</script>

My servlet:
public class dhtmlx_Servlet extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException 
{
    String data = "**** test ****";
    PreparedStatement qps;
    ResultSet rs = null;
    String city = "test";
    String sql;
    Connection conn = null;
    String username = "psv";
    String password = "psv_pw";
    com.dhtmlx.connector.GridConnector gc = null ;
    
    response.setContentType("text/html;charset=UTF-8");
    /*
    
    try {
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jdbc/PsFlowWeb");
        conn = ds.getConnection(username, password);

        sql = "SELECT top 1 *, csDescripcionCiudad as city from TCiudades";
        
        qps = conn.prepareStatement(sql);
        rs = qps.executeQuery();

        if (rs.next()) {
            city = rs.getString("city");
            //response.getWriter().write("---- inside rs.next ----");
        }
        response.getWriter().write(city);
        rs.close();
        qps.close();
        conn.close();
        
    } catch (SQLException ex) {
        Logger.getLogger("DashboardDAO").log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger("DashboardDAO").log(Level.SEVERE, null, ex);
    }
   */
    
    //response.getWriter().write(data);
    
    response.setContentType("text/html;charset=UTF-8");
    
    try (PrintWriter out = response.getWriter()) 
    {
        try 
        {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("jdbc/PsFlowWeb");
            conn = ds.getConnection(username, password);
            gc = new com.dhtmlx.connector.GridConnector(conn);
            gc.servlet(request, response);
            //gc.dynamic_loading(100);
            gc.enable_log("c:/PSFlow/logs/grid.log", true);
            gc.render_table("TCiudades","id","csCodigoCiudad,csDescripcionCiudad,csTipoRiesgo");
        } 
        catch (SQLException | NamingException ex) 
        {
            //Logger.getLogger(SqlServerDAOFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
   
}

Hello Orlando,
I specialize in dhtmlxGantt so unfortunately, I can’t really help you with dhtmlxGrid nor Java. You may try posting your question in this category:
https://forum.dhtmlx.com/c/suite/dhtmlxconnector-dataprocessor