How can I draw gantt chart with date from database in java - java

I have problem in taking from the database the startdate and the finaldate of task to draw the chart
public IntervalCategoryDataset getCategoryDataset() {
conn = ConnectDB.ConnectDB();
TaskSeriesCollection dataset = new TaskSeriesCollection();
String sql = "SELECT `TITRE`, `DATE DEBUT Prévi`, `DATE FIN prévi` FROM `projet`;";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
String a = rs.getString("TITRE");
Date StartDate = rs.getDate("DATE DEBUT Prévi");
Date EndDate = rs.getDate("DATE FIN prévi");
Names.add(a);
Dates.add(StartDate);
Dates.add(EndDate);
++count;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
int j = 0;
int k = 1;
TaskSeries series1 = new TaskSeries("Estimated Date");
for (int i = 0; i < count; i++) {
series1.add(new Task(Names.get(i),
Date.from(LocalDate.of(Dates.get(j).getYear(), Dates.get(j).getMonth(), Dates.get(j).getDay())
.atStartOfDay()
.toInstant(ZoneOffset.UTC)),
Date.from(LocalDate.of(Dates.get(k).getYear(), Dates.get(k).getMonth(), Dates.get(k).getDay())
.atStartOfDay()
.toInstant(ZoneOffset.UTC))));
}
dataset.add(series1);
return dataset;
}
I expect to have for every tasks its chart but I have the same chart for all the tasks.

