Warning: You did not close a PDF Document looping when renderImageWithDPI - java

i want to split pdf to image file by page, but i got Warning: You did not close a PDF Document looping when renderImageWithDPI
Still have warning
UPDATE CODE :
public void splitImage(PDDocument document, File checkFile, File theDirSplit, String fileExtension, File theDir, File watermarkDirectory, int numberOfPages)
throws InvalidPasswordException, IOException {
String fileName = checkFile.getName().replace(".pdf", "");
int dpi = 300;
if (theDirSplit.list().length < numberOfPages)
{
for (int i = 0; i < numberOfPages; ++i)
{
if (i == numberOfPages)
break;
if (theDirSplit.list().length != numberOfPages)
{
File outPutFile = new File(theDirSplit + Constan.simbol + fileName + "_" + (i + 1) + "." + fileExtension);
document = PDDocument.load(checkFile);
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage bImage = pdfRenderer.renderImageWithDPI(i, dpi, ImageType.RGB);
ImageIO.write(bImage, fileExtension, outPutFile);
}
// splitService.watermark(outPutFile, (i + 1), watermarkDirectory, "pdf");
}
document.close();
//System.out.println("Converted Images are saved at -> " + theDirSplit.getAbsolutePath());
}
System.out.println("Done Partial SPlit");
/*
* int i = 1; while (iterator.hasNext()) { PDDocument pd = iterator.next();
* pd.save(theDirSplit + Constan.simbol + i++ + ".pdf"); }
* System.out.println("Multiple PDF’s created");
*/
}
error looping
total warning same with number of pages...
i already try to close but not work, this process make my server java.lang.OutOfMemoryError: Java heap space
update :
else if ("pdf".equalsIgnoreCase(typeFile)) {
System.out.println(
"target file " + downloadPath + R_OBJECT_ID + Constan.simbol + R_OBJECT_ID + "." + typeFile);
//get jumlah halaman
try(PDDocument document = PDDocument.load(checkFile)){
File theDirSplit = new File(theDir.getAbsolutePath() + Constan.simbol + "splitImage");
createFolder(theDirSplit);
String fileExtension = "jpeg";
File watermarkDirectory = new File(theDir.getAbsolutePath() + Constan.simbol + "watermarkImage");
createFolder(watermarkDirectory);
// split 2 page image
if (theDirSplit.list().length <= document.getNumberOfPages()) {
try {
splitImage(document,checkFile, theDirSplit, fileExtension, theDir, watermarkDirectory, document.getNumberOfPages()/2);
} catch (IOException e) {
System.out.println("ERROR SPLIT PDF " + e.getMessage());
e.printStackTrace();
}
}
res.setTotalPages(document.getNumberOfPages());
document.close();
return new ResponseEntity<>(res, HttpStatus.OK);
}
} else {
res.setTotalPages(1);
return new ResponseEntity<>(res, HttpStatus.OK);
}
this is code to call split method....

This is somewhat lost from the question, but the cause was failing to close the documents generated by splitter.split().

Related

Issues with enclosing PDDoucment

