package com.scraper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import com.scraper.model.Image;
import com.scraper.parser.HTMLParser;
public class ImageScraper extends SwingWorker<Void, String> {
private HTMLParser parser;
private CountDownLatch latch;
private DownloaderUI downloader;
private String url;
public ImageScraper(DownloaderUI downloader, String url) {
this.downloader = downloader;
this.url = url;
}
@Override
protected Void doInBackground() throws Exception
{
parser = HTMLParser.parseImages(url);
return null;
}
@Override
protected void done()
{
String path;
if(!parser.hasError() && (path = downloader.getSaveDirectory()) != null)
{
List<ImageJob> queue = new ArrayList<>();
while (parser.hasNextImage())
{
Image image = parser.nextImage();
if(image != null)
{
queue.add(new ImageJob(image, path, downloader
.createProgressBar(image)));
}
}
for (ImageJob download : queue)
{
latch = download.nextLatch(latch);
download.execute();
}
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception
{
latch.await();
return null;
}
@Override
protected void done()
{
downloader.enableForm(true);
JOptionPane.showMessageDialog(null, "Finished!");
}
}.execute();
}
else
{
JOptionPane.showMessageDialog(null, parser.getError());
downloader.enableForm(true);
}
}
}