IDEMPIERE-5472 Unclosed resources (#1565)

* IDEMPIERE-5472 Unclosed resources

* IDEMPIERE-5472 Unclosed resources
This commit is contained in:
Elaine Tan 2022-11-17 17:35:15 +08:00 committed by GitHub
parent 4d9bc5340c
commit 2ff6378720
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 419 additions and 229 deletions

View File

@ -31,6 +31,7 @@ package org.adempiere.process;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.Timestamp; import java.sql.Timestamp;
@ -103,7 +104,7 @@ public class HouseKeeping extends SvrProcess{
String pathFile = houseKeeping.getBackupFolder(); String pathFile = houseKeeping.getBackupFolder();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = dateFormat.format(date); String dateString = dateFormat.format(date);
FileWriter file = new FileWriter(pathFile+File.separator+tableName+dateString+".xml"); FileWriter file = null;
StringBuilder sql = new StringBuilder("SELECT * FROM ").append(tableName); StringBuilder sql = new StringBuilder("SELECT * FROM ").append(tableName);
if (whereClause != null && whereClause.length() > 0) if (whereClause != null && whereClause.length() > 0)
sql.append(" WHERE ").append(whereClause); sql.append(" WHERE ").append(whereClause);
@ -112,6 +113,7 @@ public class HouseKeeping extends SvrProcess{
StringBuffer linexml = null; StringBuffer linexml = null;
try try
{ {
file = new FileWriter(pathFile+File.separator+tableName+dateString+".xml");
pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
rs = pstmt.executeQuery(); rs = pstmt.executeQuery();
while (rs.next()) { while (rs.next()) {
@ -121,7 +123,6 @@ public class HouseKeeping extends SvrProcess{
} }
if(linexml != null) if(linexml != null)
file.write(linexml.toString()); file.write(linexml.toString());
file.close();
} }
catch (Exception e) catch (Exception e)
{ {
@ -129,6 +130,15 @@ public class HouseKeeping extends SvrProcess{
} }
finally finally
{ {
if (file != null)
{
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DB.close(rs, pstmt); DB.close(rs, pstmt);
pstmt = null; pstmt = null;
rs=null; rs=null;

View File

@ -368,6 +368,7 @@ public class ImportAccount extends SvrProcess
.append("WHERE i.C_ElementValue_ID IS NOT NULL AND e.AD_Tree_ID IS NOT NULL") .append("WHERE i.C_ElementValue_ID IS NOT NULL AND e.AD_Tree_ID IS NOT NULL")
.append(" AND i.I_IsImported='Y' AND Processed='N' AND i.AD_Client_ID=").append(m_AD_Client_ID); .append(" AND i.I_IsImported='Y' AND Processed='N' AND i.AD_Client_ID=").append(m_AD_Client_ID);
int noParentUpdate = 0; int noParentUpdate = 0;
PreparedStatement updateStmt = null;
try try
{ {
pstmt = DB.prepareStatement(sql.toString(), get_TrxName()); pstmt = DB.prepareStatement(sql.toString(), get_TrxName());
@ -376,7 +377,7 @@ public class ImportAccount extends SvrProcess
String updateSQL = "UPDATE AD_TreeNode SET Parent_ID=?, SeqNo=? " String updateSQL = "UPDATE AD_TreeNode SET Parent_ID=?, SeqNo=? "
+ "WHERE AD_Tree_ID=? AND Node_ID=?"; + "WHERE AD_Tree_ID=? AND Node_ID=?";
//begin e-evolution vpj-cd 15 nov 2005 PostgreSQL //begin e-evolution vpj-cd 15 nov 2005 PostgreSQL
PreparedStatement updateStmt = DB.prepareStatement(updateSQL, ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE, get_TrxName()); updateStmt = DB.prepareStatement(updateSQL, ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE, get_TrxName());
//end //end
// //
while (rs.next()) while (rs.next())
@ -405,6 +406,8 @@ public class ImportAccount extends SvrProcess
} }
finally finally
{ {
DB.close(updateStmt);
updateStmt = null;
DB.close(rs, pstmt); DB.close(rs, pstmt);
rs = null; rs = null;
pstmt = null; pstmt = null;

View File

@ -434,10 +434,10 @@ public class ImportReportLine extends SvrProcess
.append(" WHERE I_ReportLine_ID=").append(I_ReportLine_ID).append(") ") .append(" WHERE I_ReportLine_ID=").append(I_ReportLine_ID).append(") ")
.append("WHERE PA_ReportSource_ID=").append(PA_ReportSource_ID).append(" ") .append("WHERE PA_ReportSource_ID=").append(PA_ReportSource_ID).append(" ")
.append(clientCheck); .append(clientCheck);
PreparedStatement pstmt_updateSource = DB.prepareStatement PreparedStatement pstmt_updateSource = null;
(sqlt.toString(), get_TrxName());
try try
{ {
pstmt_updateSource = DB.prepareStatement(sqlt.toString(), get_TrxName());
no = pstmt_updateSource.executeUpdate(); no = pstmt_updateSource.executeUpdate();
if (log.isLoggable(Level.FINEST)) log.finest("Update ReportSource = " + no + ", I_ReportLine_ID=" + I_ReportLine_ID + ", PA_ReportSource_ID=" + PA_ReportSource_ID); if (log.isLoggable(Level.FINEST)) log.finest("Update ReportSource = " + no + ", I_ReportLine_ID=" + I_ReportLine_ID + ", PA_ReportSource_ID=" + PA_ReportSource_ID);
noUpdateSource++; noUpdateSource++;
@ -487,6 +487,8 @@ public class ImportReportLine extends SvrProcess
pstmt_insertSource = null; pstmt_insertSource = null;
DB.close(pstmt_setImported); DB.close(pstmt_setImported);
pstmt_setImported = null; pstmt_setImported = null;
DB.close(pstmt_deleteSource);
pstmt_deleteSource = null;
} }
// Set Error to indicator to not imported // Set Error to indicator to not imported

View File

@ -205,6 +205,7 @@ public class InOutGenerate extends SvrProcess
} }
catch (Exception e) catch (Exception e)
{ {
DB.close(pstmt);
throw new AdempiereException(e); throw new AdempiereException(e);
} }
return generate(pstmt); return generate(pstmt);

View File

@ -206,6 +206,7 @@ public class InvoiceGenerate extends SvrProcess
} }
catch (Exception e) catch (Exception e)
{ {
DB.close(pstmt);
throw new AdempiereException(e); throw new AdempiereException(e);
} }
return generate(pstmt); return generate(pstmt);

View File

@ -175,23 +175,28 @@ public class RollUpCosts extends SvrProcess {
" JOIN PP_PRODUCT_BOMLINE bl ON b.PP_PRODUCT_BOM_ID = bl.PP_PRODUCT_BOM_ID" + " JOIN PP_PRODUCT_BOMLINE bl ON b.PP_PRODUCT_BOM_ID = bl.PP_PRODUCT_BOM_ID" +
" WHERE b.AD_Client_ID=" + getAD_Client_ID() +" AND b.IsActive='Y' AND bl.IsActive='Y' AND b.BOMType='A' AND b.BOMUse='A')"; " WHERE b.AD_Client_ID=" + getAD_Client_ID() +" AND b.IsActive='Y' AND bl.IsActive='Y' AND b.BOMType='A' AND b.BOMUse='A')";
Trx trx = Trx.get(get_TrxName(), false); Trx trx = Trx.get(get_TrxName(), false);
RowSet results = DB.getRowSet(sql); RowSet results = null;
while (results.next()) try {
{ results = DB.getRowSet(sql);
Savepoint savepoint = trx.setSavepoint(null); while (results.next())
int id= results.getInt(1);
String error = rollUpCosts(id);
if (!Util.isEmpty(error))
{ {
addLog(getAD_PInstance_ID(), null, null, "Rollup BOM Cost is not applicable for the product " + MProduct.get(getCtx(), id).getName() Savepoint savepoint = trx.setSavepoint(null);
+ ". Details: " + error, MProduct.Table_ID, product_id); int id= results.getInt(1);
trx.rollback(savepoint); String error = rollUpCosts(id);
} if (!Util.isEmpty(error))
else {
{ addLog(getAD_PInstance_ID(), null, null, "Rollup BOM Cost is not applicable for the product " + MProduct.get(getCtx(), id).getName()
trx.releaseSavepoint(savepoint); + ". Details: " + error, MProduct.Table_ID, product_id);
count++; trx.rollback(savepoint);
}
else
{
trx.releaseSavepoint(savepoint);
count++;
}
} }
} finally {
DB.close(results);
} }
} }
else //do it for all products else //do it for all products
@ -201,25 +206,30 @@ public class RollUpCosts extends SvrProcess {
" JOIN PP_PRODUCT_BOMLINE bl ON b.PP_PRODUCT_BOM_ID = bl.PP_PRODUCT_BOM_ID" + " JOIN PP_PRODUCT_BOMLINE bl ON b.PP_PRODUCT_BOM_ID = bl.PP_PRODUCT_BOM_ID" +
" WHERE b.AD_Client_ID=" + getAD_Client_ID() +" AND b.IsActive='Y' AND bl.IsActive='Y' AND b.BOMType='A' AND b.BOMUse='A')"; " WHERE b.AD_Client_ID=" + getAD_Client_ID() +" AND b.IsActive='Y' AND bl.IsActive='Y' AND b.BOMType='A' AND b.BOMUse='A')";
Trx trx = Trx.get(get_TrxName(), false); Trx trx = Trx.get(get_TrxName(), false);
RowSet results = DB.getRowSet(sql); RowSet results = null;
while (results.next()) try {
{ results = DB.getRowSet(sql);
Savepoint savepoint = trx.setSavepoint(null); while (results.next())
int id= results.getInt(1);
String error = rollUpCosts(id);
if (!Util.isEmpty(error))
{ {
addLog(getAD_PInstance_ID(), null, null, "Rollup BOM Cost is not applicable for the product " + MProduct.get(getCtx(), id).getName() Savepoint savepoint = trx.setSavepoint(null);
+ ". Details: " + error, MProduct.Table_ID, product_id); int id= results.getInt(1);
trx.rollback(savepoint); String error = rollUpCosts(id);
if (!Util.isEmpty(error))
{
addLog(getAD_PInstance_ID(), null, null, "Rollup BOM Cost is not applicable for the product " + MProduct.get(getCtx(), id).getName()
+ ". Details: " + error, MProduct.Table_ID, product_id);
trx.rollback(savepoint);
}
else
{
trx.releaseSavepoint(savepoint);
count++;
}
} }
else } finally {
{ DB.close(results);
trx.releaseSavepoint(savepoint); }
count++; }
}
}
}
return count + " Product Cost Updated."; return count + " Product Cost Updated.";
} }

View File

@ -115,8 +115,13 @@ public class TableCreateColumns extends SvrProcess
if (DB.isPostgreSQL()) if (DB.isPostgreSQL())
tableName = tableName.toLowerCase(); tableName = tableName.toLowerCase();
// end globalqss 2005-10-24 // end globalqss 2005-10-24
ResultSet rs = md.getColumns(catalog, schema, tableName, null); ResultSet rs = null;
addTableColumn(rs, table); try {
rs = md.getColumns(catalog, schema, tableName, null);
addTableColumn(rs, table);
} finally {
DB.close(rs);
}
} }
StringBuilder msgreturn = new StringBuilder("#").append(m_count); StringBuilder msgreturn = new StringBuilder("#").append(m_count);
return msgreturn.toString(); return msgreturn.toString();
@ -191,8 +196,12 @@ public class TableCreateColumns extends SvrProcess
if (DB.isPostgreSQL()) if (DB.isPostgreSQL())
tableName = tableName.toLowerCase(); tableName = tableName.toLowerCase();
// end globalqss 2005-10-24 // end globalqss 2005-10-24
rsC = md.getColumns(catalog, schema, tableName, null); try {
addTableColumn(rsC, table); rsC = md.getColumns(catalog, schema, tableName, null);
addTableColumn(rsC, table);
} finally {
DB.close(rsC);
}
} }
} catch (Exception e) { } catch (Exception e) {
throw e; throw e;

View File

@ -476,14 +476,15 @@ public class MInfoWindow extends X_AD_InfoWindow implements ImmutablePOSupport
// try run sql // try run sql
PreparedStatement pstmt = null; PreparedStatement pstmt = null;
ResultSet rs = null;
try { try {
pstmt = DB.prepareStatement(builder.toString(), get_TrxName()); pstmt = DB.prepareStatement(builder.toString(), get_TrxName());
pstmt.executeQuery(); rs = pstmt.executeQuery();
}catch (Exception ex){ }catch (Exception ex){
log.log(Level.WARNING, ex.getMessage()); log.log(Level.WARNING, ex.getMessage());
throw new AdempiereException(ex); throw new AdempiereException(ex);
} finally { } finally {
DB.close(pstmt); DB.close(rs, pstmt);
} }
// valid state // valid state

View File

@ -1218,9 +1218,14 @@ public final class DB
{ {
// Bugfix Gunther Hoppe, 02.09.2005, vpj-cd e-evolution // Bugfix Gunther Hoppe, 02.09.2005, vpj-cd e-evolution
CStatementVO info = new CStatementVO (RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, DB.getDatabase().convertStatement(sql)); CStatementVO info = new CStatementVO (RowSet.TYPE_SCROLL_INSENSITIVE, RowSet.CONCUR_READ_ONLY, DB.getDatabase().convertStatement(sql));
CPreparedStatement stmt = ProxyFactory.newCPreparedStatement(info); CPreparedStatement stmt = null;
RowSet retValue = stmt.getRowSet(); RowSet retValue = null;
close(stmt); try {
stmt = ProxyFactory.newCPreparedStatement(info);
retValue = stmt.getRowSet();
} finally {
close(stmt);
}
return retValue; return retValue;
} // getRowSet } // getRowSet

View File

@ -20,6 +20,7 @@ package org.adempiere.pipo2;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -405,8 +406,6 @@ public class PackRollProcess extends SvrProcess {
target.write(data); target.write(data);
byteCount++; byteCount++;
} }
source.close();
target.close();
System.out.println("Successfully copied " + byteCount + " bytes."); System.out.println("Successfully copied " + byteCount + " bytes.");
} catch (Exception e) { } catch (Exception e) {
@ -415,6 +414,21 @@ public class PackRollProcess extends SvrProcess {
System.out.println(e.toString()); System.out.println(e.toString());
success = -1; success = -1;
} finally {
if (source != null) {
try {
source.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (target != null) {
try {
target.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
return success; return success;
} }

View File

@ -103,9 +103,10 @@ public class AdempiereActivator extends AbstractActivator {
localSession.saveEx(); localSession.saveEx();
} }
FileOutputStream zipstream = null; FileOutputStream zipstream = null;
InputStream stream = null;
try { try {
// copy the resource to a temporary file to process it with 2pack // copy the resource to a temporary file to process it with 2pack
InputStream stream = context.getBundle().getEntry("/META-INF/2Pack.zip").openStream(); stream = context.getBundle().getEntry("/META-INF/2Pack.zip").openStream();
File zipfile = File.createTempFile(getName(), ".zip"); File zipfile = File.createTempFile(getName(), ".zip");
zipstream = new FileOutputStream(zipfile); zipstream = new FileOutputStream(zipfile);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -124,6 +125,11 @@ public class AdempiereActivator extends AbstractActivator {
zipstream.close(); zipstream.close();
} catch (Exception e2) {} } catch (Exception e2) {}
} }
if (stream != null) {
try {
stream.close();
} catch (Exception e2) {}
}
if (localSession != null) if (localSession != null)
localSession.logout(); localSession.logout();
} }