I have implemented a program that will print data into a pdf however I am facing this issue
java.io.IOException: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
I know there have been similar issues posted but I could not find the solution to my problem from them. What I am doing is that I initialized two documents one of them being the main document(doc) the other for the rest of the pages and then I add to the main one(activeDocument), the service calls three different functions to add a new page one for the first page one for any pages in between, one for before the last and finally the last page.a Here is my code most of the logic can be ignored its mainly just the things relating to PDDocuments since thats where the issue lies
private InputStream generateCardsPDF(String cardNumber,
String generationDate,
StatementSummaryResTypeStatementSummaryResBody resBody,
String pdf) throws IOException, ParseException {
List<StatementSummaryResTypeStatementSummaryResBodyTransactionsTransaction> transactionList = resBody.getTransactions().getTransaction().stream().limit(50).collect(Collectors.toList());
PDDocument doc = new PDDocument().load(getClass().getClassLoader().getResourceAsStream(pdf));
PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
PDPage page = docCatalog.getPages().get(0);
try {
String fullName = resBody.getStatementHeader().getAddress().getTitle() +
" " + resBody.getStatementHeader().getAddress().getFirstName() + " ";
String fullAddress = "";
if (resBody.getStatementHeader().getAddress().getMiddleName() != null) {
fullName = fullName + resBody.getStatementHeader().getAddress().getMiddleName() + " ";
}
fullName = fullName + resBody.getStatementHeader().getAddress().getLastName();
String countryAddress = resBody.getStatementHeader().getAddress().getCity() != null ? resBody.getStatementHeader().getAddress().getCity() : "";
countryAddress += resBody.getStatementHeader().getAddress().getCountry() != null &&
countryAddress.length() > 0 ? ", " + resBody.getStatementHeader().getAddress().getCountry() : "";
countryAddress += resBody.getStatementHeader().getAddress().getCountry() != null &&
countryAddress.length() == 0 ? resBody.getStatementHeader().getAddress().getCountry() : "";
fullAddress += resBody.getStatementHeader().getAddress().getAddress1() + ONE_LINE;
fullAddress += resBody.getStatementHeader().getAddress().getAddress2() != null ? resBody.getStatementHeader().getAddress().getAddress2() + ONE_LINE : "";
fullAddress += resBody.getStatementHeader().getAddress().getAddress3() != null ? resBody.getStatementHeader().getAddress().getAddress3() + ONE_LINE : "";
fullAddress += countryAddress;
String header = fullName + ONE_LINE + fullAddress;
Integer currentIndex = 0;
Integer count = 0;
Integer cutOff = 0;
Integer pageNumber = 1;
Integer numberOfPages = statementsUtils.calculateNumberOfPages(transactionList, currentIndex, cutOff, count);
String pageOf;
PDDocument activeDocument = new PDDocument();
statementsUtils.setFirstPage(transactionList, resBody, doc, header, maskedCard(cardNumber), generationDate, numberOfPages);
try {
while (currentIndex < transactionList.size()) {
Boolean fourOrFive = false;
Boolean checkpoint = false;
Boolean finalPrint = false;
if (count == 4) {
checkpoint = statementsUtils.reachedCheckpoint(currentIndex, transactionList);
if (checkpoint) {
cutOff = currentIndex;
fourOrFive = true;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
statementsUtils.addExtraPage(doc, activeDocument, cutOff, fourOrFive, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate);
count = 0;
}
} else if (count == 5) {
cutOff = currentIndex;
fourOrFive = false;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
statementsUtils.addExtraPage(doc, activeDocument, cutOff, fourOrFive, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate);
count = 0;
} else if (transactionList.size() <= 2) {
finalPrint = true;
} else if (transactionList.size() - currentIndex + 1 <= 5) { // count <4? print last page or count >=4 print 4 and check homuch left
finalPrint = true;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
if (transactionList.size() - currentIndex + 1 == 5) {
statementsUtils.setPreLastPage(doc, activeDocument, currentIndex, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate);
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
statementsUtils.setLastPage(doc, activeDocument, transactionList.size() - 1, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate);
} else {
statementsUtils.setLastPage(doc, activeDocument, currentIndex - count + 1, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate);
}
}
if (fourOrFive && !finalPrint)
currentIndex = cutOff + 1;
else if (finalPrint)
currentIndex = transactionList.size();
else
currentIndex++;
if (currentIndex >= 2) count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (activeDocument != null) {
activeDocument.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
contentStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (doc != null) {
doc.save(out);
doc.close();
}
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return in;
}
}
public void setFirstPage( PDDocument doc,....){
PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
...
acroForm.flatten();
}
public void setPreLastPage( PDDocument doc, PDDocument activeDocument....){
activeDocument = new PDDocument().load(getClass().getClassLoader().getResourceAsStream(pdf));
PDDocumentCatalog docCatalog = activeDocument.getDocumentCatalog();
PDPage p1 = docCatalog.getPages().get(0);
PDAcroForm acroForm = docCatalog.getAcroForm();
...
acroForm.flatten();
PDPageContentStream cs = new PDPageContentStream(activeDocument, p1,PDPageContentStream.AppendMode.APPEND, true);
cs.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
activeDocument.save(out);
doc.addPage(p1);
}
public void setLastPage( PDDocument doc, PDDocument activeDocument....){
activeDocument = new PDDocument().load(getClass().getClassLoader().getResourceAsStream(pdf));
PDDocumentCatalog docCatalog = activeDocument.getDocumentCatalog();
PDPage p1 = docCatalog.getPages().get(0);
PDAcroForm acroForm = docCatalog.getAcroForm();
...
acroForm.flatten();
PDPageContentStream cs = new PDPageContentStream(activeDocument, p1,PDPageContentStream.AppendMode.APPEND, true);
cs.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
activeDocument.save(out);
doc.addPage(p1);
}
public void addExtraPage( PDDocument doc, PDDocument activeDocument....){
activeDocument = new PDDocument().load(getClass().getClassLoader().getResourceAsStream(pdf));
PDDocumentCatalog docCatalog = activeDocument.getDocumentCatalog();
PDPage p1 = docCatalog.getPages().get(0);
PDAcroForm acroForm = docCatalog.getAcroForm();
...
acroForm.flatten();
PDPageContentStream cs = new PDPageContentStream(activeDocument, p1,PDPageContentStream.AppendMode.APPEND, true);
cs.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
activeDocument.save(out);
doc.addPage(p1);
}
There is a lot more logic in these functions but I tried adding only what I thought is relevant.
I believe the issue is concerning either the content stream of one of the pdfs or the order in which I close, save etc.... but I couldn't figure out what the exact issue is so any advice would be appreciated.
Three errors are in setPreLastPage, setLastPage, and addExtraPage: in each of these methods you load a new PDDocument in the respective local variable activeDocument, take a page from it and add it to the same PDDocument doc, and then drop all references to that PDDocument in activeDocument when leaving the respective method.
Dropping all references allows the garbage collection to pick these PDDocument instances up and close and remove them. This pulls away the data underneath the pages copied into the PDDocument doc, resulting in the error you observe when trying to save doc.
To prevent this either clone the page objects into doc before adding them or keep all these temporary documents open until you save doc.
In case anyone is curious of the actual implementation of the solution I created an empty list.
List<PDDocument> activeDocuments = new ArrayList<PDDocument>();
And then everytime I called one of the methods I returned the document and stored it inside of the list and then closed them all at the end after I saved the original document.
while (currentIndex < transactionList.size()) {
Boolean fourOrFive = false;
Boolean checkpoint = false;
Boolean finalPrint = false;
if (count == 4) {
checkpoint = statementsUtils.reachedCheckpoint(currentIndex, transactionList);
if (checkpoint) {
cutOff = currentIndex;
fourOrFive = true;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
activeDocuments.add(statementsUtils.addExtraPage(doc, activeDocument, cutOff, fourOrFive, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate));
count = 0;
}
} else if (count == 5) {
cutOff = currentIndex;
fourOrFive = false;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
activeDocuments.add(statementsUtils.addExtraPage(doc, activeDocument, cutOff, fourOrFive, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate));
count = 0;
} else if (transactionList.size() <= 2) {
finalPrint = true;
} else if (transactionList.size() - currentIndex + 1 <= 5) { // count <4? print last page or count >=4 print 4 and check homuch left
finalPrint = true;
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
if (transactionList.size() - currentIndex + 1 == 5) {
activeDocuments.add(statementsUtils.setPreLastPage(doc, activeDocument, currentIndex, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate));
pageNumber++;
pageOf = "Page " + pageNumber.toString() + " of " + numberOfPages.toString();
activeDocuments.add(statementsUtils.setLastPage(doc, activeDocument, transactionList.size() - 1, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate));
} else {
activeDocuments.add(statementsUtils.setLastPage(doc, activeDocument, currentIndex - count + 1, transactionList, resBody, pageOf, pdf, header, maskedCard(cardNumber), generationDate));
}
}
if (fourOrFive && !finalPrint)
currentIndex = cutOff + 1;
else if (finalPrint)
currentIndex = transactionList.size();
else
currentIndex++;
if (currentIndex >= 2) count++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
contentStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (doc != null) {
doc.save(out);
doc.close();
}
for (PDDocument a : activeDocuments)
a.close();
if (activeDocument != null) {
activeDocument.close();
}
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return in;
}

Saving scraped data to file

Im scraping data from multiple web pages using Jsoup, how can I get the scraped data to save to file without it overwriting the previous webpage that got scraped
I've tried searching on stack overflow and Jsoup docs for a solution.
int j = 0;
int i = 0;
String URL = ("https://www.ufc.com/athletes/all?gender=All&search=&page="+j);
Document doc = Jsoup.connect(URL).userAgent("mozilla/70.0.1").get();
Elements temp = doc.select("div.c-listing-athlete__text");
for (Element fighterList:temp) {
i++;
System.out.println(i + " " + fighterList.getElementsByClass("c-listing-athlete__name").first().text());
}
j++;
URL = ("https://www.ufc.com/athletes/all?gender=All&search=&page="+j);
doc = Jsoup.connect(URL).userAgent("mozilla/70.0.1").get();
temp = doc.select("div.c-listing-athlete__text");
for (Element fighterList:temp) {
i++;
System.out.println(i + " " + fighterList.getElementsByClass("c-listing-athlete__name").first().text());
}
If you need to save the data from code, just check this, maybe it can help you:
int i = 0;
int pagesNumber = 10;
String URL = "";
Document doc = null;
Elements temp = null;
try {
// Create file
FileWriter fstream = new FileWriter(System.currentTimeMillis() + "out.txt");
BufferedWriter out = new BufferedWriter(fstream);
for (i=0; i<pagesNumber; i++) {
URL = ("https://www.ufc.com/athletes/all?gender=All&search=&page="+i);
doc = Jsoup.connect(URL).userAgent("mozilla/70.0.1").get();
temp = doc.select("div.c-listing-athlete__text");
for (Element fighter : temp) {
out.write(i + " " + fighter.getElementsByClass("c-listing-athlete__name").first().text());
}
}
//Close the output stream
out.close();
} catch (Exception e) { // Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Hope it helps :)

Writing GPX file to sdcard from geopoints (ArrayList)

My application tracks the distance and shows the result in km on the screen. I save the geopoints in an ArrayList. I’d like to export the geopoints as a GPX track file to my sdcard.
I tried https://sourceforge.net/projects/gpxparser/. But after the command GPXParser p = new GPXParser(); my app crashes. (I couldn’t find out how to “instantiate the GPXParser class”, maybe that’s why it didn’t work).
Importing GPX files works flawless with this approach http://android-coding.blogspot.de/2013/01/get-latitude-and-longitude-from-gpx-file.html
Could anyone point me in a direction or give me a hint. I’ve search a lot, but couldn’t find anything I could get to work.
Update!
I've found a solution. Maybe not perfect, but it works.
To save my track, I use the following from my Map-Activity.
Maybe some has a better solution :-).
public void saveRoute(String filename) {
Toast.makeText(this, mTrace.size() + "", Toast.LENGTH_SHORT).show();
String fileName = filename;
// routeFile = new File(getFilesDir(), FILENAME);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/kml");
myDir.mkdirs();
File file = new File(myDir, fileName + ".gpx");
savegpx gpxFile = new savegpx();
try {
file.createNewFile();
gpxFile.writePath(file, fileName, mTrace);
// Log.i(TAG, "Route Saved " + file.getName());
} catch (Exception e) {
Log.e("WritingFile", "Not completed writing" + file.getName());
}
}
Separate class
public class savegpx {
private static final String TAG = savegpx.class.getName();
public savegpx() {
}
/**
* Writes locations to gpx file format
*
* #param file file for the gpx
* #param n name for the file
* #param points List of locations to be written to gpx format
*/
public static void writePath(File file, String n, ArrayList<GeoPoint> points) {
final Context applicationContext= MainActivity.getContextOfApplication();
String header = "<gpx creator=\"Off-Road Tracker\" version=\"1.1\" xmlns=\"http://www.topografix.com/GPX/1/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n";
String metadata = " <metadata>\n" + " <time>1900-01-01T00:00:00Z</time>" + "\n </metadata>";
String name = " <trk>\n <name>" + n + "</name>\n <trkseg>\n";
String segments = "";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
List<String> stockList = new ArrayList<String>();
for (int i = 0; i < points.size(); i++) {
stockList.add(" <trkpt lat=\"" + (points.get(i)).getLatitude() + "\" lon=\"" + (points.get(i)).getLongitude() + "\">\n <ele>" +(points.get(i).getAltitude()) + "</ele>\n <time>" + df.format(new Date()) + "Z</time>\n </trkpt>\n");
}
segments +=stockList;
segments = segments.replace(",","");
segments = segments.replace("[","");
segments = segments.replace("]","");
Toast.makeText(applicationContext, segments, Toast.LENGTH_LONG).show();
String footer = " </trkseg>\n </trk>\n</gpx>";
try {
FileWriter writer = new FileWriter(file);
writer.append(header);
writer.append(metadata);
writer.append(name);
writer.append(segments);
writer.append(footer);
writer.flush();
writer.close();
Log.i(TAG, "Saved " + points.size() + " points.");
} catch (IOException e) {
//Toast.makeText(mapsActivity.getApplicationContext(),"File not found",Toast.LENGTH_SHORT);
Log.e(TAG, "Error Writting Path", e);
}
}
}

Data is not in the file created

I have been trying to get data in the file but somehow i am not able to get the data in file, any suggestion is highly appreciated.
File is created as per the requirement, but they are empty.I ahve been trying to fix it by trying various things but it doesnt seem to work.
public class Node {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
// handling the argument and placing it in respective variables for
// further use
int fromNode = 0;
int toNode = 0;
String message = null;
int timeAfter = 0;
// Write a message to the respective node after particular time interval
// to the respective node after
// message example node 2 9 "message" 20 & i.e node x node y the message
// and
for (int i = 0; i < args.length; i++) {
fromNode = Integer.parseInt(args[0]);
toNode = Integer.parseInt(args[1]);
message = args[2];
timeAfter = Integer.parseInt(args[3]);
}
System.out.println("from Node :" + fromNode);
System.out.println("to Node :" + toNode);
System.out.println("message :" + message);
System.out.println("time after which :" + timeAfter);
// ******************************************************************
// opening and closing the file for required appending the content to
// those files
try {
String data = message;
File fileTo = new File(File.separator + "Users"
+ File.separator + "Desktop" + File.separator
+ "Files" + File.separator + "to" + toNode + ".txt");
File fileFrom = new File(File.separator + "Users"
+ File.separator + "Desktop" + File.separator
+ "Files" + File.separator + "from" + fromNode + ".txt");
// if file does not exists, then create it
if (!fileTo.exists()) {
fileTo.createNewFile();
}
if (!fileFrom.exists()) {
fileFrom.createNewFile();
}
// true = append file
FileWriter fileWritter = new FileWriter(fileTo.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.flush();
bufferWritter.close();
FileWriter fileWritterfrom = new FileWriter(fileFrom.getName(),
true);
// System.out.println("------>"+data);
BufferedWriter bufferWritterfrom = new BufferedWriter(
fileWritterfrom);
bufferWritterfrom.write(data);
bufferWritterfrom.flush();
bufferWritterfrom.close();
System.out.println("Files have been created");
} catch (IOException e) {
e.printStackTrace();
}
// ******************************************************************
I guess, the files were written, but not at the place you expected. The call fileTo.getName() just gives you the last component of the path. So you wrote to a file with name to<some number>.txt in the current directory.
Try to use just
FileWriter fileWritter = new FileWriter(fileTo, true);
This should write to the file at the full path.
Btw. it is not necessary to create the files first.

Java FTP file get issue

I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time

Categories

Resources