001package fr.ifremer.adagio.core.service.technical;
002
003/*
004 * #%L
005 * SIH-Adagio :: Shared
006 * $Id:$
007 * $HeadURL:$
008 * %%
009 * Copyright (C) 2012 - 2014 Ifremer
010 * %%
011 * This program is free software: you can redistribute it and/or modify
012 * it under the terms of the GNU Affero General Public License as published by
013 * the Free Software Foundation, either version 3 of the License, or
014 * (at your option) any later version.
015 * 
016 * This program is distributed in the hope that it will be useful,
017 * but WITHOUT ANY WARRANTY; without even the implied warranty of
018 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
019 * GNU General Public License for more details.
020 * 
021 * You should have received a copy of the GNU Affero General Public License
022 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
023 * #L%
024 */
025
026
027import java.io.FileNotFoundException;
028import java.io.IOException;
029import java.util.Arrays;
030import java.util.List;
031
032import org.apache.commons.lang3.ArrayUtils;
033import org.apache.commons.logging.Log;
034import org.apache.commons.logging.LogFactory;
035import org.springframework.context.ApplicationContext;
036import org.springframework.core.io.Resource;
037
038import com.google.common.base.Preconditions;
039import com.google.common.collect.Lists;
040
041public class SpringUtils {
042    /** Logger. */
043    private static final Log log = LogFactory.getLog(SpringUtils.class);
044
045    
046    protected SpringUtils() {
047        // Helper class : do not instanciate
048    }
049    
050    public static List<Resource> getResourcesFromPaths(String[] paths, ApplicationContext appContext, boolean checkIfResourceExists) throws IOException, FileNotFoundException {
051        Preconditions.checkArgument(ArrayUtils.isNotEmpty(paths));
052        Preconditions.checkNotNull(appContext);
053        
054        // For each path, retrieve corresponding resources
055        List<Resource> resources = Lists.newArrayList();
056        for (String path : paths) {
057            try {
058                Resource[] pathResources = appContext.getResources(path);
059                resources.addAll(Arrays.asList(pathResources));
060            } catch (IOException e) {
061                throw new IOException(String.format("Error while getting files from path: %s", path), e);
062            }
063        }
064        
065        // Check if all resources exists
066        if (checkIfResourceExists) {
067            for(Resource resource : resources) {
068                if (!resource.exists()) {
069                    throw new FileNotFoundException(String.format("File not found: %s", resource.getFilename()));
070                }
071            }
072        }
073        
074        return resources;
075    }
076}