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