View File

@ -225,9 +225,10 @@ public class Incremental2PackActivator extends AbstractActivator {
String suffix = "_"+path.substring(path.lastIndexOf("2Pack_")); String suffix = "_"+path.substring(path.lastIndexOf("2Pack_"));
logger.log(Level.WARNING, "Installing " + getName() + " " + path + " ..."); logger.log(Level.WARNING, "Installing " + getName() + " " + path + " ...");
FileOutputStream zipstream = null; FileOutputStream zipstream = null;
InputStream stream = null;
try { try {
// copy the resource to a temporary file to process it with 2pack // copy the resource to a temporary file to process it with 2pack
InputStream stream = packout.openStream(); stream = packout.openStream();
File zipfile = File.createTempFile(getName()+"_", suffix); File zipfile = File.createTempFile(getName()+"_", suffix);
zipstream = new FileOutputStream(zipfile); zipstream = new FileOutputStream(zipfile);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -247,6 +248,11 @@ public class Incremental2PackActivator extends AbstractActivator {
zipstream.close(); zipstream.close();
} catch (Exception e2) {} } catch (Exception e2) {}
} }
if (stream != null) {
try {
stream.close();
} catch (Exception e2) {}
}
if (localSession != null) if (localSession != null)
localSession.logout(); localSession.logout();
} }

