001/*
002 *  Copyright 2025 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.cms.indexing.solr;
017
018import java.util.Collection;
019import java.util.concurrent.CancellationException;
020import java.util.concurrent.ExecutionException;
021import java.util.concurrent.Future;
022
023import org.slf4j.Logger;
024
025/**
026 * Record to return indexation results: success and error count.
027 * @param successCount number of successful tasks
028 * @param errorCount number of fail tasks
029 */
030public record IndexationResult(int successCount, int errorCount) {
031    /**
032     * Test if the indexation had errors.
033     * @return <code>true</code> if the indexation had errors, <code>false</code> otherwise.
034     */
035    public boolean hasErrors()
036    {
037        return errorCount() > 0;
038    }
039    
040    /**
041     * Check each future of launched tasks and count success and errors.
042     * @param tasks The tasks launched in the executor service
043     * @param logger The logger
044     * @return The indexation result
045     */
046    public static IndexationResult fromTasks(Collection<Future<Void>> tasks, Logger logger)
047    {
048        int successCount = 0;
049        int errorCount = 0;
050        
051        // Now that everything is submitted, we can iterate and wait for result
052        for (Future<Void> task : tasks)
053        {
054            try
055            {
056                task.get();
057                successCount++;
058            }
059            catch (CancellationException | InterruptedException | ExecutionException e)
060            {
061                logger.error("Error during parallel indexation", e);
062                errorCount++;
063            }
064        }
065        
066        return new IndexationResult(successCount, errorCount);
067    }
068}