001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.utils;
014
015import static org.apache.juneau.internal.FileUtils.*;
016
017import java.io.*;
018import java.util.*;
019import java.util.ResourceBundle.*;
020
021/**
022 * Utility class for finding resources for a class.
023 *
024 * <p>
025 * Same as {@link Class#getResourceAsStream(String)} except looks for resources with localized file names.
026 *
027 * <p>
028 * If the <code>locale</code> is specified, then we look for resources whose name matches that locale.
029 * For example, if looking for the resource <js>"MyResource.txt"</js> for the Japanese locale, we will look for
030 * files in the following order:
031 * <ol>
032 *    <li><js>"MyResource_ja_JP.txt"</js>
033 *    <li><js>"MyResource_ja.txt"</js>
034 *    <li><js>"MyResource.txt"</js>
035 * </ol>
036 */
037public class ClasspathResourceFinderSimple implements ClasspathResourceFinder {
038
039   /**
040    * Reusable instance.
041    */
042   public static final ClasspathResourceFinderSimple INSTANCE = new ClasspathResourceFinderSimple();
043
044   private static final ResourceBundle.Control RB_CONTROL = ResourceBundle.Control.getControl(Control.FORMAT_DEFAULT);
045   private static final List<Locale> ROOT_LOCALE = Arrays.asList(Locale.ROOT);
046
047
048   @Override /* ClasspathResourceFinder */
049   public InputStream findResource(Class<?> baseClass, String name, Locale locale) throws IOException {
050      return findClasspathResource(baseClass, name, locale);
051   }
052
053   /**
054    * Workhorse method for retrieving a resource from the classpath.
055    *
056    * <p>
057    * This method can be overridden by subclasses to provide customized handling of resource retrieval from the classpath.
058    *
059    * @param baseClass The base class providing the classloader.
060    * @param name The resource name.
061    * @param locale
062    *    The resource locale.
063    *    <br>If <jk>null</jk>, won't look for localized file names.
064    * @return The resource stream, or <jk>null</jk> if it couldn't be found.
065    * @throws IOException
066    */
067   protected InputStream findClasspathResource(Class<?> baseClass, String name, Locale locale) throws IOException {
068      
069      if (locale == null) 
070         return getResourceAsStream(baseClass, name);
071      
072      for (String n : getCandidateFileNames(name, locale)) {
073         InputStream is = getResourceAsStream(baseClass, n);
074         if (is != null)
075            return is;
076      }
077      return null;
078   }
079
080   private InputStream getResourceAsStream(Class<?> baseClass, String name) {
081      InputStream is = baseClass.getResourceAsStream(name);
082      if (is != null)
083         return is;
084      if (! name.startsWith("/"))
085         is = baseClass.getResourceAsStream("/" + name);
086      if (is != null)
087         return is;
088      return null;
089   }
090
091   /**
092    * Returns the candidate file names for the specified file name in the specified locale.
093    *
094    * <p>
095    * For example, if looking for the <js>"MyResource.txt"</js> file in the Japanese locale, the iterator will return
096    * names in the following order:
097    * <ol>
098    *    <li><js>"MyResource_ja_JP.txt"</js>
099    *    <li><js>"MyResource_ja.txt"</js>
100    *    <li><js>"MyResource.txt"</js>
101    * </ol>
102    *
103    * <p>
104    * If the locale is <jk>null</jk>, then it will only return <js>"MyResource.txt"</js>.
105    *
106    * @param fileName The name of the file to get candidate file names on.
107    * @param l
108    *    The locale.
109    *    <br>If <jk>null</jk>, won't look for localized file names.
110    * @return An iterator of file names to look at.
111    */
112   protected static Iterable<String> getCandidateFileNames(final String fileName, final Locale l) {
113      return new Iterable<String>() {
114         @Override
115         public Iterator<String> iterator() {
116            return new Iterator<String>() {
117               final Iterator<Locale> locales = getCandidateLocales(l).iterator();
118               String baseName, ext;
119
120               @Override
121               public boolean hasNext() {
122                  return locales.hasNext();
123               }
124
125               @Override
126               public String next() {
127                  Locale l2 = locales.next();
128                  if (l2.toString().isEmpty())
129                     return fileName;
130                  if (baseName == null)
131                     baseName = getBaseName(fileName);
132                  if (ext == null)
133                     ext = getExtension(fileName);
134                  return baseName + "_" + l2.toString() + (ext.isEmpty() ? "" : ('.' + ext));
135               }
136               @Override
137               public void remove() {
138                  throw new UnsupportedOperationException();
139               }
140            };
141         }
142      };
143   }
144
145   /**
146    * Returns the candidate locales for the specified locale.
147    *
148    * <p>
149    * For example, if <code>locale</code> is <js>"ja_JP"</js>, then this method will return:
150    * <ol>
151    *    <li><js>"ja_JP"</js>
152    *    <li><js>"ja"</js>
153    *    <li><js>""</js>
154    * </ol>
155    *
156    * @param locale The locale to get the list of candidate locales for.
157    * @return The list of candidate locales.
158    */
159   static final List<Locale> getCandidateLocales(Locale locale) {
160      if (locale == null)
161         return ROOT_LOCALE;
162      return RB_CONTROL.getCandidateLocales("", locale);
163   }
164}