You should apply a single loop, and in addition either use getObject(index, LocalDate.class) or - if your driver doesn't support the previous option - java.sql.Date.toLocalDate():
public IntervalCategoryDataset getCategoryDataset() {
conn = ConnectDB.ConnectDB();
TaskSeriesCollection dataset = new TaskSeriesCollection();
TaskSeries series1 = new TaskSeries("Estimated Date");
String sql = "SELECT `TITRE`, `DATE DEBUT Prévi`, `DATE FIN prévi` FROM `projet`;";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("TITRE");
LocalDate startDate = rs.getObject("DATE DEBUT Prévi", LocalDate.class);
LocalDate endDate = rs.getObject("DATE FIN prévi", LocalDate.class);
series1.add(new Task(name,
Date.from(startDate.atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(endDate.atStartOfDay().toInstant(ZoneOffset.UTC)));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
dataset.add(series1);
return dataset;
}

You always get the same result because the j and k values are stacked in their default values and not incrementing along with the i counter in your for loop. Referring to the code am seeing, i advise you to get rid of the j and k counters, replace the j with i and the k with i+1.
Your for loop should be like the following:
for (int i =0; i<count; i++) {
series1.add(new Task(Names.get(i),
Date.from(LocalDate.of(Dates.get(i).getYear(), Dates.get(i).getMonth(),Dates.get(i).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC)),
Date.from(LocalDate.of(Dates.get(i+1).getYear(),Dates.get(i+1).getMonth(),Dates.get(i+1).getDay()).atStartOfDay().toInstant(ZoneOffset.UTC))
)
);
}

Related

Thread automatically stop (freeze) in Eclipse

I am running a thread in eclipse to get data from mysql server. Thread works fine. The problem is after bit of time thread stop running(withing 6 to 8 hours). Thread get freeze. After that I have to manually close and re-run the program. Eclipse runs in a windows server 2012 r2 machine. No error or exception is shown.
Main class.
public class Main {
private final static int fONE_DAY = 1;
private final static int fZERO_MINUTES = 0;
public static void main(String[] argv) {
Timer timer1 = new Timer();
Timer timer4 = new Timer();
try {
timer1.scheduleAtFixedRate(new CearteSDQuatation(),500 , 1000*60*4);// 4min
System.out.println("timer 1 : createSDQuotation");
} catch (Exception e) {
e.printStackTrace();
}
try {
timer4.schedule(new GarbageCol(), 5000, 1000 * 60 * 60);// 60mins
System.out.println("timer 2 : garbageCollector");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Date getTomorrowRunningTime(int Ftime){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
Ftime,
fZERO_MINUTES
);
return result.getTime();
}
}
CearteSDQuatation class.
public class CearteSDQuatation extends TimerTask {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");;
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
DBPool_SF pooler;
DataSource dataSource;
DataSource dataSource1;
DBTableQueryExcecutre qex = null;
DBTableQueryExcecutre qex3 = null;
DBTableQueryExcecutre qex1 = null;
DBTableQueryExcecutre qex2 = null;
ArrayList<String> dates = null;
HashSet<String> dateSet = null;
Iterator<String> itr = null;
StringBuilder inClause;
int rcount = 0;
StringBuilder sbDel = null;
int delStatus = 0;
ArrayList<String> elements = new ArrayList<String>();// for update query
int queryStatus = 0;
String delete_query1 = " ";
String strDate = "";
String strMatnr = "";
String strkunnr = "";
// Object for table data
private Object[][] itemData;
RFCHandler handler;
public CearteSDQuatation(){
handler = new RFCHandler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
CallItem_ListCreate();
CallRFC_CreateSDQuata();
System.out.println("Thread Run");
}
catch (Exception e){
e.printStackTrace();
}
}
private void CallItem_ListCreate() {
// TODO Auto-generated method stub
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Create Quotation : Started sub excecutions List create...");
String sbQuery3 = "SELECT d.plant, h.dis_channel, h.order_no, h.Rep_no," +
"h.dealer_no,h.order_date,h.last_date, d.items_no," +
"d.quantity " +
"FROM tbl_item_list as d, " +
"tbl_items_header_t as h " +
"where d.order_no = h.order_no " +
"and h.status <> 'X'" ;
try {
pooler = DBPool_SF.getInstance();
dataSource1 = pooler.getDataSource();
System.out.println("pooler");
} catch (Exception e1)
{
e1.printStackTrace();
}
try {
Connection con3 = dataSource1.getConnection();
con3.setAutoCommit(false);
Statement st = con3.createStatement();
ResultSet rs = st.executeQuery(sbQuery3);
int lineitem = 0;
try {
rs.last();
rcount = rs.getRow();
rs.beforeFirst();
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("while loop");
itemData = new Object[9][rcount];
while(rs.next())
{
itemData[0][lineitem] = rs.getString("plant");
lineitem = lineitem + 1;
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void CallRFC_CreateSDQuata()
{
System.out.println("Create Quotation : Started sub excecutions");
JCO.Table IT_LIST = null;
JCO.Table IT_LIST1 = null;
JCO.Table IT_REF = null;
JCO.Table IT_Msg = null;
try {
if(rcount > 0)
{
handler.createRFCFunction("ZSL");
IT_LIST = handler.getTablePara("IT_LIST");
IT_LIST1 = handler.getTablePara("IT_LIST1");
for(int x = 0; x < rcount; x++ )
{
IT_LIST.appendRow();
IT_LIST1.appendRow();
IT_LIST.setValue( itemData[0][x].toString().trim(), "SAL_ORG");
}
handler.excFunction();
IT_REF = handler.getTablePara("IT_REF");
IT_Msg = handler.getTablePara("IT_MSG");
handler.releaseClient();
int int_row = IT_REF.getNumRows();
if (int_row > 0) {
this.tableOparator(IT_REF , IT_Msg);
}
}
} catch (Exception ex) {
handler.releaseClient();
ex.printStackTrace();
}
finally {
// Release the client to the pool
//handler.releaseClient();
rcount = 0;
}
}
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
public void tableOparator(JCO.Table table , JCO.Table table1 ) throws Exception {
pooler = DBPool_SF.getInstance();
dataSource = pooler.getDataSource();
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
qex = new DBTableQueryExcecutre(con);
StringBuilder sbQuery = new StringBuilder(
"INSERT INTO tbl_RefQut (QuatationNo,RefOrderNumber) VALUES");
System.out.println("COL -->"+table.getNumRows()
+ " records to insert for tbl_RefQut");
// --- create query ---------------------------------
for (int i = 0; i < table.getNumRows(); i++) {
// table.setRow(i);
sbQuery.append("(?,?),");
}
sbQuery.deleteCharAt(sbQuery.length() - 1);
sbQuery.append(";");
qex.setUpdateQuery(sbQuery.toString());// *****************
elements.clear();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
elements.add(table.getString("SDOCUMENT").trim());
elements.add(table.getString("ONUMBER").trim());
}
qex.updateInsertQuery(elements);
con.commit();
StringBuilder sbQuery1 = new StringBuilder(
"INSERT INTO tbl_item_order_msg (order_no,msg) VALUES");
System.out.println("COL -->"+table1.getNumRows()
+ " records to insert for tbl_item_order_msg");
// --- create query ---------------------------------
for (int i = 0; i < table1.getNumRows(); i++) {
// table.setRow(i);
sbQuery1.append("(?,?),");
}
sbQuery1.deleteCharAt(sbQuery1.length() - 1);
sbQuery1.append(";");
qex.setUpdateQuery(sbQuery1.toString());// *****************
elements.clear();
for (int i = 0; i < table1.getNumRows(); i++) {
table1.setRow(i);
elements.add(table1.getString("ORDER_NUMBER").trim());
elements.add(table1.getString("MESSAGE").trim());
}
qex.updateInsertQuery(elements);
con.commit();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
String sbQuery2 = "update tbl_items_header_t set status = 'X' where order_no = '" + table.getString("ORDER_NUMBER").trim() + "';";
int rcount = qex.runQuery(sbQuery2);
System.out.println("tbl_items_header_t Rows -->"+rcount + "Status Updated");
con.commit();
}
qex.closeConnections();
System.out.println("COL --> Cycle Finished....");
}
}
a possible reason to this situation is, you are hitting mysql's max open connections error, because you are not closing connections in method CallItem_ListCreate. it seems mysql default max connection count is 151. you are openning 15 connections per hour and after 10 hour you will hit that mentiooned error.
p.s. : you should try running your code in debug mode (or using tools like visualvm, jstack) and view thread dumps as #saurav commented.

Problems with ResultSet Nodes

Quick questions...
I'm trying to make a Dynamic JTree but I can't get to put every database I have into one single node for each one. This is my code so far:
jTree2 = new javax.swing.JTree();
try {
String DSN = "jdbc:mysql://localhost";
String user = "root";
String password = "";
conexion = DriverManager.getConnection(DSN, user, password);
}
catch(Exception e) {
System.out.println("ERROR");
}
try {
sentencia = conexion.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception e) {
System.out.println("ERROR2");
}
try {
String hi = "";
ResultSet rs1 = conexion.getMetaData().getCatalogs();
ResultSetMetaData rsmd = rs1.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++ ) {
hi = hi + rs1.getString(i) + ", ";
}
//for
String sb = hi.substring(0, hi.length()-2);
jTree2.setModel(new FileSystemModel(new File(sb)));
}
}
catch(Exception ae) {
System.out.println("ERROR3");
}
jScrollPane3.setViewportView(jTree2);
And the result I get is this:
Every database is splitted by a "," but I want them to be on a single node for each one. Any help?
This should do it for you:
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases", true);
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rs1.getString(i), true);
parent.add(node);
}
jTree2.setModel(new DefaultTreeModel(parent));
}

