View Javadoc
1   package fr.ifremer.quadrige2.core.dao.technical.spring;
2   
3   /*-
4    * #%L
5    * Quadrige2 Core :: Quadrige2 Core Shared
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   * 
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   * 
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  
27  
28  import com.google.common.base.Preconditions;
29  import com.google.common.collect.Lists;
30  import org.apache.commons.lang3.ArrayUtils;
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.springframework.context.ApplicationContext;
34  import org.springframework.core.io.*;
35  import org.springframework.util.Assert;
36  import org.springframework.util.ClassUtils;
37  import org.springframework.util.StringUtils;
38  
39  import java.io.FileNotFoundException;
40  import java.io.IOException;
41  import java.net.MalformedURLException;
42  import java.net.URL;
43  import java.util.Arrays;
44  import java.util.List;
45  
46  /**
47   * <p>Springs class.</p>
48   */
49  public class Springs {
50  	/** Logger. */
51  	private static final Log log = LogFactory.getLog(Springs.class);
52  
53  	
54  	/**
55  	 * <p>Constructor for Springs.</p>
56  	 */
57  	protected Springs() {
58  		// Helper class : do not instanciate
59  	}
60  	
61  	/**
62  	 * <p>getResourcesFromPaths.</p>
63  	 *
64  	 * @param paths an array of {@link java.lang.String} objects.
65  	 * @param appContext a {@link org.springframework.context.ApplicationContext} object.
66  	 * @param checkIfResourceExists a boolean.
67  	 * @return a {@link java.util.List} object.
68  	 * @throws java.io.IOException if any.
69  	 */
70  	public static List<Resource> getResourcesFromPaths(String[] paths, ApplicationContext appContext, boolean checkIfResourceExists) throws IOException {
71  		Preconditions.checkArgument(ArrayUtils.isNotEmpty(paths));
72  		Preconditions.checkNotNull(appContext);
73  		
74  		// For each path, retrieve corresponding resources
75  		List<Resource> resources = Lists.newArrayList();
76  		for (String path : paths) {
77  	        try {
78  	        	Resource[] pathResources = appContext.getResources(path);
79  		        resources.addAll(Arrays.asList(pathResources));
80  	        } catch (IOException e) {
81  	        	throw new IOException(String.format("Error while getting files from path: %s", path), e);
82  	        }
83  		}
84  		
85          // Check if all resources exists
86          if (checkIfResourceExists) {
87  	    	for(Resource resource : resources) {
88  	    		if (!resource.exists()) {
89  	    			throw new FileNotFoundException(String.format("File not found: %s", resource.getFilename()));
90  	    		}
91  	    	}
92          }
93  		
94          return resources;
95  	}
96  	
97  
98      /**
99       * <p>getResource.</p>
100      *
101      * @param location a {@link java.lang.String} object.
102      * @return a {@link org.springframework.core.io.Resource} object.
103      */
104     public static Resource getResource(String location) {
105         Assert.notNull(location, "Location must not be null");
106         if (location.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) {
107             return new ClassPathResource(location.substring(ResourceLoader.CLASSPATH_URL_PREFIX.length()), getClassLoader());
108         }
109         else {
110             try {
111                 // Try to parse the location as a URL...
112                 URL url = new URL(location);
113                 return new UrlResource(url);
114             }
115             catch (MalformedURLException ex) {
116                 // No URL -> resolve as resource path.
117                 return getResourceByPath(location);
118             }
119         }
120     }
121     
122     /**
123      * <p>getResourceByPath.</p>
124      *
125      * @param path a {@link java.lang.String} object.
126      * @return a {@link org.springframework.core.io.Resource} object.
127      */
128     protected static Resource getResourceByPath(String path) {
129         return new ClassPathContextResource(path, getClassLoader());
130     }
131     
132     /**
133      * <p>getClassLoader.</p>
134      *
135      * @return a {@link java.lang.ClassLoader} object.
136      */
137     protected static ClassLoader getClassLoader() {
138         return ClassUtils.getDefaultClassLoader();
139     }
140     
141     protected static class ClassPathContextResource extends ClassPathResource implements ContextResource {
142 
143         public ClassPathContextResource(String path, ClassLoader classLoader) {
144             super(path, classLoader);
145         }
146 
147         @Override
148         public String getPathWithinContext() {
149             return getPath();
150         }
151 
152         @Override
153         public Resource createRelative(String relativePath) {
154             String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
155             return new ClassPathContextResource(pathToUse, getClassLoader());
156         }
157     }
158 
159 }