View File

@ -194,9 +194,10 @@ public class Version2PackActivator extends AbstractActivator{
String suffix = "_"+path.substring(path.lastIndexOf("2Pack_")); String suffix = "_"+path.substring(path.lastIndexOf("2Pack_"));
logger.log(Level.WARNING, "Installing " + getName() + " " + path + " ..."); logger.log(Level.WARNING, "Installing " + getName() + " " + path + " ...");
FileOutputStream zipstream = null; FileOutputStream zipstream = null;
InputStream stream = null;
try { try {
// copy the resource to a temporary file to process it with 2pack // copy the resource to a temporary file to process it with 2pack
InputStream stream = packout.openStream(); stream = packout.openStream();
File zipfile = File.createTempFile(getName()+"_", suffix); File zipfile = File.createTempFile(getName()+"_", suffix);
zipstream = new FileOutputStream(zipfile); zipstream = new FileOutputStream(zipfile);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -216,6 +217,11 @@ public class Version2PackActivator extends AbstractActivator{
zipstream.close(); zipstream.close();
} catch (Exception e2) {} } catch (Exception e2) {}
} }
if (stream != null) {
try {
stream.close();
} catch (Exception e2) {}
}
} }
logger.log(Level.WARNING, getName() + " " + packout.getPath() + " installed"); logger.log(Level.WARNING, getName() + " " + packout.getPath() + " installed");
} }

