Java tutorial
package edu.byu.softwareDist.manager.impl; import edu.byu.softwareDist.dao.LicenseDao; import edu.byu.softwareDist.dao.LicenseSetDao; import edu.byu.softwareDist.dao.ProductDao; import edu.byu.softwareDist.domain.License; import edu.byu.softwareDist.domain.LicenseSet; import edu.byu.softwareDist.domain.LicenseSetType; import edu.byu.softwareDist.domain.Product; import edu.byu.softwareDist.manager.SendEmail; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.*; /** * Author: Wyatt Taylor (wyatt_taylor@byu.edu) * Date: 08/13/2013 * * @author Wyatt Taylor (wyatt_taylor@byu.edu) * @since 08/13/2013 */ @Service("licenseCountChecker") public class LicenseCountChecker implements Runnable { private static final Logger LOG = Logger.getLogger(LicenseCountChecker.class); private static final Set<Product> TO_CHECK = Collections .synchronizedSet(new LinkedHashSet<Product>(512, .999999f)); @Autowired @Qualifier("licenseDao") protected LicenseDao licenseDao; @Autowired @Qualifier("productDao") protected ProductDao productDao; @Autowired @Qualifier("licenseSetDao") protected LicenseSetDao licenseSetDao; @Autowired @Qualifier("sendEmail") protected SendEmail sendEmail; public void addProductsToSet(final Collection<Product> products) { TO_CHECK.addAll(products); } @Override public void run() { while (true) { try { final Iterator<Product> iter = TO_CHECK.iterator(); while (iter.hasNext()) { final Product p = iter.next(); try { actuallyCheckingLicenseLeft(p); } catch (final Throwable t) { LOG.error("Error checking for licenses for product " + p, t); } iter.remove(); } } catch (final Throwable t) { LOG.error("Error checking for no licenses left.", t); } try { Thread.sleep(5000); } catch (InterruptedException e) { } } } private void actuallyCheckingLicenseLeft(final Product p) { int qtyAvailable = 0; final List<LicenseSet> licenseSets = licenseSetDao.findAllByProduct(p); if (licenseSets.size() == 0) { return; } for (final LicenseSet ls : licenseSets) { if (ls.getSetType() == LicenseSetType.UNLIMIT_NO_KEY || ls.getSetType() == LicenseSetType.UNLIMIT_KEY) { return; } final List<License> licenses = licenseDao.findAllByLicenseSetId(ls.getLicenseSetId()); for (final License l : licenses) { qtyAvailable += l.getQtyAvailable(); } } if (qtyAvailable <= 5) { sendEmail.sendEmail(p.getName(), qtyAvailable); } if (qtyAvailable <= 0) { p.setOpenForPurchase(false); productDao.update(p, "SYSTEM"); } } }