SQLDataException the syntax of the string representation of date/timeis incorrect while inserting date from a jtable model

I'm adding data to a table model which in turn i will pass to the database.amoung some of the fields am adding is a date object as shown by the code below.
String ref = cboReferenceNumber.getSelectedItem().toString();
if(!txtAction.getText().equals("") ){
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
java.util.Date date = new java.util.Date();
String action = txtAction.getText();
String hierachyOfControl = (String)cboHierachyOfControl.getSelectedItem();
String responsiblePerson = (String)cboName.getSelectedItem();
java.util.Date dueDate = dcDueDate.getDate();
java.sql.Date sqlDueDate = new java.sql.Date(dueDate.getTime());
String status = txtStatus.getText();
Object[] newRow = {action,hierachyOfControl,responsiblePerson,sqlDueDate,status};
if(dcDueDate.getDate().getTime() <= date.getTime()){
JOptionPane.showMessageDialog(Corrective.this, "Due date can not be less or equal to today's date");}
else{
model.addRow(newRow);
}
}else{
JOptionPane.showMessageDialog(Corrective.this, "Please enter action required for"+" "+ref);
}
i then use the code below to add the created model to a database but the date column complains of the error message on my question header.
String sql = "insert into CorrectiveAction(ReferenceNumber,Action,Hierachy"+
",ResponsiblePerson,DuteDate,Status)values(?,?,?,?,?,?)";
String reference = cboReferenceNumber.getSelectedItem().toString();
TableModel tm = jTable1.getModel();
try {
Connection con = DbConnection.dbConnection();
PreparedStatement pst = con.prepareStatement(sql);
for(int tableRow = 0; tableRow < tm.getRowCount(); tableRow++){
for(int col = 0; col < tm.getColumnCount(); col++){
Object val = tm.getValueAt(tableRow, col);
pst.setObject(col+1, val);
pst.setString(6, reference);
}
pst.addBatch();
}
pst.executeBatch();
pst.executeBatch();
JOptionPane.showMessageDialog(this, "Record successfully saved..!");
}
catch (SQLException | HeadlessException | ClassNotFoundException e){
Logger.getLogger(Corrective.class.getName()).log(Level.SEVERE, null, e);
}