View File

@ -114,7 +114,7 @@ public class EMailProcessor
// Cleanup // Cleanup
try try
{ {
if (m_store.isConnected()) if (m_store != null && m_store.isConnected())
m_store.close(); m_store.close();
} }
catch (Exception e) catch (Exception e)
@ -181,92 +181,132 @@ public class EMailProcessor
protected int processInBox() throws Exception protected int processInBox() throws Exception
{ {
// Folder // Folder
Folder folder; Folder folder = null;
folder = m_store.getDefaultFolder(); Folder inbox = null;
if (folder == null) Folder requestFolder = null;
throw new IllegalStateException("No default folder"); Folder workflowFolder = null;
// Open Inbox Folder errorFolder = null;
Folder inbox = folder.getFolder("INBOX");
if (!inbox.exists())
throw new IllegalStateException("No Inbox");
inbox.open(Folder.READ_WRITE);
if (log.isLoggable(Level.FINE)) log.fine("processInBox - " + inbox.getName()
+ "; Messages Total=" + inbox.getMessageCount()
+ "; New=" + inbox.getNewMessageCount());
// Open Request
Folder requestFolder = folder.getFolder("CRequest");
if (!requestFolder.exists() && !requestFolder.create(Folder.HOLDS_MESSAGES))
throw new IllegalStateException("Cannot create Request Folder");
requestFolder.open(Folder.READ_WRITE);
// Open Workflow
Folder workflowFolder = folder.getFolder("CWorkflow");
if (!workflowFolder.exists() && !workflowFolder.create(Folder.HOLDS_MESSAGES))
throw new IllegalStateException("Cannot create Workflow Folder");
workflowFolder.open(Folder.READ_WRITE);
// Open Error
Folder errorFolder = folder.getFolder("AdempiereError");
if (!errorFolder.exists() && !errorFolder.create(Folder.HOLDS_MESSAGES))
throw new IllegalStateException("Cannot create Error Folder");
errorFolder.open(Folder.READ_WRITE);
// Messages
Message[] messages = inbox.getMessages();
/**
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
inbox.fetch(messages, fp);
**/
//
int noProcessed = 0; int noProcessed = 0;
int noError = 0; try {
for (int i = 0; i < messages.length; i++) folder = m_store.getDefaultFolder();
// for (int i = messages.length-1; i >= 0; i--) // newest first if (folder == null)
{ throw new IllegalStateException("No default folder");
Message msg = messages[i]; // Open Inbox
int result = processMessage (msg); inbox = folder.getFolder("INBOX");
if (result == REQUEST) if (!inbox.exists())
{ throw new IllegalStateException("No Inbox");
msg.setFlag(Flags.Flag.SEEN, true); inbox.open(Folder.READ_WRITE);
msg.setFlag(Flags.Flag.ANSWERED, true); if (log.isLoggable(Level.FINE)) log.fine("processInBox - " + inbox.getName()
// Copy to processed + "; Messages Total=" + inbox.getMessageCount()
requestFolder.appendMessages(new Message[]{msg}); + "; New=" + inbox.getNewMessageCount());
}
else if (result == WORKFLOW)
{
msg.setFlag(Flags.Flag.SEEN, true);
msg.setFlag(Flags.Flag.ANSWERED, true);
// Copy to processed
workflowFolder.appendMessages(new Message[]{msg});
}
else if (result == DELIVERY)
{
msg.setFlag(Flags.Flag.SEEN, true);
msg.setFlag(Flags.Flag.ANSWERED, true);
}
else // error
{
errorFolder.appendMessages(new Message[]{msg});
noError++;
}
// Delete in InBox
// msg.setFlag(Flags.Flag.DELETED, true);
// Message[] deleted = inbox.expunge();
//
noProcessed++;
}
if (log.isLoggable(Level.INFO)) log.info("processInBox - Total=" + noProcessed + " - Errors=" + noError); // Open Request
// Fini requestFolder = folder.getFolder("CRequest");
errorFolder.close(false); if (!requestFolder.exists() && !requestFolder.create(Folder.HOLDS_MESSAGES))
requestFolder.close(false); throw new IllegalStateException("Cannot create Request Folder");
workflowFolder.close(false); requestFolder.open(Folder.READ_WRITE);
//
inbox.close(true); // Open Workflow
workflowFolder = folder.getFolder("CWorkflow");
if (!workflowFolder.exists() && !workflowFolder.create(Folder.HOLDS_MESSAGES))
throw new IllegalStateException("Cannot create Workflow Folder");
workflowFolder.open(Folder.READ_WRITE);
// Open Error
errorFolder = folder.getFolder("AdempiereError");
if (!errorFolder.exists() && !errorFolder.create(Folder.HOLDS_MESSAGES))
throw new IllegalStateException("Cannot create Error Folder");
errorFolder.open(Folder.READ_WRITE);
// Messages
Message[] messages = inbox.getMessages();
/**
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
inbox.fetch(messages, fp);
**/
//
int noError = 0;
for (int i = 0; i < messages.length; i++)
// for (int i = messages.length-1; i >= 0; i--) // newest first
{
Message msg = messages[i];
int result = processMessage (msg);
if (result == REQUEST)
{
msg.setFlag(Flags.Flag.SEEN, true);
msg.setFlag(Flags.Flag.ANSWERED, true);
// Copy to processed
requestFolder.appendMessages(new Message[]{msg});
}
else if (result == WORKFLOW)
{
msg.setFlag(Flags.Flag.SEEN, true);
msg.setFlag(Flags.Flag.ANSWERED, true);
// Copy to processed
workflowFolder.appendMessages(new Message[]{msg});
}
else if (result == DELIVERY)
{
msg.setFlag(Flags.Flag.SEEN, true);
msg.setFlag(Flags.Flag.ANSWERED, true);
}
else // error
{
errorFolder.appendMessages(new Message[]{msg});
noError++;
}
// Delete in InBox
// msg.setFlag(Flags.Flag.DELETED, true);
// Message[] deleted = inbox.expunge();
//
noProcessed++;
}
if (log.isLoggable(Level.INFO)) log.info("processInBox - Total=" + noProcessed + " - Errors=" + noError);
} finally {
if (errorFolder != null && errorFolder.isOpen()) {
try {
errorFolder.close(false);
} catch (Exception e) {
e.printStackTrace();
}
}
if (requestFolder != null && requestFolder.isOpen()) {
try {
requestFolder.close(false);
} catch (Exception e) {
e.printStackTrace();
}
}
if (workflowFolder != null && workflowFolder.isOpen()) {
try {
workflowFolder.close(false);
} catch (Exception e) {
e.printStackTrace();
}
}
if (inbox != null && inbox.isOpen()) {
try {
inbox.close(true);
} catch (Exception e) {
e.printStackTrace();
}
}
if (folder != null && folder.isOpen()) {
try {
folder.close(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return noProcessed; return noProcessed;
} // processInBox } // processInBox
@ -462,12 +502,16 @@ public class EMailProcessor
if (content instanceof InputStream) if (content instanceof InputStream)
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream is = (InputStream)content; InputStream is = null;
int c; try {
while ((c = is.read()) != -1) is = (InputStream)content;
sb.append((char)c); int c;
while ((c = is.read()) != -1)
is.close(); sb.append((char)c);
} finally {
if (is != null)
is.close();
}
deliveryMessage = sb.toString().trim(); deliveryMessage = sb.toString().trim();
} }
else else

View File

@ -571,6 +571,7 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
} }
if (pdfList.size() > 1) { if (pdfList.size() > 1) {
List<PdfReader> pdfReaders = new ArrayList<PdfReader>();
try { try {
File outFile = File.createTempFile("PrintShipments", ".pdf"); File outFile = File.createTempFile("PrintShipments", ".pdf");
Document document = null; Document document = null;
@ -579,6 +580,7 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
{ {
String fileName = f.getAbsolutePath(); String fileName = f.getAbsolutePath();
PdfReader reader = new PdfReader(fileName); PdfReader reader = new PdfReader(fileName);
pdfReaders.add(reader);
reader.consolidateNamedDestinations(); reader.consolidateNamedDestinations();
if (document == null) if (document == null)
{ {
@ -602,6 +604,11 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
} catch (Exception e) { } catch (Exception e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e); log.log(Level.SEVERE, e.getLocalizedMessage(), e);
} finally { } finally {
for (PdfReader reader : pdfReaders)
{
if (reader != null)
reader.close();
}
//do no harm calling this twice //do no harm calling this twice
hideBusyDialog(); hideBusyDialog();
} }
@ -656,6 +663,7 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
} }
if (pdfList.size() > 1) { if (pdfList.size() > 1) {
List<PdfReader> pdfReaders = new ArrayList<PdfReader>();
try { try {
File outFile = File.createTempFile("PrintInvoices", ".pdf"); File outFile = File.createTempFile("PrintInvoices", ".pdf");
Document document = null; Document document = null;
@ -663,6 +671,7 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
for (File f : pdfList) for (File f : pdfList)
{ {
PdfReader reader = new PdfReader(f.getAbsolutePath()); PdfReader reader = new PdfReader(f.getAbsolutePath());
pdfReaders.add(reader);
if (document == null) if (document == null)
{ {
document = new Document(reader.getPageSizeWithRotation(1)); document = new Document(reader.getPageSizeWithRotation(1));
@ -685,6 +694,11 @@ public class ProcessDialog extends AbstractProcessDialog implements EventListene
} catch (Exception e) { } catch (Exception e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e); log.log(Level.SEVERE, e.getLocalizedMessage(), e);
} finally { } finally {
for (PdfReader reader : pdfReaders)
{
if (reader != null)
reader.close();
}
//do no harm calling this twice //do no harm calling this twice
hideBusyDialog(); hideBusyDialog();
} }

View File

@ -756,9 +756,10 @@ public class WArchiveViewer extends Archive implements IFormController, EventLis
descriptionField.setText(ar.getDescription()); descriptionField.setText(ar.getDescription());
helpField.setText(ar.getHelp()); helpField.setText(ar.getHelp());
InputStream in = null;
try try
{ {
InputStream in = ar.getInputStream(); in = ar.getInputStream();
//pdfViewer.setScale(reportField.isSelected() ? 50 : 75); //pdfViewer.setScale(reportField.isSelected() ? 50 : 75);
if (in != null) if (in != null)
reportViewer(ar.getName(), ar.getBinaryData());//pdfViewer.loadPDF(in); reportViewer(ar.getName(), ar.getBinaryData());//pdfViewer.loadPDF(in);
@ -770,6 +771,17 @@ public class WArchiveViewer extends Archive implements IFormController, EventLis
log.log(Level.SEVERE, "pdf", e); log.log(Level.SEVERE, "pdf", e);
iframe.getChildren().clear();//pdfViewer.clearDocument(); iframe.getChildren().clear();//pdfViewer.clearDocument();
} }
finally
{
if (in != null)
{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} // updateVDisplay } // updateVDisplay
/** /**

View File

@ -170,13 +170,19 @@ public class WFilenameEditor extends WEditor
if (file.inMemory()) { if (file.inMemory()) {
bytes = file.getByteData(); bytes = file.getByteData();
} else { } else {
InputStream is = file.getStreamData(); InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {
byte[] buf = new byte[ 1000 ]; is = file.getStreamData();
int byteread = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (( byteread=is.read(buf) )!=-1) byte[] buf = new byte[ 1000 ];
baos.write(buf,0,byteread); int byteread = 0;
bytes = baos.toByteArray(); while (( byteread=is.read(buf) )!=-1)
baos.write(buf,0,byteread);
bytes = baos.toByteArray();
} finally {
if (is != null)
is.close();
}
} }
fos.write(bytes); fos.write(bytes);

View File

@ -758,21 +758,26 @@ public class WAttachment extends Window implements EventListener<Event>
private byte[] getMediaData(Media media) { private byte[] getMediaData(Media media) {
byte[] bytes = null; byte[] bytes = null;
try{ try {
if (media.inMemory()) if (media.inMemory())
bytes = media.isBinary() ? media.getByteData() : media.getStringData().getBytes(getCharset(media.getContentType())); bytes = media.isBinary() ? media.getByteData() : media.getStringData().getBytes(getCharset(media.getContentType()));
else { else {
InputStream is = media.getStreamData(); InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {
byte[] buf = new byte[ 1000 ]; is = media.getStreamData();
int byteread = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1000];
int byteread = 0;
while (( byteread=is.read(buf) )!=-1) while ((byteread = is.read(buf)) != -1)
baos.write(buf,0,byteread); baos.write(buf, 0, byteread);
bytes = baos.toByteArray();
bytes = baos.toByteArray(); } finally {
} if (is != null)
is.close();
}
}
} catch (IOException e) { } catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e); log.log(Level.SEVERE, e.getLocalizedMessage(), e);
throw new IllegalStateException(e.getLocalizedMessage()); throw new IllegalStateException(e.getLocalizedMessage());

View File

@ -165,9 +165,10 @@ public class HTMLExtension implements IHTMLExtension {
if (urlFile != null) { if (urlFile != null) {
FileOutputStream cssStream = null; FileOutputStream cssStream = null;
File cssFile = null; File cssFile = null;
InputStream stream = null;
try { try {
// copy the resource to a temporary file to process it with 2pack // copy the resource to a temporary file to process it with 2pack
InputStream stream = urlFile.openStream(); stream = urlFile.openStream();
cssFile = File.createTempFile("report", ".css"); cssFile = File.createTempFile("report", ".css");
cssStream = new FileOutputStream(cssFile); cssStream = new FileOutputStream(cssFile);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
@ -183,6 +184,13 @@ public class HTMLExtension implements IHTMLExtension {
cssStream.close(); cssStream.close();
} catch (Exception e2) {} } catch (Exception e2) {}
} }
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
return cssFile.getAbsolutePath(); return cssFile.getAbsolutePath();
} else { } else {

View File

@ -650,16 +650,21 @@ public class WEMailDialog extends Window implements EventListener<Event>, ValueC
if (media.inMemory()) { if (media.inMemory()) {
bytes = media.isBinary() ? media.getByteData() : media.getStringData().getBytes(getCharset(media.getContentType())); bytes = media.isBinary() ? media.getByteData() : media.getStringData().getBytes(getCharset(media.getContentType()));
} else { } else {
InputStream is = null;
try {
is = media.getStreamData();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[ 1000 ];
int byteread = 0;
InputStream is = media.getStreamData(); while (( byteread=is.read(buf) )!=-1)
ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(buf,0,byteread);
byte[] buf = new byte[ 1000 ];
int byteread = 0;
while (( byteread=is.read(buf) )!=-1) bytes = baos.toByteArray();
baos.write(buf,0,byteread); } finally {
if (is != null)
bytes = baos.toByteArray(); is.close();
}
} }
} catch (IOException e) { } catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e); log.log(Level.SEVERE, e.getLocalizedMessage(), e);

View File

@ -432,21 +432,27 @@ public class ZkJRViewer extends Window implements EventListener<Event>, ITabOnCl
prefix += "_".repeat(3-prefix.length()); prefix += "_".repeat(3-prefix.length());
if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix);
File file = File.createTempFile(prefix, ".xls", new File(path)); File file = File.createTempFile(prefix, ".xls", new File(path));
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// coding For Excel: // coding For Excel:
JRXlsExporter exporterXLS = new JRXlsExporter(); JRXlsExporter exporterXLS = new JRXlsExporter();
SimpleXlsReportConfiguration xlsConfig = new SimpleXlsReportConfiguration(); SimpleXlsReportConfiguration xlsConfig = new SimpleXlsReportConfiguration();
xlsConfig.setOnePagePerSheet(false); xlsConfig.setOnePagePerSheet(false);
if (!isList){ if (!isList){
jasperPrintList = new ArrayList<>(); jasperPrintList = new ArrayList<>();
jasperPrintList.add(jasperPrint); jasperPrintList.add(jasperPrint);
}
exporterXLS.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporterXLS.setExporterOutput(new SimpleOutputStreamExporterOutput(fos));
exporterXLS.setConfiguration(xlsConfig);
exporterXLS.exportReport();
} finally {
if (fos != null)
fos.close();
} }
exporterXLS.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporterXLS.setExporterOutput(new SimpleOutputStreamExporterOutput(fos));
exporterXLS.setConfiguration(xlsConfig);
exporterXLS.exportReport();
return new AMedia(m_title+"."+EXCEL_FILE_EXT, EXCEL_FILE_EXT, EXCEL_MIME_TYPE, file, true); return new AMedia(m_title+"."+EXCEL_FILE_EXT, EXCEL_FILE_EXT, EXCEL_MIME_TYPE, file, true);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof RuntimeException) if (e instanceof RuntimeException)
@ -468,21 +474,27 @@ public class ZkJRViewer extends Window implements EventListener<Event>, ITabOnCl
prefix += "_".repeat(3-prefix.length()); prefix += "_".repeat(3-prefix.length());
if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix);
File file = File.createTempFile(prefix, "."+EXCEL_XML_FILE_EXT, new File(path)); File file = File.createTempFile(prefix, "."+EXCEL_XML_FILE_EXT, new File(path));
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// coding For Excel: // coding For Excel:
JRXlsxExporter exporterXLSX = new JRXlsxExporter(); JRXlsxExporter exporterXLSX = new JRXlsxExporter();
SimpleXlsxReportConfiguration xlsxConfig = new SimpleXlsxReportConfiguration(); SimpleXlsxReportConfiguration xlsxConfig = new SimpleXlsxReportConfiguration();
xlsxConfig.setOnePagePerSheet(false); xlsxConfig.setOnePagePerSheet(false);
if (!isList){ if (!isList){
jasperPrintList = new ArrayList<>(); jasperPrintList = new ArrayList<>();
jasperPrintList.add(jasperPrint); jasperPrintList.add(jasperPrint);
}
exporterXLSX.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporterXLSX.setExporterOutput(new SimpleOutputStreamExporterOutput(fos));
exporterXLSX.setConfiguration(xlsxConfig);
exporterXLSX.exportReport();
} finally {
if (fos != null)
fos.close();
} }
exporterXLSX.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporterXLSX.setExporterOutput(new SimpleOutputStreamExporterOutput(fos));
exporterXLSX.setConfiguration(xlsxConfig);
exporterXLSX.exportReport();
return new AMedia(m_title+"."+EXCEL_XML_FILE_EXT, EXCEL_XML_FILE_EXT, EXCEL_XML_MIME_TYPE, file, true); return new AMedia(m_title+"."+EXCEL_XML_FILE_EXT, EXCEL_XML_FILE_EXT, EXCEL_XML_MIME_TYPE, file, true);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof RuntimeException) if (e instanceof RuntimeException)
@ -504,16 +516,21 @@ public class ZkJRViewer extends Window implements EventListener<Event>, ITabOnCl
prefix += "_".repeat(3-prefix.length()); prefix += "_".repeat(3-prefix.length());
if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix);
File file = File.createTempFile(prefix, "."+CSV_FILE_EXT, new File(path)); File file = File.createTempFile(prefix, "."+CSV_FILE_EXT, new File(path));
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = null;
JRCsvExporter exporter= new JRCsvExporter(); try {
if (!isList){ fos = new FileOutputStream(file);
jasperPrintList = new ArrayList<>(); JRCsvExporter exporter= new JRCsvExporter();
jasperPrintList.add(jasperPrint); if (!isList){
jasperPrintList = new ArrayList<>();
jasperPrintList.add(jasperPrint);
}
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fos));
exporter.exportReport();
} finally {
if (fos != null)
fos.close();
} }
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fos));
exporter.exportReport();
return new AMedia(m_title+"."+CSV_FILE_EXT, CSV_FILE_EXT, CSV_MIME_TYPE, file, false); return new AMedia(m_title+"."+CSV_FILE_EXT, CSV_FILE_EXT, CSV_MIME_TYPE, file, false);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof RuntimeException) if (e instanceof RuntimeException)
@ -535,19 +552,24 @@ public class ZkJRViewer extends Window implements EventListener<Event>, ITabOnCl
prefix += "_".repeat(3-prefix.length()); prefix += "_".repeat(3-prefix.length());
if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix); if (log.isLoggable(Level.FINE)) log.log(Level.FINE, "Path="+path + " Prefix="+prefix);
File file = File.createTempFile(prefix, "."+SSV_FILE_EXT, new File(path)); File file = File.createTempFile(prefix, "."+SSV_FILE_EXT, new File(path));
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = null;
JRCsvExporter exporter= new JRCsvExporter(); try {
SimpleCsvExporterConfiguration csvConfig = new SimpleCsvExporterConfiguration(); fos = new FileOutputStream(file);
csvConfig.setFieldDelimiter(";"); JRCsvExporter exporter= new JRCsvExporter();
if (!isList){ SimpleCsvExporterConfiguration csvConfig = new SimpleCsvExporterConfiguration();
jasperPrintList = new ArrayList<>(); csvConfig.setFieldDelimiter(";");
jasperPrintList.add(jasperPrint); if (!isList){
jasperPrintList = new ArrayList<>();
jasperPrintList.add(jasperPrint);
}
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fos));
exporter.setConfiguration(csvConfig);
exporter.exportReport();
} finally {
if (fos != null)
fos.close();
} }
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fos));
exporter.setConfiguration(csvConfig);
exporter.exportReport();
return new AMedia(m_title+"."+SSV_FILE_EXT, SSV_FILE_EXT, CSV_MIME_TYPE, file, false); return new AMedia(m_title+"."+SSV_FILE_EXT, SSV_FILE_EXT, CSV_MIME_TYPE, file, false);
} catch (Exception e) { } catch (Exception e) {
if (e instanceof RuntimeException) if (e instanceof RuntimeException)