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