Exhausted Resultset SQL Exception occur in if condition else condition

I written following code but it throws a "Resultset exhausted" error.
String dt = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat1.parse(dt);
DateTime dateTime = new DateTime(date);
Integer attributeID = 0;
String query1 ="select distinct M_attributesetinstance_id from M_storage where m_Product_id="+M_Product_ID;
attributeID = DB.getSQLValue(trxName, query1);
Timestamp MaufacuringDate = null;
String query = "select manufacturingdate from m_attributesetinstance where m_attributesetinstance_id="+attributeID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
if (MaufacuringDate!= null)
{
DateTime ManufacturingDate = new DateTime(MaufacuringDate);
try
{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate != null)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
DateTime dateTime1 = new DateTime(d1);
try
{
// c1.setTime(sdf.parse(dt));
// ReadableInstant date2;
Days d = Days.daysBetween(ManufacturingDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}
catch (Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
catch (ParseException e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else
{
continue;
}
}
catch(Exception e)
{
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.after(GuaranteeDate))
{
continue;
}
}
else
{
Timestamp GRNDate = null;
String query2 = "select distinct Movementdate from M_inout m "
+"inner join m_inoutline mil ON (m.M_Inout_ID = mil.M_Inout_id) where mil.M_Product_Id="+M_Product_ID;
try
{
pstmt = null;
rs = null;
pstmt = DB.prepareStatement(query2.toString(),null);
rs = pstmt.executeQuery();
while (rs.next())
{
GRNDate = rs.getTimestamp("Movementdate");
}
}
catch (Exception e)
{
e.printStackTrace();
}
// String dt1 = rs.getTimestamp("GuaranteeDate")+"";
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dateFormat1.parse(dt);
DateTime dateTime2 = new DateTime(date1);
DateTime GRDate = new DateTime(GRNDate);
try{
if((!"".equalsIgnoreCase(dt) || dt!=null) && percentage>=0 && GuaranteeDate!=null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c1 = Calendar.getInstance();
Date d1 = c1.getTime();
//DateTime dateTime1 = new DateTime(d1);
try {
// c1.setTime(sdf.parse(dt));
//ReadableInstant date2;
Days d = Days.daysBetween(GRDate, dateTime);
int days = d.getDays();
float calulateddays = (float)(days*(percentage/100.0f));
Integer roundeddays = Math.round(calulateddays);
c1.setTime(sdf.parse(dt));
c1.add(Calendar.DATE, -roundeddays); // number of days to add
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = dateFormat.parse(sdf.format(c1.getTime()));
MinGuaranteeDate = new java.sql.Timestamp(parsedDate.getTime());
}catch(Exception e){
MinGuaranteeDate = null;
e.printStackTrace();
}
} catch (ParseException e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
}
else {
continue;
}
}catch(Exception e) {
MinGuaranteeDate = null;
e.printStackTrace();
}
System.out.println("MinGuaranteeDate :"+MinGuaranteeDate);
System.out.println("TodayDate :"+GuaranteeDate);
if(MinGuaranteeDate==null || MinGuaranteeDate.before(GuaranteeDate)) {
continue;
}
}
}
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
}
}
} catch (Exception e) {
s_log.log(Level.SEVERE, sql, e);
} finally {
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
in above code gives the error on statement of bigdecimal
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
on this line
Kindly help me out
You need to find out whether MStorage calls rs.next() again, as you already used up all the results within another block:
while (rs.next())
{
MaufacuringDate = rs.getTimestamp("manufacturingdate");
}
I guess you have iterated over the record using Resultset object rs and now your rs cursor is at the end of the record/ or we can say it not pointing to any record.
Still your code below is using rs object which is exhausted and not pointing to any record/table row.
if (rs.getBigDecimal(11).signum() == 0) {
list.add(new MStorage(ctx, rs, trxName));
}
Possible solution :: Create a new statement, execute query and get the new ResultSet object whose cursor will be at the start of record (Note: Cursor at -1 (use .next())) and iterate over the record ad get the required result.
OR use some logic inside previous iteration over record and get the result there itself instead of iterating again .

Convert java.util.Date to java.sql.Date

I am trying to get date in my database that have format like this "dd/MM/yyyy" and compare them to get latest date..
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me. Any suggestions? It seems like this should be an easy feat to accomplish.
from String last_updatedArr[]'s array result :
12/11/2015
12/11/2015
12/11/2015
12/11/2015
12/11/2015
13/11/2015
Method:
public String latestDate(){
String last_updated=null;
try {
String last_updatedDb=null;
String query = "SELECT Last_updated FROM Mattress";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs= pst.executeQuery();
String last_updatedArr[]=new String[100];
while(rs.next()){
int i = 0;
last_updatedDb=rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i]=last_updatedDb;
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
for(int i =0;i<last_updatedArr.length;i++){
date1 = (java.sql.Date)sdf.parse(last_updatedArr[i]);
date2 = (java.sql.Date)sdf.parse("1/1/2010");
if(date1.after(date2)){
//Date1 is after Date2
last_updated= sdf.format(date1);
}
if(date1.before(date2)){
//Date1 is before Date2
last_updated= sdf.format(date2);
}
if(date1.equals(date2)){
//Date1 is equal Date2
last_updated= sdf.format(date1);
}
}
} catch (ParseException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return last_updated;
}
Your loop resets i on every iteration. Move the declaration of i in your while loop. Or just use a for loop. Like,
for(int i = 0; rs.next(); i++) {
last_updatedDb = rs.getString("Last_updated");
System.out.println(last_updatedDb);
last_updatedArr[i] = last_updatedDb;
}
or something like,
int i = 0;
while(rs.next()){
// int i = 0;
last_updatedArr[i] = rs.getString("Last_updated");
System.out.println(last_updatedArr[i]);
i++;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date date1,date2;
// reuse i from while loop...
for(i = 0; i < last_updatedArr.length; i++){

Categories