@Test
  public void getProductByDownloadableFilename() {
    fr.gael.dhus.database.object.Collection validCollection;
    fr.gael.dhus.database.object.Collection invalidCollection;
    Product product;

    validCollection = new Collection();
    validCollection.setUUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa3");
    validCollection.setName("Japan");

    invalidCollection = new Collection();
    invalidCollection.setUUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa4");
    invalidCollection.setName("China");

    product = dao.getProductByDownloadableFilename("prod0", validCollection);
    Assert.assertNotNull(product);
    Assert.assertEquals(product.getId().intValue(), 0);

    product = dao.getProductByDownloadableFilename("prod6", validCollection);
    Assert.assertNull(product);

    product = dao.getProductByDownloadableFilename("prod0", invalidCollection);
    Assert.assertNull(product);

    product = dao.getProductByDownloadableFilename("prod6", null);
    Assert.assertNotNull(product);
    Assert.assertEquals(product.getId().intValue(), 6);

    product = dao.getProductByDownloadableFilename(null, null);
    Assert.assertNull(product);
  }
 @Override
 public void first() {
   String hql = "FROM Product WHERE processed IS FALSE ORDER BY id DESC";
   Product product = dao.first(hql);
   Assert.assertNotNull(product);
   Assert.assertEquals(product.getId().intValue(), 4);
 }
  public void addProduct(
      URL path,
      User owner,
      final List<Collection> collections,
      String origin,
      Scanner scanner,
      FileScannerWrapper wrapper)
      throws DataStoreAlreadyExistException {
    if (productDao.exists(path)) {
      throw new DataStoreAlreadyExistException(
          "Product \"" + path.toExternalForm() + "\" already present in the system.");
    }

    /* **** CRITICAL SECTION *** */
    /** THIS SECTION SHALL NEVER BE STOPPED BY CNTRL-C OR OTHER SIGNALS */
    /* TODO: check if shutdownHook can protect this section */
    Product product = new Product();
    product.setPath(path);
    product.setOrigin(origin);
    List<User> users = new ArrayList<User>();

    if (owner != null) {
      product.setOwner(owner);
      users.add(userDao.read(owner.getId()));
      product.setAuthorizedUsers(new HashSet<User>(users));
    }

    product = productDao.create(product);

    // FIX
    product = productDao.read(product.getId());
    /* **** CRITICAL SECTION *** */
    processProduct(product, owner, collections, scanner, wrapper);
  }
  @Test
  public void getProductByUuid() {
    String valid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa6";
    String invalid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb6";
    User user = new User();
    user.setUUID("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0");
    user.setUsername("koko");

    Product product = dao.getProductByUuid(valid);
    Assert.assertNotNull(product);
    Assert.assertEquals(product.getId().intValue(), 6);

    product = dao.getProductByUuid(invalid);
    Assert.assertNull(product);

    product = dao.getProductByUuid(valid);
    Assert.assertNotNull(product);
    Assert.assertEquals(product.getId().intValue(), 6);

    product = dao.getProductByUuid(null);
    Assert.assertNull(product);
  }
  /**
   * Do process all products in database that their ingestion is not finished. If provided parameter
   * is null, default processing consists in removing the data from database. Otherwise, the
   * provided processing is launched.
   *
   * @param proc the processing to execute. if null, remove processing will be performed.
   * @return the list of products reprocessed.
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  @CacheEvict(
      value = {"product_count", "product", "products"},
      allEntries = true)
  public void processUnprocessed(boolean recover) {
    long start = new Date().getTime();

    if (!recover) {
      Iterator<Product> products = getUnprocessedProducts();
      while (products.hasNext()) {
        products.next();
        products.remove();
      }

      logger.debug(
          "Cleanup incomplete processed products in " + (new Date().getTime() - start) + "ms");
    } else {
      Iterator<Product> products = getUnprocessedProducts();
      while (products.hasNext()) {
        Product product = products.next();
        // Do reporcess only already transfered products
        if (product.getPath().toString().equals(product.getOrigin())) {
          products.remove();
        } else {
          try {
            String path = product.getPath().getPath();
            logger.info("Recovering product from " + path);
            // Check if product is still present in repository
            if (!new File(path).exists()) {
              throw new DataStoreException("Product " + path + " not present locally.");
            }
            // Retrieve owner if any
            User owner = productDao.getOwnerOfProduct(product);

            // Retrieve collections
            List<Collection> collections = collectionDao.getCollectionsOfProduct(product.getId());

            processProduct(product, owner, collections, null, null);
          } catch (Exception e) {
            logger.error("Error while processing: " + e.getMessage() + "- abort reprocessing.");
            products.remove();
          }
        }
      }
    }
  }
  @Test
  public void getProductByPath() {
    URL valid = null;
    URL invalid = null;
    try {
      valid = new URL("file:/home/lambert/test/prod5");
      invalid = new URL("file:/home/lambert/test/prod512");
    } catch (MalformedURLException e) {
      Assert.fail("Malformed URL !", e);
    }

    Product product = dao.getProductByPath(valid);
    Assert.assertNotNull(product);
    Assert.assertEquals(product.getId().intValue(), 5);

    product = dao.getProductByPath(invalid);
    Assert.assertNull(product);

    product = dao.getProductByPath(null);
    Assert.assertNull(product);
  }
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Caching(
        evict = {
          @CacheEvict(value = "product", allEntries = true),
          @CacheEvict(value = "products", allEntries = true)
        })
    @IncrementCache(name = "product_count", key = "all", value = 1)
    public void run() {
      if (scanner != null && scanner.isStopped()) {
        logger.info("Scanner stopped, deleting product #" + product.getId());
        if (wrapper != null) {
          wrapper.error(product, new InterruptedException("Processing stopped by the user"));
        }
        productDao.delete(product);
        return;
      }
      logger.debug("Add product \"" + ProductDao.getPathFromProduct(product) + "\".");

      try {
        long processing_start = System.currentTimeMillis();

        if (wrapper != null) {
          wrapper.startIngestion();
        }

        processingManager.process(product);
        productDao.update(product);
        searchService.index(product);

        if (collections != null) {
          for (Collection c : collections) {
            collectionService.systemAddProduct(c.getId(), product.getId(), true);
          }
        }

        if (wrapper != null) {
          wrapper.endIngestion();
        }

        long processing_end = System.currentTimeMillis();
        logger.info(
            "Ingestion processing complete for product "
                + product.getPath().toExternalForm()
                + " ("
                + product.getSize()
                + " bytes, "
                + product.getDownloadableSize()
                + " bytes compressed)"
                + " in "
                + (processing_end - processing_start)
                + "ms.");

        actionRecordWritterDao.uploadEnd(
            this.product.getPath(), this.owner.getUsername(), collections, true);
      } catch (Exception excp) {
        logger.warn(
            "Unrecoverable error happen during ingestion of "
                + product.getPath()
                + " (removing from database)",
            excp);
        try {
          productDao.delete(product);
        } catch (Exception e) {
          logger.error("Unable to remove product after ingestion failure", e);
        }
        if (wrapper != null) {
          wrapper.error(product, excp);
        }

        if ((this.product.getPath() != null) && (this.owner != null)) {
          actionRecordWritterDao.uploadFailed(
              this.product.getPath().toString(), this.owner.getUsername());
          actionRecordWritterDao.uploadEnd(
              this.product.getPath(), this.owner.getUsername(), collections, false);
        }
        return;
      }
    }