001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance 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
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.common.base.Charsets;
023import com.google.common.base.MoreObjects;
024import com.google.common.collect.Lists;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.OutputStream;
029import java.net.URL;
030import java.nio.charset.Charset;
031import java.util.List;
032import org.checkerframework.checker.nullness.qual.Nullable;
033
034/**
035 * Provides utility methods for working with resources in the classpath. Note that even though these
036 * methods use {@link URL} parameters, they are usually not appropriate for HTTP or other
037 * non-classpath resources.
038 *
039 * @author Chris Nokleberg
040 * @author Ben Yu
041 * @author Colin Decker
042 * @since 1.0
043 */
044@J2ktIncompatible
045@GwtIncompatible
046@ElementTypesAreNonnullByDefault
047public final class Resources {
048  private Resources() {}
049
050  /**
051   * Returns a {@link ByteSource} that reads from the given URL.
052   *
053   * @since 14.0
054   */
055  public static ByteSource asByteSource(URL url) {
056    return new UrlByteSource(url);
057  }
058
059  /** A byte source that reads from a URL using {@link URL#openStream()}. */
060  private static final class UrlByteSource extends ByteSource {
061
062    private final URL url;
063
064    private UrlByteSource(URL url) {
065      this.url = checkNotNull(url);
066    }
067
068    @Override
069    public InputStream openStream() throws IOException {
070      return url.openStream();
071    }
072
073    @Override
074    public String toString() {
075      return "Resources.asByteSource(" + url + ")";
076    }
077  }
078
079  /**
080   * Returns a {@link CharSource} that reads from the given URL using the given character set.
081   *
082   * @since 14.0
083   */
084  public static CharSource asCharSource(URL url, Charset charset) {
085    return asByteSource(url).asCharSource(charset);
086  }
087
088  /**
089   * Reads all bytes from a URL into a byte array.
090   *
091   * @param url the URL to read from
092   * @return a byte array containing all the bytes from the URL
093   * @throws IOException if an I/O error occurs
094   */
095  public static byte[] toByteArray(URL url) throws IOException {
096    return asByteSource(url).read();
097  }
098
099  /**
100   * Reads all characters from a URL into a {@link String}, using the given character set.
101   *
102   * @param url the URL to read from
103   * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
104   *     predefined constants
105   * @return a string containing all the characters from the URL
106   * @throws IOException if an I/O error occurs.
107   */
108  public static String toString(URL url, Charset charset) throws IOException {
109    return asCharSource(url, charset).read();
110  }
111
112  /**
113   * Streams lines from a URL, stopping when our callback returns false, or we have read all of the
114   * lines.
115   *
116   * @param url the URL to read from
117   * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
118   *     predefined constants
119   * @param callback the LineProcessor to use to handle the lines
120   * @return the output of processing the lines
121   * @throws IOException if an I/O error occurs
122   */
123  @CanIgnoreReturnValue // some processors won't return a useful result
124  @ParametricNullness
125  public static <T extends @Nullable Object> T readLines(
126      URL url, Charset charset, LineProcessor<T> callback) throws IOException {
127    return asCharSource(url, charset).readLines(callback);
128  }
129
130  /**
131   * Reads all of the lines from a URL. The lines do not include line-termination characters, but do
132   * include other leading and trailing whitespace.
133   *
134   * <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
135   * Resources.asCharSource(url, charset).readLines()}.
136   *
137   * @param url the URL to read from
138   * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
139   *     predefined constants
140   * @return a mutable {@link List} containing all the lines
141   * @throws IOException if an I/O error occurs
142   */
143  public static List<String> readLines(URL url, Charset charset) throws IOException {
144    // don't use asCharSource(url, charset).readLines() because that returns
145    // an immutable list, which would change the behavior of this method
146    return readLines(
147        url,
148        charset,
149        new LineProcessor<List<String>>() {
150          final List<String> result = Lists.newArrayList();
151
152          @Override
153          public boolean processLine(String line) {
154            result.add(line);
155            return true;
156          }
157
158          @Override
159          public List<String> getResult() {
160            return result;
161          }
162        });
163  }
164
165  /**
166   * Copies all bytes from a URL to an output stream.
167   *
168   * @param from the URL to read from
169   * @param to the output stream
170   * @throws IOException if an I/O error occurs
171   */
172  public static void copy(URL from, OutputStream to) throws IOException {
173    asByteSource(from).copyTo(to);
174  }
175
176  /**
177   * Returns a {@code URL} pointing to {@code resourceName} if the resource is found using the
178   * {@linkplain Thread#getContextClassLoader() context class loader}. In simple environments, the
179   * context class loader will find resources from the class path. In environments where different
180   * threads can have different class loaders, for example app servers, the context class loader
181   * will typically have been set to an appropriate loader for the current thread.
182   *
183   * <p>In the unusual case where the context class loader is null, the class loader that loaded
184   * this class ({@code Resources}) will be used instead.
185   *
186   * @throws IllegalArgumentException if the resource is not found
187   */
188  @CanIgnoreReturnValue // being used to check if a resource exists
189  // TODO(cgdecker): maybe add a better way to check if a resource exists
190  // e.g. Optional<URL> tryGetResource or boolean resourceExists
191  public static URL getResource(String resourceName) {
192    ClassLoader loader =
193        MoreObjects.firstNonNull(
194            Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());
195    URL url = loader.getResource(resourceName);
196    checkArgument(url != null, "resource %s not found.", resourceName);
197    return url;
198  }
199
200  /**
201   * Given a {@code resourceName} that is relative to {@code contextClass}, returns a {@code URL}
202   * pointing to the named resource.
203   *
204   * @throws IllegalArgumentException if the resource is not found
205   */
206  @CanIgnoreReturnValue // being used to check if a resource exists
207  public static URL getResource(Class<?> contextClass, String resourceName) {
208    URL url = contextClass.getResource(resourceName);
209    checkArgument(
210        url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName());
211    return url;
212  }
213}