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);
  }
 @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
 @CacheEvict(
     value = {"indexes"},
     key = "#product_id")
 public void setIndexes(Long product_id, List<MetadataIndex> indexes) {
   Product product = productDao.read(product_id);
   product.setIndexes(indexes);
   productDao.update(product);
 }
 @PreAuthorize("hasRole('ROLE_DOWNLOAD')")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product", key = "#id")
 public Product getProductToDownload(Long id) {
   // TODO remove method cause duplicated and not used
   return productDao.read(id);
 }
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(
     value = {"indexes"},
     key = "#product_id")
 public List<MetadataIndex> getIndexes(Long product_id) {
   Product product = productDao.read(product_id);
   Hibernate.initialize(product.getIndexes());
   return product.getIndexes();
 }
 // Check if product present is the DB is still present into the repository.
 @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
 public void checkDBProducts() {
   logger.info("Syncing database with repositories...");
   Iterator<Product> products = productDao.getAllProducts();
   while (products.hasNext()) {
     Product product = products.next();
     if (!ProductService.checkUrl(product.getPath())) {
       logger.info("Removing Product " + product.getPath() + " not found in repository.");
       products.remove();
     } else logger.info("Product " + product.getPath() + " found in repository.");
   }
 }
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  @Caching(
      evict = {
        @CacheEvict(value = "indexes", key = "#pid"),
        @CacheEvict(value = "product", key = "#pid"),
        @CacheEvict(value = "products", allEntries = true)
      })
  @IncrementCache(name = "product_count", key = "all", value = -1)
  public void systemDeleteProduct(Long pid) {
    Product product = productDao.read(pid);

    if (product == null) {
      throw new DataStoreException("Product #" + pid + " not found in the system.");
    }

    if (product.getLocked()) {
      throw new DataStoreException(
          "Cannot delete product #" + pid + ". Product is locked in the system.");
    }
    productDao.delete(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();
          }
        }
      }
    }
  }
    @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;
      }
    }
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product", key = "#id")
 public Product systemGetProduct(Long id) {
   return productDao.read(id);
 }
 @PreAuthorize("isAuthenticated ()")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product", key = "#uuid")
 public Product getProduct(String uuid, User u) {
   return productDao.getProductByUuid(uuid, u);
 }
 @PreAuthorize("hasAnyRole('ROLE_DATA_MANAGER','ROLE_SEARCH')")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product_count", key = "{#filter, null}")
 public Integer count(String filter) {
   return productDao.count(filter, null, null);
 }
 /**
  * Gets a {@link Product} by its {@code UUID} (Unprotected).
  *
  * @param uuid UUID unique identifier
  * @return a {@link Product} or {@code null}
  */
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product", key = "#uuid")
 public Product systemGetProduct(String uuid) {
   return productDao.getProductByUuid(uuid, null);
 }
 @PreAuthorize("hasAnyRole('ROLE_DATA_MANAGER','ROLE_SEARCH')")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "products", key = "#ids")
 public List<Product> getProducts(List<Long> ids) {
   return productDao.read(ids);
 }
 @Transactional(readOnly = true)
 public Iterator<Product> getUnprocessedProducts() {
   return productDao.getUnprocessedProducts();
 }
 @PreAuthorize("isAuthenticated ()")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product_count", key = "'all'")
 public int countAuthorizedProducts() {
   return productDao.count();
 }
 @PreAuthorize("hasRole('ROLE_DATA_MANAGER')")
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 public Iterator<Product> getProducts(String filter, Long collection_id, int skip) {
   return productDao.scrollFiltered(filter.toUpperCase(), collection_id, skip);
 }
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
 @Cacheable(value = "product", key = "#path")
 public Product getProduct(URL path) {
   return productDao.getProductByPath(path);
 }